From a9439e9038b755428b5c5d3d0505c7f66827e9d7 Mon Sep 17 00:00:00 2001 From: Qiang Xue Date: Sun, 25 Dec 2011 11:21:30 -0500 Subject: [PATCH] ... --- docs/code_style.md | 7 +- framework/YiiBase.php | 2 + framework/base/Application.php | 36 ++---- framework/base/Component.php | 51 +++----- framework/base/Dictionary.php | 27 ++-- framework/base/Model.php | 21 +-- framework/base/Module.php | 33 ++--- framework/base/Object.php | 30 ++--- framework/base/Vector.php | 33 ++--- framework/console/Command.php | 15 +-- framework/console/CommandRunner.php | 12 +- framework/console/HelpCommand.php | 6 +- framework/db/ar/ActiveRecord.php | 63 +++------ framework/db/dao/ColumnSchema.php | 3 +- framework/db/dao/Command.php | 38 ++---- framework/db/dao/Connection.php | 27 ++-- framework/db/dao/DataReader.php | 6 +- framework/db/dao/Query.php | 63 +++------ framework/db/dao/QueryBuilder.php | 51 +++----- framework/db/dao/Schema.php | 9 +- framework/db/dao/Transaction.php | 6 +- framework/db/dao/mysql/ColumnSchema.php | 12 +- framework/db/dao/mysql/QueryBuilder.php | 3 +- framework/db/dao/mysql/Schema.php | 9 +- framework/logging/ProfileTarget.php | 9 +- framework/logging/Router.php | 3 +- framework/logging/WebTarget.php | 3 +- framework/util/File.php | 6 +- framework/validators/CaptchaValidator.php | 3 +- framework/validators/CompareValidator.php | 6 +- framework/validators/FileValidator.php | 9 +- framework/validators/RangeValidator.php | 3 +- .../validators/RegularExpressionValidator.php | 3 +- framework/validators/RequiredValidator.php | 6 +- framework/validators/StringValidator.php | 3 +- framework/validators/UniqueValidator.php | 3 +- framework/validators/UrlValidator.php | 6 +- framework/validators/Validator.php | 12 +- framework/yiic.php | 3 +- tests/unit/MysqlTestCase.php | 33 +++++ tests/unit/data/mysql.sql | 144 ++++++++++----------- tests/unit/framework/db/dao/CommandTest.php | 99 +++++++------- tests/unit/framework/db/dao/ConnectionTest.php | 30 ++--- 43 files changed, 383 insertions(+), 564 deletions(-) create mode 100644 tests/unit/MysqlTestCase.php diff --git a/docs/code_style.md b/docs/code_style.md index 2281664..d8a247e 100644 --- a/docs/code_style.md +++ b/docs/code_style.md @@ -15,12 +15,9 @@ class MyClass { public function myClassMethod() { - if($x) - { + if($x) { // do it - } - else - { + } else { // some code } } diff --git a/framework/YiiBase.php b/framework/YiiBase.php index 309d25b..4296288 100644 --- a/framework/YiiBase.php +++ b/framework/YiiBase.php @@ -386,6 +386,8 @@ class YiiBase if ($object instanceof \yii\base\Initable) { $object->init(); } + + return $object; } /** diff --git a/framework/base/Application.php b/framework/base/Application.php index f0f7eaa..7e5abe7 100644 --- a/framework/base/Application.php +++ b/framework/base/Application.php @@ -125,8 +125,7 @@ abstract class Application extends Module if (isset($config['basePath'])) { $this->setBasePath($config['basePath']); unset($config['basePath']); - } - else + } else { $this->setBasePath('protected'); } @@ -211,8 +210,7 @@ abstract class Application extends Module { if ($this->_id !== null) { return $this->_id; - } - else + } else { return $this->_id = sprintf('%x', crc32($this->getBasePath() . $this->name)); } @@ -258,8 +256,7 @@ abstract class Application extends Module { if ($this->_runtimePath !== null) { return $this->_runtimePath; - } - else + } else { $this->setRuntimePath($this->getBasePath() . DIRECTORY_SEPARATOR . 'runtime'); return $this->_runtimePath; @@ -545,8 +542,7 @@ abstract class Application extends Module $url = $this->createUrl($route, $params, $ampersand); if (strpos($url, 'http') === 0) { return $url; - } - else + } else { return $this->getRequest()->getHostInfo($schema) . $url; } @@ -573,13 +569,11 @@ abstract class Application extends Module if ($this->_homeUrl === null) { if ($this->getUrlManager()->showScriptName) { return $this->getRequest()->getScriptUrl(); - } - else + } else { return $this->getRequest()->getBaseUrl() . '/'; } - } - else + } else { return $this->_homeUrl; } @@ -609,8 +603,7 @@ abstract class Application extends Module } if (isset($this->_globalState[$key])) { return $this->_globalState[$key]; - } - else + } else { return $defaultValue; } @@ -638,8 +631,7 @@ abstract class Application extends Module unset($this->_globalState[$key]); $this->_stateChanged = true; } - } - elseif (!isset($this->_globalState[$key]) || $this->_globalState[$key] !== $value) + } elseif (!isset($this->_globalState[$key]) || $this->_globalState[$key] !== $value) { $this->_globalState[$key] = $value; $this->_stateChanged = true; @@ -731,8 +723,7 @@ abstract class Application extends Module // try an error handler if (($handler = $this->getErrorHandler()) !== null) { $handler->handle($event); - } - else + } else { $this->displayException($exception); } @@ -822,8 +813,7 @@ abstract class Application extends Module // try an error handler if (($handler = $this->getErrorHandler()) !== null) { $handler->handle($event); - } - else + } else { $this->displayError($code, $message, $file, $line); } @@ -922,8 +912,7 @@ abstract class Application extends Module } echo ''; - } - else + } else { echo "

PHP Error [$code]

\n"; echo "

$message

\n"; @@ -942,8 +931,7 @@ abstract class Application extends Module echo '

' . get_class($exception) . "

\n"; echo '

' . $exception->getMessage() . ' (' . $exception->getFile() . ':' . $exception->getLine() . ')

'; echo '
' . $exception->getTraceAsString() . '
'; - } - else + } else { echo '

' . get_class($exception) . "

\n"; echo '

' . $exception->getMessage() . '

'; diff --git a/framework/base/Component.php b/framework/base/Component.php index a4d77eb..5d96cb6 100644 --- a/framework/base/Component.php +++ b/framework/base/Component.php @@ -98,18 +98,15 @@ class Component extends Object $getter = 'get' . $name; if (method_exists($this, $getter)) { // read property, e.g. getName() return $this->$getter(); - } - elseif (method_exists($this, $name) && strncasecmp($name, 'on', 2) === 0) { // event, e.g. onClick() + } elseif (method_exists($this, $name) && strncasecmp($name, 'on', 2) === 0) { // event, e.g. onClick() $name = strtolower($name); if (!isset($this->_e[$name])) { $this->_e[$name] = new Vector; } return $this->_e[$name]; - } - elseif (isset($this->_b[$name])) { // behavior + } elseif (isset($this->_b[$name])) { // behavior return $this->_b[$name]; - } - elseif (is_array($this->_b)) { // a behavior property + } elseif (is_array($this->_b)) { // a behavior property foreach ($this->_b as $object) { if ($object->canGetProperty($name)) { return $object->$name; @@ -140,15 +137,13 @@ class Component extends Object $setter = 'set' . $name; if (method_exists($this, $setter)) { // write property return $this->$setter($value); - } - elseif (method_exists($this, $name) && strncasecmp($name, 'on', 2) === 0) { // event + } elseif (method_exists($this, $name) && strncasecmp($name, 'on', 2) === 0) { // event $name = strtolower($name); if (!isset($this->_e[$name])) { $this->_e[$name] = new Vector; } return $this->_e[$name]->add($value); - } - elseif (is_array($this->_b)) { // behavior + } elseif (is_array($this->_b)) { // behavior foreach ($this->_b as $object) { if ($object->canSetProperty($name)) { return $object->$name = $value; @@ -157,8 +152,7 @@ class Component extends Object } if (method_exists($this, 'get' . $name)) { throw new Exception('Setting read-only property: ' . get_class($this) . '.' . $name); - } - else { + } else { throw new Exception('Setting unknown property: ' . get_class($this) . '.' . $name); } } @@ -181,15 +175,12 @@ class Component extends Object $getter = 'get' . $name; if (method_exists($this, $getter)) { // property is not null return $this->$getter() !== null; - } - elseif (method_exists($this, $name) && strncasecmp($name, 'on', 2) === 0) { // has event handler + } elseif (method_exists($this, $name) && strncasecmp($name, 'on', 2) === 0) { // has event handler $name = strtolower($name); return isset($this->_e[$name]) && $this->_e[$name]->getCount(); - } - elseif (isset($this->_b[$name])) { // has behavior + } elseif (isset($this->_b[$name])) { // has behavior return true; - } - elseif (is_array($this->_b)) { + } elseif (is_array($this->_b)) { foreach ($this->_b as $object) { if ($object->canGetProperty($name)) { return $object->$name !== null; @@ -217,15 +208,12 @@ class Component extends Object $setter = 'set' . $name; if (method_exists($this, $setter)) { // write property return $this->$setter(null); - } - elseif (method_exists($this, $name) && strncasecmp($name, 'on', 2) === 0) { // event + } elseif (method_exists($this, $name) && strncasecmp($name, 'on', 2) === 0) { // event unset($this->_e[strtolower($name)]); return; - } - elseif (isset($this->_b[$name])) { // behavior + } elseif (isset($this->_b[$name])) { // behavior return $this->detachBehavior($name); - } - elseif (is_array($this->_b)) { // behavior property + } elseif (is_array($this->_b)) { // behavior property foreach ($this->_b as $object) { if ($object->canSetProperty($name)) { return $object->$name = null; @@ -386,21 +374,17 @@ class Component extends Object foreach ($this->_e[$name] as $handler) { if (is_string($handler) || $handler instanceof \Closure) { call_user_func($handler, $event); - } - elseif (is_callable($handler, true)) { + } elseif (is_callable($handler, true)) { // an array: 0 - object, 1 - method name list($object, $method) = $handler; if (is_string($object)) { // static method call call_user_func($handler, $event); - } - elseif (method_exists($object, $method)) { + } elseif (method_exists($object, $method)) { $object->$method($event); - } - else { + } else { throw new Exception('Event "' . get_class($this) . '.' . $name . '" is attached with an invalid handler.'); } - } - else { + } else { throw new Exception('Event "' . get_class($this) . '.' . $name . '" is attached with an invalid handler.'); } @@ -409,8 +393,7 @@ class Component extends Object return; } } - } - elseif (!$this->hasEvent($name)) { + } elseif (!$this->hasEvent($name)) { throw new Exception('Raising unknown event: ' . get_class($this) . '.' . $name); } } diff --git a/framework/base/Dictionary.php b/framework/base/Dictionary.php index 86be283..80fd168 100644 --- a/framework/base/Dictionary.php +++ b/framework/base/Dictionary.php @@ -114,8 +114,7 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co { if ($key === null) { $this->_d[] = $value; - } - else { + } else { $this->_d[$key] = $value; } } @@ -132,8 +131,7 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co $value = $this->_d[$key]; unset($this->_d[$key]); return $value; - } - else { // the value is null + } else { // the value is null unset($this->_d[$key]); return null; } @@ -151,8 +149,7 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co foreach (array_keys($this->_d) as $key) { $this->remove($key); } - } - else { + } else { $this->_d = array(); } } @@ -194,8 +191,7 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co foreach ($data as $key => $value) { $this->add($key, $value); } - } - else { + } else { throw new Exception('Data must be either an array or an object implementing Traversable.'); } } @@ -230,18 +226,15 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co $d[$key] = $value; } $this->_d = self::mergeArray($this->_d, $d); - } - else { + } else { $this->_d = self::mergeArray($this->_d, $data); } - } - else { + } else { foreach ($data as $key => $value) { $this->add($key, $value); } } - } - else { + } else { throw new Exception('Dictionary data must be an array or an object implementing Traversable.'); } } @@ -317,11 +310,9 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co foreach ($b as $k => $v) { if (is_integer($k)) { isset($a[$k]) ? $a[] = $v : $a[$k] = $v; - } - elseif (is_array($v) && isset($a[$k]) && is_array($a[$k])) { + } elseif (is_array($v) && isset($a[$k]) && is_array($a[$k])) { $a[$k] = self::mergeArray($a[$k], $v); - } - else { + } else { $a[$k] = $v; } } diff --git a/framework/base/Model.php b/framework/base/Model.php index d12a1a8..5b9dc00 100644 --- a/framework/base/Model.php +++ b/framework/base/Model.php @@ -367,8 +367,7 @@ class Model extends Component implements Initable, \IteratorAggregate, \ArrayAcc if (isset($rule[0], $rule[1])) { // attributes, validator type $validator = \yii\validators\Validator::createValidator($rule[1], $this, $rule[0], array_slice($rule, 2)); $validators->add($validator); - } - else { + } else { throw new Exception('Invalid validation rule: a rule must specify both attribute names and validator type.'); } } @@ -456,8 +455,7 @@ class Model extends Component implements Initable, \IteratorAggregate, \ArrayAcc { if ($attribute === null) { return $this->_errors === null ? array() : $this->_errors; - } - else { + } else { return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : array(); } } @@ -496,8 +494,7 @@ class Model extends Component implements Initable, \IteratorAggregate, \ArrayAcc foreach ($error as $e) { $this->_errors[$attribute][] = $e; } - } - else { + } else { $this->_errors[$attribute][] = $error; } } @@ -511,8 +508,7 @@ class Model extends Component implements Initable, \IteratorAggregate, \ArrayAcc { if ($attribute === null) { $this->_errors = array(); - } - else { + } else { unset($this->_errors[$attribute]); } } @@ -547,8 +543,7 @@ class Model extends Component implements Initable, \IteratorAggregate, \ArrayAcc $values[$name] = $this->$name; } } - } - else { + } else { foreach ($this->attributeNames() as $name) { $values[$name] = $this->$name; } @@ -572,8 +567,7 @@ class Model extends Component implements Initable, \IteratorAggregate, \ArrayAcc foreach ($values as $name => $value) { if (isset($attributes[$name])) { $this->$name = $value; - } - elseif ($safeOnly) { + } elseif ($safeOnly) { $this->onUnsafeAttribute($name, $value); } } @@ -639,8 +633,7 @@ class Model extends Component implements Initable, \IteratorAggregate, \ArrayAcc foreach ($validator->attributes as $name) { $unsafe[] = $name; } - } - else { + } else { foreach ($validator->attributes as $name) { $attributes[$name] = true; } diff --git a/framework/base/Module.php b/framework/base/Module.php index 2843fdf..32f79e4 100644 --- a/framework/base/Module.php +++ b/framework/base/Module.php @@ -88,8 +88,7 @@ abstract class Module extends Component { if ($this->hasComponent($name)) { return $this->getComponent($name); - } - else { + } else { return parent::__get($name); } } @@ -105,8 +104,7 @@ abstract class Module extends Component { if ($this->hasComponent($name)) { return $this->getComponent($name) !== null; - } - else { + } else { return parent::__isset($name); } } @@ -176,8 +174,7 @@ abstract class Module extends Component { if ($this->_modulePath !== null) { return $this->_modulePath; - } - else { + } else { return $this->_modulePath = $this->getBasePath() . DIRECTORY_SEPARATOR . 'modules'; } } @@ -248,8 +245,7 @@ abstract class Module extends Component { if (isset($this->_modules[$id]) || array_key_exists($id, $this->_modules)) { return $this->_modules[$id]; - } - elseif (isset($this->_moduleConfig[$id])) + } elseif (isset($this->_moduleConfig[$id])) { $config = $this->_moduleConfig[$id]; if (!isset($config['enabled']) || $config['enabled']) { @@ -258,8 +254,7 @@ abstract class Module extends Component unset($config['class'], $config['enabled']); if ($this === \Yii::$app) { $module = \Yii::createObject($class, $id, null, $config); - } - else + } else { $module = \Yii::createObject($class, $this->getId() . '/' . $id, $this, $config); } @@ -328,8 +323,7 @@ abstract class Module extends Component if (isset($this->_moduleConfig[$id])) { $this->_moduleConfig[$id] = CMap::mergeArray($this->_moduleConfig[$id], $module); - } - else + } else { $this->_moduleConfig[$id] = $module; } @@ -358,8 +352,7 @@ abstract class Module extends Component { if (isset($this->_components[$id])) { return $this->_components[$id]; - } - elseif (isset($this->_componentConfig[$id]) && $createIfNull) + } elseif (isset($this->_componentConfig[$id]) && $createIfNull) { $config = $this->_componentConfig[$id]; if (!isset($config['enabled']) || $config['enabled']) { @@ -383,8 +376,7 @@ abstract class Module extends Component { if ($component === null) { unset($this->_components[$id]); - } - else { + } else { $this->_components[$id] = $component; if (!$component->getIsInitialized()) { $component->init(); @@ -404,8 +396,7 @@ abstract class Module extends Component { if ($loadedOnly) { return $this->_components; - } - else { + } else { return array_merge($this->_componentConfig, $this->_components); } } @@ -447,12 +438,10 @@ abstract class Module extends Component { if ($component instanceof IApplicationComponent) { $this->setComponent($id, $component); - } - elseif (isset($this->_componentConfig[$id]) && $merge) + } elseif (isset($this->_componentConfig[$id]) && $merge) { $this->_componentConfig[$id] = CMap::mergeArray($this->_componentConfig[$id], $component); - } - else + } else { $this->_componentConfig[$id] = $component; } diff --git a/framework/base/Object.php b/framework/base/Object.php index 60b2510..c7b461b 100644 --- a/framework/base/Object.php +++ b/framework/base/Object.php @@ -85,8 +85,7 @@ class Object $getter = 'get' . $name; if (method_exists($this, $getter)) { return $this->$getter(); - } - else { + } else { throw new Exception('Getting unknown property: ' . get_class($this) . '.' . $name); } } @@ -106,11 +105,9 @@ class Object $setter = 'set' . $name; if (method_exists($this, $setter)) { $this->$setter($value); - } - elseif (method_exists($this, 'get' . $name)) { + } elseif (method_exists($this, 'get' . $name)) { throw new Exception('Setting read-only property: ' . get_class($this) . '.' . $name); - } - else { + } else { throw new Exception('Setting unknown property: ' . get_class($this) . '.' . $name); } } @@ -130,8 +127,7 @@ class Object $getter = 'get' . $name; if (method_exists($this, $getter)) { // property is not null return $this->$getter() !== null; - } - else { + } else { return false; } } @@ -152,8 +148,7 @@ class Object $setter = 'set' . $name; if (method_exists($this, $setter)) { // write property $this->$setter(null); - } - elseif (method_exists($this, 'get' . $name)) { + } elseif (method_exists($this, 'get' . $name)) { throw new Exception('Unsetting read-only property: ' . get_class($this) . '.' . $name); } } @@ -254,8 +249,7 @@ class Object if (is_string($_expression_)) { extract($_data_); return eval('return ' . $_expression_ . ';'); - } - else { + } else { $_data_[] = $this; return call_user_func_array($_expression_, $_data_); } @@ -321,17 +315,13 @@ class Object if ($n === 0) { $object = new $class; - } - elseif ($n === 1) { + } elseif ($n === 1) { $object = new $class($args[0]); - } - elseif ($n === 2) { + } elseif ($n === 2) { $object = new $class($args[0], $args[1]); - } - elseif ($n === 3) { + } elseif ($n === 3) { $object = new $class($args[0], $args[1], $args[2]); - } - else { + } else { $r = new \ReflectionClass($class); $object = $r->newInstanceArgs($args); } diff --git a/framework/base/Vector.php b/framework/base/Vector.php index b9e7c93..7c6dadd 100644 --- a/framework/base/Vector.php +++ b/framework/base/Vector.php @@ -103,11 +103,9 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta { if (isset($this->_d[$index])) { return $this->_d[$index]; - } - elseif ($index >= 0 && $index < $this->_c) { // in case the value is null + } elseif ($index >= 0 && $index < $this->_c) { // in case the value is null return $this->_d[$index]; - } - else { + } else { throw new Exception('Index out of range: ' . $index); } } @@ -136,12 +134,10 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta { if ($index === $this->_c) { $this->_d[$this->_c++] = $item; - } - elseif ($index >= 0 && $index < $this->_c) { + } elseif ($index >= 0 && $index < $this->_c) { array_splice($this->_d, $index, 0, array($item)); $this->_c++; - } - else { + } else { throw new Exception('Index out of range: ' . $index); } } @@ -160,8 +156,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta if (($index = $this->indexOf($item)) >= 0) { $this->removeAt($index); return $index; - } - else { + } else { return false; } } @@ -178,14 +173,12 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta $this->_c--; if ($index === $this->_c) { return array_pop($this->_d); - } - else { + } else { $item = $this->_d[$index]; array_splice($this->_d, $index, 1); return $item; } - } - else { + } else { throw new Exception('Index out of range: ' . $index); } } @@ -202,8 +195,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta for ($i = $this->_c - 1; $i >= 0; --$i) { $this->removeAt($i); } - } - else { + } else { $this->_d = array(); $this->_c = 0; } @@ -260,8 +252,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta foreach ($data as $item) { $this->add($item); } - } - else { + } else { throw new Exception('Data must be either an array or an object implementing Traversable.'); } } @@ -281,8 +272,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta foreach ($data as $item) { $this->add($item); } - } - else { + } else { throw new Exception('Data must be either an array or an object implementing Traversable.'); } } @@ -328,8 +318,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta { if ($offset === null || $offset === $this->_c) { $this->insertAt($this->_c, $item); - } - else { + } else { $this->removeAt($offset); $this->insertAt($offset, $item); } diff --git a/framework/console/Command.php b/framework/console/Command.php index 7f8ee57..6f30231 100644 --- a/framework/console/Command.php +++ b/framework/console/Command.php @@ -103,8 +103,7 @@ abstract class Command extends \yii\base\Component $params[]=$options[$name]; else $this->usageError("Option --$name requires a scalar. Array is given."); - } - else if($name==='args') + } else if($name==='args') $params[]=$args; else if($param->isDefaultValueAvailable()) $params[]=$param->getDefaultValue(); @@ -183,11 +182,9 @@ abstract class Command extends \yii\base\Component if(!is_array($options[$name])) $options[$name]=array($options[$name]); $options[$name][]=$value; - } - else + } else $options[$name]=$value; - } - else if(isset($action)) + } else if(isset($action)) $params[]=$arg; else $action=$arg; @@ -299,8 +296,7 @@ abstract class Command extends \yii\base\Component ob_implicit_flush(false); require($_viewFile_); return ob_get_clean(); - } - else + } else require($_viewFile_); } @@ -317,8 +313,7 @@ abstract class Command extends \yii\base\Component $input = readline($message.' '); readline_add_history($input); return $input; - } - else + } else { echo $message.' '; return trim(fgets(STDIN)); diff --git a/framework/console/CommandRunner.php b/framework/console/CommandRunner.php index 1a6ed55..ba2c041 100644 --- a/framework/console/CommandRunner.php +++ b/framework/console/CommandRunner.php @@ -55,8 +55,7 @@ class CommandRunner extends \yii\base\Component { $name=$args[0]; array_shift($args); - } - else + } else $name='help'; if(($command=$this->createCommand($name))===null) @@ -126,15 +125,12 @@ class CommandRunner extends \yii\base\Component $className=substr(basename($this->commands[$name]),0,-4); if(!class_exists($className,false)) require_once($this->commands[$name]); - } - else // an alias + } else // an alias $className=\Yii::import($this->commands[$name]); return new $className($name,$this); - } - else // an array configuration + } else // an array configuration return \Yii::create($this->commands[$name],$name,$this); - } - else if($name==='help') + } else if($name==='help') return new HelpCommand('help',$this); else return null; diff --git a/framework/console/HelpCommand.php b/framework/console/HelpCommand.php index e97ac42..f1d0013 100644 --- a/framework/console/HelpCommand.php +++ b/framework/console/HelpCommand.php @@ -54,15 +54,13 @@ class HelpCommand extends Command echo ' - '.implode("\n - ",$commandNames); echo "\n\nTo see individual command help, use the following:\n"; echo " ".$runner->getScriptName()." help \n"; - } - else + } else { echo "No available commands.\n"; echo "Please define them under the following directory:\n"; echo "\t".\Yii::$app->getCommandPath()."\n"; } - } - else + } else echo $runner->createCommand($name)->getHelp(); } diff --git a/framework/db/ar/ActiveRecord.php b/framework/db/ar/ActiveRecord.php index cff8532..d57079f 100644 --- a/framework/db/ar/ActiveRecord.php +++ b/framework/db/ar/ActiveRecord.php @@ -265,8 +265,7 @@ abstract class ActiveRecord extends \yii\base\Model if ($exists) $save = $this->_related[$name]; $r = array($name => $params); - } - else + } else $r = $name; unset($this->_related[$name]); @@ -291,8 +290,7 @@ abstract class ActiveRecord extends \yii\base\Model else unset($this->_related[$name]); return $results; - } - else + } else return $this->_related[$name]; } @@ -597,8 +595,7 @@ abstract class ActiveRecord extends \yii\base\Model break; } return $model->getAttributeLabel($name); - } - else + } else return $this->generateAttributeLabel($attribute); } @@ -720,8 +717,7 @@ abstract class ActiveRecord extends \yii\base\Model else $this->_related[$name][$index] = $record; } - } - elseif (!isset($this->_related[$name])) + } elseif (!isset($this->_related[$name])) $this->_related[$name] = $record; } @@ -755,8 +751,7 @@ abstract class ActiveRecord extends \yii\base\Model $attrs[$name] = isset($attributes[$name]) ? $attributes[$name] : null; } return $attrs; - } - else + } else return $attributes; } @@ -890,8 +885,7 @@ abstract class ActiveRecord extends \yii\base\Model $event = new CModelEvent($this); $this->onBeforeSave($event); return $event->isValid; - } - else + } else return true; } @@ -921,8 +915,7 @@ abstract class ActiveRecord extends \yii\base\Model $event = new CModelEvent($this); $this->onBeforeDelete($event); return $event->isValid; - } - else + } else return true; } @@ -1063,8 +1056,7 @@ abstract class ActiveRecord extends \yii\base\Model $this->_pk = $this->getPrimaryKey(); $this->afterSave(); return true; - } - else + } else return false; } @@ -1105,11 +1097,9 @@ abstract class ActiveRecord extends \yii\base\Model { $this->_pk = $this->getPrimaryKey(); return true; - } - else + } else return false; - } - else + } else throw new CDbException(Yii::t('yii', 'The active record cannot be updated because it is new.')); } @@ -1139,8 +1129,7 @@ abstract class ActiveRecord extends \yii\base\Model foreach ($counters as $name => $value) $this->$name = $this->$name + $value; return true; - } - else + } else return false; } @@ -1159,11 +1148,9 @@ abstract class ActiveRecord extends \yii\base\Model $result = $this->deleteByPk($this->getPrimaryKey()) > 0; $this->afterDelete(); return $result; - } - else + } else return false; - } - else + } else throw new CDbException(Yii::t('yii', 'The active record cannot be deleted because it is new.')); } @@ -1186,8 +1173,7 @@ abstract class ActiveRecord extends \yii\base\Model $this->_attributes[$name] = $record->$name; } return true; - } - else + } else return false; } @@ -1218,8 +1204,7 @@ abstract class ActiveRecord extends \yii\base\Model foreach ($table->primaryKey as $name) $values[$name] = $this->$name; return $values; - } - else + } else return null; } @@ -1281,8 +1266,7 @@ abstract class ActiveRecord extends \yii\base\Model $criteria->limit = 1; $command = $this->getCommandBuilder()->createFindCommand($this->getTableSchema(), $criteria); return $all ? $this->populateRecords($command->queryAll(), true, $criteria->index) : $this->populateRecord($command->queryRow()); - } - else + } else { $finder = new CActiveFinder($this, $criteria->with); return $finder->query($criteria, $all); @@ -1314,14 +1298,12 @@ abstract class ActiveRecord extends \yii\base\Model } $scope = $v; $params = array(); - } - elseif (is_array($v)) + } elseif (is_array($v)) { $scope = key($v); $params = current($v); } - } - elseif (is_string($k)) + } elseif (is_string($k)) { $scope = $k; $params = $v; @@ -1481,8 +1463,7 @@ abstract class ActiveRecord extends \yii\base\Model $this->_c = null; $finder = new CActiveFinder($this, $criteria->with); return $finder->findBySql($sql, $params); - } - else + } else { $command = $this->getCommandBuilder()->createSqlCommand($sql, $params); return $this->populateRecord($command->queryRow()); @@ -1504,8 +1485,7 @@ abstract class ActiveRecord extends \yii\base\Model $this->_c = null; $finder = new CActiveFinder($this, $criteria->with); return $finder->findAllBySql($sql, $params); - } - else + } else { $command = $this->getCommandBuilder()->createSqlCommand($sql, $params); return $this->populateRecords($command->queryAll()); @@ -1795,8 +1775,7 @@ abstract class ActiveRecord extends \yii\base\Model if ($callAfterFind) $record->afterFind(); return $record; - } - else + } else return null; } diff --git a/framework/db/dao/ColumnSchema.php b/framework/db/dao/ColumnSchema.php index d6b457a..f7566b9 100644 --- a/framework/db/dao/ColumnSchema.php +++ b/framework/db/dao/ColumnSchema.php @@ -94,8 +94,7 @@ class ColumnSchema extends \yii\base\Component if (isset($typeMap[$this->type])) { if ($this->type === 'bigint') { return PHP_INT_SIZE == 8 && !$this->unsigned ? 'integer' : 'string'; - } - elseif ($this->type === 'integer') { + } elseif ($this->type === 'integer') { return PHP_INT_SIZE == 4 && $this->unsigned ? 'string' : 'integer'; } return $typeMap[$this->type]; diff --git a/framework/db/dao/Command.php b/framework/db/dao/Command.php index 68ee314..3715390 100644 --- a/framework/db/dao/Command.php +++ b/framework/db/dao/Command.php @@ -44,6 +44,8 @@ use yii\db\Exception; * ->queryRow(); * ~~~ * + * @property string $sql the SQL statement to be executed + * * @author Qiang Xue * @since 2.0 */ @@ -93,13 +95,11 @@ class Command extends \yii\base\Component $this->connection = $connection; if (is_object($query)) { $this->query = $query; - } - else { + } else { $this->query = new Query; if (is_array($query)) { $this->query->fromArray($query); - } - else { + } else { $this->_sql = $query; } } @@ -200,14 +200,11 @@ class Command extends \yii\base\Component $this->prepare(); if ($dataType === null) { $this->pdoStatement->bindParam($name, $value, $this->connection->getPdoType(gettype($value))); - } - elseif ($length === null) { + } elseif ($length === null) { $this->pdoStatement->bindParam($name, $value, $dataType); - } - elseif ($driverOptions === null) { + } elseif ($driverOptions === null) { $this->pdoStatement->bindParam($name, $value, $dataType, $length); - } - else { + } else { $this->pdoStatement->bindParam($name, $value, $dataType, $length, $driverOptions); } $this->_params[$name] =& $value; @@ -230,8 +227,7 @@ class Command extends \yii\base\Component $this->prepare(); if ($dataType === null) { $this->pdoStatement->bindValue($name, $value, $this->connection->getPdoType(gettype($value))); - } - else { + } else { $this->pdoStatement->bindValue($name, $value, $dataType); } $this->_params[$name] = $value; @@ -270,8 +266,7 @@ class Command extends \yii\base\Component $this->_params = array_merge($this->_params, $params); if ($this->_params === array()) { $paramLog = ''; - } - else { + } else { $paramLog = "\nParameters: " . var_export($this->_params, true); } @@ -285,8 +280,7 @@ class Command extends \yii\base\Component $this->prepare(); if ($params === array()) { $this->pdoStatement->execute(); - } - else { + } else { $this->pdoStatement->execute($params); } $n = $this->pdoStatement->rowCount(); @@ -369,8 +363,7 @@ class Command extends \yii\base\Component $result = $this->queryInternal('fetchColumn', $params); if (is_resource($result) && get_resource_type($result) === 'stream') { return stream_get_contents($result); - } - else { + } else { return $result; } } @@ -408,8 +401,7 @@ class Command extends \yii\base\Component $this->_params = array_merge($this->_params, $params); if ($this->_params === array()) { $paramLog = ''; - } - else { + } else { $paramLog = "\nParameters: " . var_export($this->_params, true); } @@ -436,15 +428,13 @@ class Command extends \yii\base\Component $this->prepare(); if ($params === array()) { $this->pdoStatement->execute(); - } - else { + } else { $this->pdoStatement->execute($params); } if ($method === '') { $result = new DataReader($this); - } - else { + } else { if ($fetchMode === null) { $fetchMode = $this->fetchMode; } diff --git a/framework/db/dao/Connection.php b/framework/db/dao/Connection.php index fc7a535..efdf53a 100644 --- a/framework/db/dao/Connection.php +++ b/framework/db/dao/Connection.php @@ -84,6 +84,15 @@ use yii\db\Exception; * ) * ~~~ * + * @property boolean $active Whether the DB connection is established. + * @property Transaction $currentTransaction The currently active transaction. Null if no active transaction. + * @property Schema $schema The database schema for the current connection. + * @property QueryBuilder $queryBuilder The query builder. + * @property string $lastInsertID The row ID of the last row inserted, or the last value retrieved from the sequence object. + * @property string $driverName Name of the DB driver currently being used. + * @property string $clientVersion The version information of the DB driver. + * @property array $stats The statistical results of SQL executions. + * * @author Qiang Xue * @since 2.0 */ @@ -428,8 +437,7 @@ class Connection extends \yii\base\ApplicationComponent { if ($this->_transaction !== null && $this->_transaction->active) { return $this->_transaction; - } - else { + } else { return null; } } @@ -454,13 +462,11 @@ class Connection extends \yii\base\ApplicationComponent { if ($this->_schema !== null) { return $this->_schema; - } - else { + } else { $driver = $this->getDriverName(); if (isset($this->schemaMap[$driver])) { return $this->_schema = \Yii::createObject($this->schemaMap[$driver], $this); - } - else { + } else { throw new Exception("Connection does not support reading schema for '$driver' database."); } } @@ -503,8 +509,7 @@ class Connection extends \yii\base\ApplicationComponent $this->open(); if (($value = $this->pdo->quote($str)) !== false) { return $value; - } - else { // the driver doesn't support quote (e.g. oci) + } else { // the driver doesn't support quote (e.g. oci) return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'"; } } @@ -546,8 +551,7 @@ class Connection extends \yii\base\ApplicationComponent { if ($this->tablePrefix !== null && strpos($sql, '{{') !== false) { return preg_replace('/{{(.*?)}}/', $this->tablePrefix . '\1', $sql); - } - else { + } else { return $sql; } } @@ -577,8 +581,7 @@ class Connection extends \yii\base\ApplicationComponent { if (($pos = strpos($this->dsn, ':')) !== false) { return strtolower(substr($this->dsn, 0, $pos)); - } - else { + } else { return strtolower($this->getAttribute(\PDO::ATTR_DRIVER_NAME)); } } diff --git a/framework/db/dao/DataReader.php b/framework/db/dao/DataReader.php index 0333397..67d2f59 100644 --- a/framework/db/dao/DataReader.php +++ b/framework/db/dao/DataReader.php @@ -70,8 +70,7 @@ class DataReader extends \yii\base\Object implements \Iterator, \Countable { if ($dataType === null) { $this->_statement->bindColumn($column, $value); - } - else { + } else { $this->_statement->bindColumn($column, $value, $dataType); } } @@ -204,8 +203,7 @@ class DataReader extends \yii\base\Object implements \Iterator, \Countable if ($this->_index < 0) { $this->_row = $this->_statement->fetch(); $this->_index = 0; - } - else { + } else { throw new Exception('DataReader cannot rewind. It is a forward-only reader.'); } } diff --git a/framework/db/dao/Query.php b/framework/db/dao/Query.php index 73e3653..6c30acb 100644 --- a/framework/db/dao/Query.php +++ b/framework/db/dao/Query.php @@ -87,8 +87,7 @@ class Query extends \yii\base\Object foreach ($params as $name => $value) { if (is_integer($name)) { $this->params[] = $value; - } - else { + } else { $this->params[$name] = $value; } } @@ -104,8 +103,7 @@ class Query extends \yii\base\Object if ($this->select !== $query->select) { if ($this->select === '*') { $this->select = $query->select; - } - elseif ($query->select !== '*') { + } elseif ($query->select !== '*') { $select1 = is_string($this->select) ? preg_split('/\s*,\s*/', trim($this->select), -1, PREG_SPLIT_NO_EMPTY) : $this->select; $select2 = is_string($query->select) ? preg_split('/\s*,\s*/', trim($query->select), -1, PREG_SPLIT_NO_EMPTY) : $query->select; $this->select = array_merge($select1, array_diff($select2, $select1)); @@ -115,8 +113,7 @@ class Query extends \yii\base\Object if ($this->selectOption !== $query->selectOption) { if ($this->selectOption === null) { $this->selectOption = $query->selectOption; - } - elseif ($query->selectOption !== null) { + } elseif ($query->selectOption !== null) { $this->selectOption .= ' ' . $query->selectOption; } } @@ -128,8 +125,7 @@ class Query extends \yii\base\Object if ($this->where !== $query->where) { if (empty($this->where)) { $this->where = $query->where; - } - elseif (!empty($query->where)) { + } elseif (!empty($query->where)) { $this->where = array('AND', $this->where, $query->where); } } @@ -149,15 +145,13 @@ class Query extends \yii\base\Object if ($this->orderBy !== $query->orderBy) { if (empty($this->orderBy)) { $this->orderBy = $query->orderBy; - } - elseif (!empty($query->orderBy)) { + } elseif (!empty($query->orderBy)) { if (!is_array($this->orderBy)) { $this->orderBy = array($this->orderBy); } if (is_array($query->orderBy)) { $this->orderBy = array_merge($this->orderBy, $query->orderBy); - } - else { + } else { $this->orderBy[] = $query->orderBy; } } @@ -166,15 +160,13 @@ class Query extends \yii\base\Object if ($this->groupBy !== $query->groupBy) { if (empty($this->groupBy)) { $this->groupBy = $query->groupBy; - } - elseif (!empty($query->groupBy)) { + } elseif (!empty($query->groupBy)) { if (!is_array($this->groupBy)) { $this->groupBy = array($this->groupBy); } if (is_array($query->groupBy)) { $this->groupBy = array_merge($this->groupBy, $query->groupBy); - } - else { + } else { $this->groupBy[] = $query->groupBy; } } @@ -183,15 +175,13 @@ class Query extends \yii\base\Object if ($this->join !== $query->join) { if (empty($this->join)) { $this->join = $query->join; - } - elseif (!empty($query->join)) { + } elseif (!empty($query->join)) { if (!is_array($this->join)) { $this->join = array($this->join); } if (is_array($query->join)) { $this->join = array_merge($this->join, $query->join); - } - else { + } else { $this->join[] = $query->join; } } @@ -200,8 +190,7 @@ class Query extends \yii\base\Object if ($this->having !== $query->having) { if (empty($this->having)) { $this->having = $query->having; - } - elseif (!empty($query->having)) { + } elseif (!empty($query->having)) { $this->having = array('AND', $this->having, $query->having); } } @@ -209,15 +198,13 @@ class Query extends \yii\base\Object if ($this->union !== $query->union) { if (empty($this->union)) { $this->union = $query->union; - } - elseif (!empty($query->union)) { + } elseif (!empty($query->union)) { if (!is_array($this->union)) { $this->union = array($this->union); } if (is_array($query->union)) { $this->union = array_merge($this->union, $query->union); - } - else { + } else { $this->union[] = $query->union; } } @@ -246,8 +233,7 @@ class Query extends \yii\base\Object } if ($this->condition === '') { $this->condition = $condition; - } - else + } else { $this->condition = '(' . $this->condition . ') ' . $operator . ' (' . $condition . ')'; } @@ -309,8 +295,7 @@ class Query extends \yii\base\Object } $condition = $column . '=' . self::PARAM_PREFIX . self::$paramCount; $this->params[self::PARAM_PREFIX . self::$paramCount++] = $value; - } - else + } else { $params = array(); foreach ($values as $value) @@ -347,8 +332,7 @@ class Query extends \yii\base\Object } $condition = $column . '!=' . self::PARAM_PREFIX . self::$paramCount; $this->params[self::PARAM_PREFIX . self::$paramCount++] = $value; - } - else + } else { $params = array(); foreach ($values as $value) @@ -379,8 +363,7 @@ class Query extends \yii\base\Object { if ($value === null) { $params[] = $name . ' IS NULL'; - } - else + } else { $params[] = $name . '=' . self::PARAM_PREFIX . self::$paramCount; $this->params[self::PARAM_PREFIX . self::$paramCount++] = $value; @@ -439,8 +422,7 @@ class Query extends \yii\base\Object return $this; } return $this->addInCondition($column, $value, $operator); - } - else + } else { $value = "$value"; } @@ -448,8 +430,7 @@ class Query extends \yii\base\Object if (preg_match('/^(?:\s*(<>|<=|>=|<|>|=))?(.*)$/', $value, $matches)) { $value = $matches[2]; $op = $matches[1]; - } - else + } else { $op = ''; } @@ -465,8 +446,7 @@ class Query extends \yii\base\Object if ($op === '<>') { return $this->addSearchCondition($column, $value, $escape, $operator, 'NOT LIKE'); } - } - elseif ($op === '') + } elseif ($op === '') { $op = '='; } @@ -506,8 +486,7 @@ class Query extends \yii\base\Object if ($this->condition === '') { $this->condition = $condition; - } - else + } else { $this->condition = '(' . $this->condition . ') ' . $operator . ' (' . $condition . ')'; } diff --git a/framework/db/dao/QueryBuilder.php b/framework/db/dao/QueryBuilder.php index 71badca..8aad9cc 100644 --- a/framework/db/dao/QueryBuilder.php +++ b/framework/db/dao/QueryBuilder.php @@ -88,8 +88,7 @@ class QueryBuilder extends \yii\base\Object foreach ($value->params as $n => $v) { $params[$n] = $v; } - } - else { + } else { $placeholders[] = ':p' . $count; $params[':p' . $count] = $value; $count++; @@ -121,8 +120,7 @@ class QueryBuilder extends \yii\base\Object foreach ($value->params as $n => $v) { $params[$n] = $v; } - } - else { + } else { $lines[] = $this->schema->quoteSimpleColumnName($name) . '=:p' . $count; $params[':p' . $count] = $value; $count++; @@ -175,8 +173,7 @@ class QueryBuilder extends \yii\base\Object foreach ($columns as $name => $type) { if (is_string($name)) { $cols[] = "\t" . $this->schema->quoteColumnName($name) . ' ' . $this->schema->getColumnType($type); - } - else + } else { $cols[] = "\t" . $type; } @@ -340,8 +337,7 @@ class QueryBuilder extends \yii\base\Object { if (strpos($col, '(') !== false) { $cols[] = $col; - } - else + } else { $cols[] = $this->schema->quoteColumnName($col); } @@ -413,12 +409,10 @@ class QueryBuilder extends \yii\base\Object { if (isset($this->typeMap[$type])) { return $this->typeMap[$type]; - } - elseif (($pos = strpos($type, ' ')) !== false) { + } elseif (($pos = strpos($type, ' ')) !== false) { $t = substr($type, 0, $pos); return (isset($this->typeMap[$t]) ? $this->typeMap[$t] : $t) . substr($type, $pos); - } - else { + } else { return $type; } } @@ -445,12 +439,10 @@ class QueryBuilder extends \yii\base\Object foreach ($columns as $i => $column) { if (is_object($column)) { $columns[$i] = (string)$column; - } - elseif (strpos($column, '(') === false) { + } elseif (strpos($column, '(') === false) { if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-\.])$/', $column, $matches)) { $columns[$i] = $this->connection->quoteColumnName($matches[1]) . ' AS ' . $this->connection->quoteSimpleColumnName($matches[2]); - } - else { + } else { $columns[$i] = $this->connection->quoteColumnName($column); } } @@ -473,8 +465,7 @@ class QueryBuilder extends \yii\base\Object if (strpos($table, '(') === false) { if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/i', $table, $matches)) { // with alias $tables[$i] = $this->connection->quoteTableName($matches[1]) . ' ' . $this->connection->quoteTableName($matches[2]); - } - else { + } else { $tables[$i] = $this->connection->quoteTableName($table); } } @@ -500,8 +491,7 @@ class QueryBuilder extends \yii\base\Object if (strpos($table, '(') === false) { if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)(.*)$/', $table, $matches)) { // with alias $table = $this->connection->quoteTableName($matches[1]) . ' ' . $this->connection->quoteTableName($matches[2]); - } - else { + } else { $table = $this->connection->quoteTableName($table); } } @@ -510,8 +500,7 @@ class QueryBuilder extends \yii\base\Object $condition = $this->buildCondition($join[2]); $joins[$i] .= ' ON ' . $condition; } - } - else { + } else { throw new Exception('The join clause may be specified as an array of at least two elements.'); } } @@ -542,8 +531,7 @@ class QueryBuilder extends \yii\base\Object foreach ($columns as $i => $column) { if (is_object($column)) { $columns[$i] = (string)$column; - } - elseif (strpos($column, '(') === false) { + } elseif (strpos($column, '(') === false) { $columns[$i] = $this->connection->quoteColumnName($column); } } @@ -572,12 +560,10 @@ class QueryBuilder extends \yii\base\Object foreach ($columns as $i => $column) { if (is_object($column)) { $columns[$i] = (string)$column; - } - elseif (strpos($column, '(') === false) { + } elseif (strpos($column, '(') === false) { if (preg_match('/^(.*?)\s+(asc|desc)$/i', $column, $matches)) { $columns[$i] = $this->connection->quoteColumnName($matches[1]) . ' ' . strtoupper($matches[2]); - } - else { + } else { $columns[$i] = $this->connection->quoteColumnName($column); } } @@ -618,8 +604,7 @@ class QueryBuilder extends \yii\base\Object { if (!is_array($conditions)) { return $conditions; - } - elseif ($conditions === array()) { + } elseif ($conditions === array()) { return ''; } @@ -657,8 +642,7 @@ class QueryBuilder extends \yii\base\Object foreach ($values as $i => $value) { if (is_string($value)) { $values[$i] = $this->connection->quoteValue($value); - } - else { + } else { $values[$i] = (string)$value; } } @@ -672,8 +656,7 @@ class QueryBuilder extends \yii\base\Object if ($operator === 'LIKE' || $operator === 'NOT LIKE') { $andor = ' AND '; - } - else { + } else { $andor = ' OR '; $operator = $operator === 'OR LIKE' ? 'LIKE' : 'NOT LIKE'; } diff --git a/framework/db/dao/Schema.php b/framework/db/dao/Schema.php index d96bd6c..6f45a5c 100644 --- a/framework/db/dao/Schema.php +++ b/framework/db/dao/Schema.php @@ -58,8 +58,7 @@ abstract class Schema extends \yii\base\Object if (strpos($name, '{{') !== false) { $realName = preg_replace('/\{\{(.*?)\}\}/', $this->connection->tablePrefix . '$1', $name); - } - else { + } else { $realName = $name; } @@ -80,8 +79,7 @@ abstract class Schema extends \yii\base\Object } } $this->_tables[$name] = $table; - } - else { + } else { $this->_tables[$name] = $table = $this->loadTableSchema($realName); } @@ -195,8 +193,7 @@ abstract class Schema extends \yii\base\Object if (($pos = strrpos($name, '.')) !== false) { $prefix = $this->quoteTableName(substr($name, 0, $pos)) . '.'; $name = substr($name, $pos + 1); - } - else + } else { $prefix = ''; } diff --git a/framework/db/dao/Transaction.php b/framework/db/dao/Transaction.php index c4df4dc..0e815f0 100644 --- a/framework/db/dao/Transaction.php +++ b/framework/db/dao/Transaction.php @@ -69,8 +69,7 @@ class Transaction extends \yii\base\Object \Yii::trace('Committing transaction', __CLASS__); $this->connection->pdo->commit(); $this->active = false; - } - else { + } else { throw new Exception('Failed to commit transaction: transaction was inactive.'); } } @@ -85,8 +84,7 @@ class Transaction extends \yii\base\Object \Yii::trace('Rolling back transaction', __CLASS__); $this->connection->pdo->rollBack(); $this->active = false; - } - else { + } else { throw new Exception('Failed to roll back transaction: transaction was inactive.'); } } diff --git a/framework/db/dao/mysql/ColumnSchema.php b/framework/db/dao/mysql/ColumnSchema.php index f9f2b61..bbcd1b6 100644 --- a/framework/db/dao/mysql/ColumnSchema.php +++ b/framework/db/dao/mysql/ColumnSchema.php @@ -69,8 +69,7 @@ class ColumnSchema extends \yii\db\dao\ColumnSchema $values[$i] = trim($value, "'"); } $this->enumValues = $values; - } - else { + } else { $values = explode(',', $matches[2]); $this->size = $this->precision = (int)$values[0]; if (isset($values[1])) { @@ -78,12 +77,10 @@ class ColumnSchema extends \yii\db\dao\ColumnSchema } if ($this->size === 1 && ($type === 'tinyint' || $type === 'bit')) { $this->type = 'boolean'; - } - elseif ($type === 'bit') { + } elseif ($type === 'bit') { if ($this->size > 32) { $this->type = 'bigint'; - } - elseif ($this->size === 32) { + } elseif ($this->size === 32) { $this->type = 'integer'; } } @@ -103,8 +100,7 @@ class ColumnSchema extends \yii\db\dao\ColumnSchema { if ($this->type === 'timestamp' && $defaultValue === 'CURRENT_TIMESTAMP') { $this->defaultValue = null; - } - else { + } else { $this->defaultValue = $this->typecast($defaultValue); } } diff --git a/framework/db/dao/mysql/QueryBuilder.php b/framework/db/dao/mysql/QueryBuilder.php index a53bd9a..0c4791c 100644 --- a/framework/db/dao/mysql/QueryBuilder.php +++ b/framework/db/dao/mysql/QueryBuilder.php @@ -54,8 +54,7 @@ class QueryBuilder extends \yii\db\dao\QueryBuilder throw new CDbException(Yii::t('yii', 'Unable to find "{column}" in table "{table}".', array('{column}' => $name, '{table}' => $table))); if (isset($row['Create Table'])) { $sql = $row['Create Table']; - } - else { + } else { $row = array_values($row); $sql = $row[1]; } diff --git a/framework/db/dao/mysql/Schema.php b/framework/db/dao/mysql/Schema.php index 8edf50f..a98510b 100644 --- a/framework/db/dao/mysql/Schema.php +++ b/framework/db/dao/mysql/Schema.php @@ -68,8 +68,7 @@ class Schema extends \yii\db\dao\Schema $table->schemaName = $parts[0]; $table->name = $parts[1]; $table->quotedName = $this->quoteSimpleTableName($table->schemaName) . '.' . $this->quoteSimpleTableName($table->name); - } - else { + } else { $table->name = $parts[0]; $table->quotedName = $this->quoteSimpleTableName($table->name); } @@ -114,11 +113,9 @@ class Schema extends \yii\db\dao\Schema if ($c->isPrimaryKey) { if ($table->primaryKey === null) { $table->primaryKey = $c->name; - } - elseif (is_string($table->primaryKey)) { + } elseif (is_string($table->primaryKey)) { $table->primaryKey = array($table->primaryKey, $c->name); - } - else { + } else { $table->primaryKey[] = $c->name; } if ($c->autoIncrement) { diff --git a/framework/logging/ProfileTarget.php b/framework/logging/ProfileTarget.php index 39c4172..bdf6c80 100644 --- a/framework/logging/ProfileTarget.php +++ b/framework/logging/ProfileTarget.php @@ -107,8 +107,7 @@ class CProfileLogRoute extends CWebLogRoute if (($last = array_pop($stack)) !== null && $last[0] === $token) { $delta = $log[3] - $last[3]; $results[$last[4]] = array($token, $delta, count($stack)); - } - else + } else { throw new CException(Yii::t('yii', 'CProfileLogRoute found a mismatching code block "{token}". Make sure the calls to Yii::beginProfile() and Yii::endProfile() be properly nested.', array('{token}' => $token))); @@ -140,8 +139,7 @@ class CProfileLogRoute extends CWebLogRoute { $log[0] = substr($message, 6); $stack[] = $log; - } - elseif (!strncasecmp($message, 'end:', 4)) + } elseif (!strncasecmp($message, 'end:', 4)) { $token = substr($message, 4); if (($last = array_pop($stack)) !== null && $last[0] === $token) @@ -153,8 +151,7 @@ class CProfileLogRoute extends CWebLogRoute $results[$token] = $this->aggregateResult($results[$token], $delta); else $results[$token] = array($token, 1, $delta, $delta, $delta); - } - else + } else throw new CException(Yii::t('yii', 'CProfileLogRoute found a mismatching code block "{token}". Make sure the calls to Yii::beginProfile() and Yii::endProfile() be properly nested.', array('{token}' => $token))); } diff --git a/framework/logging/Router.php b/framework/logging/Router.php index 5676643..fb8a293 100644 --- a/framework/logging/Router.php +++ b/framework/logging/Router.php @@ -108,8 +108,7 @@ class Router extends \yii\base\ApplicationComponent foreach ($config as $name => $target) { if ($target instanceof Target) { $this->_targets[$name] = $target; - } - else { + } else { $this->_targets[$name] = \Yii::createObject($target); } } diff --git a/framework/logging/WebTarget.php b/framework/logging/WebTarget.php index ede5d3f..5da59dc 100644 --- a/framework/logging/WebTarget.php +++ b/framework/logging/WebTarget.php @@ -55,8 +55,7 @@ class CWebLogRoute extends CLogRoute if ($isAjax && $this->ignoreAjaxInFireBug) return; $view .= '-firebug'; - } - elseif (!($app instanceof CWebApplication) || $isAjax) + } elseif (!($app instanceof CWebApplication) || $isAjax) return; $viewFile = YII_PATH . DIRECTORY_SEPARATOR . 'views' . DIRECTORY_SEPARATOR . $view . '.php'; diff --git a/framework/util/File.php b/framework/util/File.php index 679305d..b315201 100644 --- a/framework/util/File.php +++ b/framework/util/File.php @@ -79,15 +79,13 @@ class File { echo " overwrite $name\n"; $overwriteAll=true; - } - else + } else { echo " skip $name\n"; continue; } } - } - else + } else { $this->ensureDirectory(dirname($target)); echo " generate $name\n"; diff --git a/framework/validators/CaptchaValidator.php b/framework/validators/CaptchaValidator.php index 97fda69..b29c75b 100644 --- a/framework/validators/CaptchaValidator.php +++ b/framework/validators/CaptchaValidator.php @@ -66,8 +66,7 @@ class CaptchaValidator extends Validator list($controller, $actionID) = $ca; $action = $controller->createAction($actionID); } - } - else { + } else { $action = Yii::app()->getController()->createAction($this->captchaAction); } diff --git a/framework/validators/CompareValidator.php b/framework/validators/CompareValidator.php index 076094c..97febb5 100644 --- a/framework/validators/CompareValidator.php +++ b/framework/validators/CompareValidator.php @@ -77,8 +77,7 @@ class CompareValidator extends Validator } if ($this->compareValue !== null) { $compareTo = $compareValue = $this->compareValue; - } - else { + } else { $compareAttribute = $this->compareAttribute === null ? $attribute . '_repeat' : $this->compareAttribute; $compareValue = $object->$compareAttribute; $compareTo = $object->getAttributeLabel($compareAttribute); @@ -138,8 +137,7 @@ class CompareValidator extends Validator if ($this->compareValue !== null) { $compareTo = $this->compareValue; $compareValue = json_encode($this->compareValue); - } - else { + } else { $compareAttribute = $this->compareAttribute === null ? $attribute . '_repeat' : $this->compareAttribute; $compareValue = "\$('#" . (CHtml::activeId($object, $compareAttribute)) . "').val()"; $compareTo = $object->getAttributeLabel($compareAttribute); diff --git a/framework/validators/FileValidator.php b/framework/validators/FileValidator.php index 448be36..a1ce299 100644 --- a/framework/validators/FileValidator.php +++ b/framework/validators/FileValidator.php @@ -117,12 +117,10 @@ class CFileValidator extends Validator { $message = $this->tooMany !== null ? $this->tooMany : Yii::t('yii', '{attribute} cannot accept more than {limit} files.'); $this->addError($object, $attribute, $message, array('{attribute}' => $attribute, '{limit}' => $this->maxFiles)); - } - else + } else foreach ($files as $file) $this->validateFile($object, $attribute, $file); - } - else + } else { $file = $object->$attribute; if (!$file instanceof CUploadedFile) @@ -149,8 +147,7 @@ class CFileValidator extends Validator { $message = $this->tooLarge !== null ? $this->tooLarge : Yii::t('yii', 'The file "{file}" is too large. Its size cannot exceed {limit} bytes.'); $this->addError($object, $attribute, $message, array('{file}' => $file->getName(), '{limit}' => $this->getSizeLimit())); - } - elseif ($error == UPLOAD_ERR_PARTIAL) + } elseif ($error == UPLOAD_ERR_PARTIAL) throw new CException(Yii::t('yii', 'The file "{file}" was only partially uploaded.', array('{file}' => $file->getName()))); elseif ($error == UPLOAD_ERR_NO_TMP_DIR) throw new CException(Yii::t('yii', 'Missing the temporary folder to store the uploaded file "{file}".', array('{file}' => $file->getName()))); diff --git a/framework/validators/RangeValidator.php b/framework/validators/RangeValidator.php index 24e3504..ab04dbb 100644 --- a/framework/validators/RangeValidator.php +++ b/framework/validators/RangeValidator.php @@ -58,8 +58,7 @@ class RangeValidator extends Validator if (!$this->not && !in_array($value, $this->range, $this->strict)) { $message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} should be in the list.'); $this->addError($object, $attribute, $message); - } - elseif ($this->not && in_array($value, $this->range, $this->strict)) { + } elseif ($this->not && in_array($value, $this->range, $this->strict)) { $message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} should NOT be in the list.'); $this->addError($object, $attribute, $message); } diff --git a/framework/validators/RegularExpressionValidator.php b/framework/validators/RegularExpressionValidator.php index 18a4ed5..a1630ab 100644 --- a/framework/validators/RegularExpressionValidator.php +++ b/framework/validators/RegularExpressionValidator.php @@ -80,8 +80,7 @@ class RegularExpressionValidator extends Validator $flag = substr($pattern, $endpos + 1); if ($delim !== '/') { $pattern = '/' . str_replace('/', '\\/', substr($pattern, 1, $endpos - 1)) . '/'; - } - else { + } else { $pattern = substr($pattern, 0, $endpos + 1); } if (!empty($flag)) { diff --git a/framework/validators/RequiredValidator.php b/framework/validators/RequiredValidator.php index 46ce96d..60677f6 100644 --- a/framework/validators/RequiredValidator.php +++ b/framework/validators/RequiredValidator.php @@ -50,8 +50,7 @@ class RequiredValidator extends Validator $message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} cannot be blank.'); $this->addError($object, $attribute, $message); } - } - else { + } else { if (!$this->strict && $value != $this->requiredValue || $this->strict && $value !== $this->requiredValue) { $message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} must be "{requiredValue}".', array('{requiredValue}' => $this->requiredValue)); @@ -83,8 +82,7 @@ if (value != " . json_encode($this->requiredValue) . ") { messages.push(" . json_encode($message) . "); } "; - } - else { + } else { if ($message === null) { $message = Yii::t('yii', '{attribute} cannot be blank.'); } diff --git a/framework/validators/StringValidator.php b/framework/validators/StringValidator.php index b11af29..45c2c03 100644 --- a/framework/validators/StringValidator.php +++ b/framework/validators/StringValidator.php @@ -83,8 +83,7 @@ class StringValidator extends Validator if (function_exists('mb_strlen') && $this->encoding !== false) { $length = mb_strlen($value, $this->encoding ? $this->encoding : Yii::app()->charset); - } - else { + } else { $length = strlen($value); } diff --git a/framework/validators/UniqueValidator.php b/framework/validators/UniqueValidator.php index ef13e26..c58338b 100644 --- a/framework/validators/UniqueValidator.php +++ b/framework/validators/UniqueValidator.php @@ -104,8 +104,7 @@ class CUniqueValidator extends Validator // non-primary key, need to exclude the current record based on PK $exists = array_shift($objects)->getPrimaryKey() != $object->getOldPrimaryKey(); } - } - else + } else $exists = $n > 1; } diff --git a/framework/validators/UrlValidator.php b/framework/validators/UrlValidator.php index fba3135..52412e7 100644 --- a/framework/validators/UrlValidator.php +++ b/framework/validators/UrlValidator.php @@ -54,8 +54,7 @@ class UrlValidator extends Validator } if (($value = $this->validateValue($value)) !== false) { $object->$attribute = $value; - } - else { + } else { $message = $this->message !== null ? $this->message : Yii::t('yii', '{attribute} is not a valid URL.'); $this->addError($object, $attribute, $message); } @@ -78,8 +77,7 @@ class UrlValidator extends Validator if (strpos($this->pattern, '{schemes}') !== false) { $pattern = str_replace('{schemes}', '(' . implode('|', $this->validSchemes) . ')', $this->pattern); - } - else { + } else { $pattern = $this->pattern; } diff --git a/framework/validators/Validator.php b/framework/validators/Validator.php index e695b5d..7c6851e 100644 --- a/framework/validators/Validator.php +++ b/framework/validators/Validator.php @@ -137,13 +137,11 @@ abstract class Validator extends \yii\base\Component if (isset($params['on'])) { if (is_array($params['on'])) { $on = $params['on']; - } - else { + } else { $on = preg_split('/[\s,]+/', $params['on'], -1, PREG_SPLIT_NO_EMPTY); } $params['on'] = empty($on) ? array() : array_combine($on, $on); - } - else { + } else { $params['on'] = array(); } @@ -153,8 +151,7 @@ abstract class Validator extends \yii\base\Component 'method' => $type, 'attributes' => $attributes, ); - } - else { + } else { if (is_string($type) && isset(self::$builtInValidators[$type])) { $type = self::$builtInValidators[$type]; } @@ -181,8 +178,7 @@ abstract class Validator extends \yii\base\Component { if (is_array($attributes)) { $attributes = array_intersect($this->attributes, $attributes); - } - else { + } else { $attributes = $this->attributes; } foreach ($attributes as $attribute) { diff --git a/framework/yiic.php b/framework/yiic.php index 72f6f36..9592526 100644 --- a/framework/yiic.php +++ b/framework/yiic.php @@ -19,8 +19,7 @@ if(isset($config)) $env=@getenv('YII_CONSOLE_COMMANDS'); if(!empty($env)) $app->commandRunner->addCommands($env); -} -else +} else { $app=new \yii\console\Application(array( 'basePath'=>__DIR__.'/cli', diff --git a/tests/unit/MysqlTestCase.php b/tests/unit/MysqlTestCase.php new file mode 100644 index 0000000..8c0fbcb --- /dev/null +++ b/tests/unit/MysqlTestCase.php @@ -0,0 +1,33 @@ +markTestSkipped('pdo and pdo_mysql extensions are required.'); + } + } + + /** + * @param bool $reset whether to clean up the test database + * @return \yii\db\dao\Connection + */ + function getConnection($reset = true) + { + $params = $this->getParam('mysql'); + $db = new \yii\db\dao\Connection($params['dsn'], $params['username'], $params['password']); + if ($reset) { + $db->active = true; + $lines = explode(';', file_get_contents($params['fixture'])); + foreach ($lines as $line) { + if (trim($line) !== '') { + $db->pdo->exec($line); + } + } + } + return $db; + } +} \ No newline at end of file diff --git a/tests/unit/data/mysql.sql b/tests/unit/data/mysql.sql index 042277e..7b77af2 100644 --- a/tests/unit/data/mysql.sql +++ b/tests/unit/data/mysql.sql @@ -4,17 +4,17 @@ * and create an account 'test/test' which owns this test database. */ -DROP TABLE IF EXISTS types CASCADE; -DROP TABLE IF EXISTS items CASCADE; -DROP TABLE IF EXISTS orders CASCADE; -DROP TABLE IF EXISTS post_category CASCADE; -DROP TABLE IF EXISTS categories CASCADE; -DROP TABLE IF EXISTS comments CASCADE; -DROP TABLE IF EXISTS posts CASCADE; -DROP TABLE IF EXISTS profiles CASCADE; -DROP TABLE IF EXISTS users CASCADE; - -CREATE TABLE users +DROP TABLE IF EXISTS yii_type CASCADE; +DROP TABLE IF EXISTS yii_item CASCADE; +DROP TABLE IF EXISTS yii_order CASCADE; +DROP TABLE IF EXISTS yii_post_category CASCADE; +DROP TABLE IF EXISTS yii_category CASCADE; +DROP TABLE IF EXISTS yii_comment CASCADE; +DROP TABLE IF EXISTS yii_post CASCADE; +DROP TABLE IF EXISTS yii_profile CASCADE; +DROP TABLE IF EXISTS yii_user CASCADE; + +CREATE TABLE yii_user ( id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, username VARCHAR(128) NOT NULL, @@ -22,24 +22,24 @@ CREATE TABLE users email VARCHAR(128) NOT NULL ) TYPE=INNODB; -INSERT INTO users (username, password, email) VALUES ('user1','pass1','email1'); -INSERT INTO users (username, password, email) VALUES ('user2','pass2','email2'); -INSERT INTO users (username, password, email) VALUES ('user3','pass3','email3'); +INSERT INTO yii_user (username, password, email) VALUES ('user1','pass1','email1'); +INSERT INTO yii_user (username, password, email) VALUES ('user2','pass2','email2'); +INSERT INTO yii_user (username, password, email) VALUES ('user3','pass3','email3'); -CREATE TABLE profiles +CREATE TABLE yii_profile ( id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, first_name VARCHAR(128) NOT NULL, last_name VARCHAR(128) NOT NULL, user_id INTEGER NOT NULL, CONSTRAINT FK_profile_user FOREIGN KEY (user_id) - REFERENCES users (id) ON DELETE CASCADE ON UPDATE RESTRICT + REFERENCES yii_user (id) ON DELETE CASCADE ON UPDATE RESTRICT ) TYPE=INNODB; -INSERT INTO profiles (first_name, last_name, user_id) VALUES ('first 1','last 1',1); -INSERT INTO profiles (first_name, last_name, user_id) VALUES ('first 2','last 2',2); +INSERT INTO yii_profile (first_name, last_name, user_id) VALUES ('first 1','last 1',1); +INSERT INTO yii_profile (first_name, last_name, user_id) VALUES ('first 2','last 2',2); -CREATE TABLE posts +CREATE TABLE yii_post ( id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, title VARCHAR(128) NOT NULL, @@ -47,74 +47,74 @@ CREATE TABLE posts author_id INTEGER NOT NULL, content TEXT, CONSTRAINT FK_post_author FOREIGN KEY (author_id) - REFERENCES users (id) ON DELETE CASCADE ON UPDATE RESTRICT + REFERENCES yii_user (id) ON DELETE CASCADE ON UPDATE RESTRICT ) TYPE=INNODB; -INSERT INTO posts (title, create_time, author_id, content) VALUES ('post 1','2000-01-01',1,'content 1'); -INSERT INTO posts (title, create_time, author_id, content) VALUES ('post 2','2000-01-02',2,'content 2'); -INSERT INTO posts (title, create_time, author_id, content) VALUES ('post 3','2000-01-03',2,'content 3'); -INSERT INTO posts (title, create_time, author_id, content) VALUES ('post 4','2000-01-04',2,'content 4'); -INSERT INTO posts (title, create_time, author_id, content) VALUES ('post 5','2000-01-05',3,'content 5'); +INSERT INTO yii_post (title, create_time, author_id, content) VALUES ('post 1','2000-01-01',1,'content 1'); +INSERT INTO yii_post (title, create_time, author_id, content) VALUES ('post 2','2000-01-02',2,'content 2'); +INSERT INTO yii_post (title, create_time, author_id, content) VALUES ('post 3','2000-01-03',2,'content 3'); +INSERT INTO yii_post (title, create_time, author_id, content) VALUES ('post 4','2000-01-04',2,'content 4'); +INSERT INTO yii_post (title, create_time, author_id, content) VALUES ('post 5','2000-01-05',3,'content 5'); -CREATE TABLE comments +CREATE TABLE yii_comment ( id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, content TEXT NOT NULL, post_id INTEGER NOT NULL, author_id INTEGER NOT NULL, CONSTRAINT FK_post_comment FOREIGN KEY (post_id) - REFERENCES posts (id) ON DELETE CASCADE ON UPDATE RESTRICT, + REFERENCES yii_post (id) ON DELETE CASCADE ON UPDATE RESTRICT, CONSTRAINT FK_user_comment FOREIGN KEY (author_id) - REFERENCES users (id) ON DELETE CASCADE ON UPDATE RESTRICT + REFERENCES yii_user (id) ON DELETE CASCADE ON UPDATE RESTRICT ) TYPE=INNODB; -INSERT INTO comments (content, post_id, author_id) VALUES ('comment 1',1, 2); -INSERT INTO comments (content, post_id, author_id) VALUES ('comment 2',1, 2); -INSERT INTO comments (content, post_id, author_id) VALUES ('comment 3',1, 2); -INSERT INTO comments (content, post_id, author_id) VALUES ('comment 4',2, 2); -INSERT INTO comments (content, post_id, author_id) VALUES ('comment 5',2, 2); -INSERT INTO comments (content, post_id, author_id) VALUES ('comment 6',3, 2); -INSERT INTO comments (content, post_id, author_id) VALUES ('comment 7',3, 2); -INSERT INTO comments (content, post_id, author_id) VALUES ('comment 8',3, 2); -INSERT INTO comments (content, post_id, author_id) VALUES ('comment 9',3, 2); -INSERT INTO comments (content, post_id, author_id) VALUES ('comment 10',5, 3); - -CREATE TABLE categories +INSERT INTO yii_comment (content, post_id, author_id) VALUES ('comment 1',1, 2); +INSERT INTO yii_comment (content, post_id, author_id) VALUES ('comment 2',1, 2); +INSERT INTO yii_comment (content, post_id, author_id) VALUES ('comment 3',1, 2); +INSERT INTO yii_comment (content, post_id, author_id) VALUES ('comment 4',2, 2); +INSERT INTO yii_comment (content, post_id, author_id) VALUES ('comment 5',2, 2); +INSERT INTO yii_comment (content, post_id, author_id) VALUES ('comment 6',3, 2); +INSERT INTO yii_comment (content, post_id, author_id) VALUES ('comment 7',3, 2); +INSERT INTO yii_comment (content, post_id, author_id) VALUES ('comment 8',3, 2); +INSERT INTO yii_comment (content, post_id, author_id) VALUES ('comment 9',3, 2); +INSERT INTO yii_comment (content, post_id, author_id) VALUES ('comment 10',5, 3); + +CREATE TABLE yii_category ( id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, name VARCHAR(128) NOT NULL, parent_id INTEGER, CONSTRAINT FK_category_category FOREIGN KEY (parent_id) - REFERENCES categories (id) ON DELETE CASCADE ON UPDATE RESTRICT + REFERENCES yii_category (id) ON DELETE CASCADE ON UPDATE RESTRICT ) TYPE=INNODB; -INSERT INTO categories (name, parent_id) VALUES ('cat 1',NULL); -INSERT INTO categories (name, parent_id) VALUES ('cat 2',NULL); -INSERT INTO categories (name, parent_id) VALUES ('cat 3',NULL); -INSERT INTO categories (name, parent_id) VALUES ('cat 4',1); -INSERT INTO categories (name, parent_id) VALUES ('cat 5',1); -INSERT INTO categories (name, parent_id) VALUES ('cat 6',5); -INSERT INTO categories (name, parent_id) VALUES ('cat 7',5); +INSERT INTO yii_category (name, parent_id) VALUES ('cat 1',NULL); +INSERT INTO yii_category (name, parent_id) VALUES ('cat 2',NULL); +INSERT INTO yii_category (name, parent_id) VALUES ('cat 3',NULL); +INSERT INTO yii_category (name, parent_id) VALUES ('cat 4',1); +INSERT INTO yii_category (name, parent_id) VALUES ('cat 5',1); +INSERT INTO yii_category (name, parent_id) VALUES ('cat 6',5); +INSERT INTO yii_category (name, parent_id) VALUES ('cat 7',5); -CREATE TABLE post_category +CREATE TABLE yii_post_category ( category_id INTEGER NOT NULL, post_id INTEGER NOT NULL, PRIMARY KEY (category_id, post_id), - CONSTRAINT FK_post_category_post FOREIGN KEY (post_id) - REFERENCES posts (id) ON DELETE CASCADE ON UPDATE RESTRICT, - CONSTRAINT FK_post_category_category FOREIGN KEY (category_id) - REFERENCES categories (id) ON DELETE CASCADE ON UPDATE RESTRICT + CONSTRAINT FK_yii_post_category_post FOREIGN KEY (post_id) + REFERENCES yii_post (id) ON DELETE CASCADE ON UPDATE RESTRICT, + CONSTRAINT FK_yii_post_category_category FOREIGN KEY (category_id) + REFERENCES yii_category (id) ON DELETE CASCADE ON UPDATE RESTRICT ) TYPE=INNODB; -INSERT INTO post_category (category_id, post_id) VALUES (1,1); -INSERT INTO post_category (category_id, post_id) VALUES (2,1); -INSERT INTO post_category (category_id, post_id) VALUES (3,1); -INSERT INTO post_category (category_id, post_id) VALUES (4,2); -INSERT INTO post_category (category_id, post_id) VALUES (1,2); -INSERT INTO post_category (category_id, post_id) VALUES (1,3); +INSERT INTO yii_post_category (category_id, post_id) VALUES (1,1); +INSERT INTO yii_post_category (category_id, post_id) VALUES (2,1); +INSERT INTO yii_post_category (category_id, post_id) VALUES (3,1); +INSERT INTO yii_post_category (category_id, post_id) VALUES (4,2); +INSERT INTO yii_post_category (category_id, post_id) VALUES (1,2); +INSERT INTO yii_post_category (category_id, post_id) VALUES (1,3); -CREATE TABLE orders +CREATE TABLE yii_order ( key1 INTEGER NOT NULL, key2 INTEGER NOT NULL, @@ -122,28 +122,28 @@ CREATE TABLE orders PRIMARY KEY (key1, key2) ) TYPE=INNODB; -INSERT INTO orders (key1,key2,name) VALUES (1,2,'order 12'); -INSERT INTO orders (key1,key2,name) VALUES (1,3,'order 13'); -INSERT INTO orders (key1,key2,name) VALUES (2,1,'order 21'); -INSERT INTO orders (key1,key2,name) VALUES (2,2,'order 22'); +INSERT INTO yii_order (key1,key2,name) VALUES (1,2,'order 12'); +INSERT INTO yii_order (key1,key2,name) VALUES (1,3,'order 13'); +INSERT INTO yii_order (key1,key2,name) VALUES (2,1,'order 21'); +INSERT INTO yii_order (key1,key2,name) VALUES (2,2,'order 22'); -CREATE TABLE items +CREATE TABLE yii_item ( id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, name VARCHAR(128), col1 INTEGER NOT NULL, col2 INTEGER NOT NULL, CONSTRAINT FK_order_item FOREIGN KEY (col1,col2) - REFERENCES orders (key1,key2) ON DELETE CASCADE ON UPDATE RESTRICT + REFERENCES yii_order (key1,key2) ON DELETE CASCADE ON UPDATE RESTRICT ) TYPE=INNODB; -INSERT INTO items (name,col1,col2) VALUES ('item 1',1,2); -INSERT INTO items (name,col1,col2) VALUES ('item 2',1,2); -INSERT INTO items (name,col1,col2) VALUES ('item 3',1,3); -INSERT INTO items (name,col1,col2) VALUES ('item 4',2,2); -INSERT INTO items (name,col1,col2) VALUES ('item 5',2,2); +INSERT INTO yii_item (name,col1,col2) VALUES ('item 1',1,2); +INSERT INTO yii_item (name,col1,col2) VALUES ('item 2',1,2); +INSERT INTO yii_item (name,col1,col2) VALUES ('item 3',1,3); +INSERT INTO yii_item (name,col1,col2) VALUES ('item 4',2,2); +INSERT INTO yii_item (name,col1,col2) VALUES ('item 5',2,2); -CREATE TABLE types +CREATE TABLE yii_type ( int_col INT NOT NULL, int_col2 INTEGER DEFAULT 1, diff --git a/tests/unit/framework/db/dao/CommandTest.php b/tests/unit/framework/db/dao/CommandTest.php index 723140c..fb2b561 100644 --- a/tests/unit/framework/db/dao/CommandTest.php +++ b/tests/unit/framework/db/dao/CommandTest.php @@ -6,47 +6,40 @@ use yii\db\dao\Connection; use yii\db\dao\Command; use yii\db\dao\Query; -class CommandTest extends \yiiunit\TestCase +class CommandTest extends \yiiunit\MysqlTestCase { - private $connection; - - function setUp() - { - if(!extension_loaded('pdo') || !extension_loaded('pdo_mysql')) - $this->markTestSkipped('pdo and pdo_mysql extensions are required.'); - - $params = $this->getParam('mysql'); - $this->connection = new Connection($params['dsn'], $params['username'], $params['password']); - $this->connection->open(); - $this->connection->pdo->exec(file_get_contents($params['fixture'])); - } - - function tearDown() - { - $this->connection->close(); - } - function testConstruct() { - $command = $this->connection->createCommand(); + $db = $this->getConnection(false); + + $command = $db->createCommand(); $this->assertEquals("SELECT *\nFROM ", $command->sql); $sql='SELECT * FROM posts'; - $command = $this->connection->createCommand($sql); + $command = $db->createCommand($sql); $this->assertEquals($sql, $command->sql); $query = new Query; - $command = $this->connection->createCommand($query); + $command = $db->createCommand($query); $this->assertEquals($query, $command->query); $query = array('select'=>'id', 'from'=>'posts'); - $command = $this->connection->createCommand($query); + $command = $db->createCommand($query); $this->assertEquals($query, $command->query->toArray()); } function testReset() { + $db = $this->getConnection(); + + $command = $db->createCommand('SELECT * FROM yii_user'); + $command->queryRow(); + $this->assertNotEquals(null, $command->pdoStatement); + $this->assertEquals('SELECT * FROM yii_user', $command->sql); + $command->reset(); + $this->assertEquals(null, $command->pdoStatement); + $this->assertNotEquals('SELECT * FROM yii_user', $command->sql); } function testGetSetSql() @@ -108,7 +101,7 @@ class CommandTest extends \yiiunit\TestCase function testPrepare() { $sql='SELECT title FROM posts'; - $command=$this->connection->createCommand($sql); + $command=$db->createCommand($sql); $this->assertEquals($command->pdoStatement,null); $command->prepare(); $this->assertTrue($command->pdoStatement instanceof PDOStatement); @@ -122,7 +115,7 @@ class CommandTest extends \yiiunit\TestCase function testCancel() { $sql='SELECT title FROM posts'; - $command=$this->connection->createCommand($sql); + $command=$db->createCommand($sql); $command->prepare(); $this->assertTrue($command->pdoStatement instanceof PDOStatement); $command->cancel(); @@ -132,15 +125,15 @@ class CommandTest extends \yiiunit\TestCase function testExecute() { $sql='INSERT INTO comments(content,post_id,author_id) VALUES (\'test comment\', 1, 1)'; - $command=$this->connection->createCommand($sql); + $command=$db->createCommand($sql); $this->assertEquals($command->execute(),1); $this->assertEquals($command->execute(),1); - $command=$this->connection->createCommand('SELECT * FROM comments WHERE content=\'test comment\''); + $command=$db->createCommand('SELECT * FROM comments WHERE content=\'test comment\''); $this->assertEquals($command->execute(),0); - $command=$this->connection->createCommand('SELECT COUNT(*) FROM comments WHERE content=\'test comment\''); + $command=$db->createCommand('SELECT COUNT(*) FROM comments WHERE content=\'test comment\''); $this->assertEquals($command->queryScalar(),2); - $command=$this->connection->createCommand('bad SQL'); + $command=$db->createCommand('bad SQL'); $this->setExpectedException('CException'); $command->execute(); } @@ -148,16 +141,16 @@ class CommandTest extends \yiiunit\TestCase function testQuery() { $sql='SELECT * FROM posts'; - $reader=$this->connection->createCommand($sql)->query(); + $reader=$db->createCommand($sql)->query(); $this->assertTrue($reader instanceof CDbDataReader); $sql='SELECT * FROM posts'; - $command=$this->connection->createCommand($sql); + $command=$db->createCommand($sql); $command->prepare(); $reader=$command->query(); $this->assertTrue($reader instanceof CDbDataReader); - $command=$this->connection->createCommand('bad SQL'); + $command=$db->createCommand('bad SQL'); $this->setExpectedException('CException'); $command->query(); } @@ -165,7 +158,7 @@ class CommandTest extends \yiiunit\TestCase function testBindParam() { $sql='INSERT INTO posts(title,create_time,author_id) VALUES (:title, :create_time, 1)'; - $command=$this->connection->createCommand($sql); + $command=$db->createCommand($sql); $title='test title'; $createTime=time(); $command->bindParam(':title',$title); @@ -173,12 +166,12 @@ class CommandTest extends \yiiunit\TestCase $command->execute(); $sql='SELECT create_time FROM posts WHERE title=:title'; - $command=$this->connection->createCommand($sql); + $command=$db->createCommand($sql); $command->bindParam(':title',$title); $this->assertEquals($command->queryScalar(),$createTime); $sql='INSERT INTO types (int_col, char_col, float_col, blob_col, numeric_col, bool_col) VALUES (:int_col, :char_col, :float_col, :blob_col, :numeric_col, :bool_col)'; - $command=$this->connection->createCommand($sql); + $command=$db->createCommand($sql); $intCol=123; $charCol='abc'; $floatCol=1.23; @@ -194,7 +187,7 @@ class CommandTest extends \yiiunit\TestCase $this->assertEquals(1,$command->execute()); $sql='SELECT * FROM types'; - $row=$this->connection->createCommand($sql)->queryRow(); + $row=$db->createCommand($sql)->queryRow(); $this->assertEquals($row['int_col'],$intCol); $this->assertEquals($row['char_col'],$charCol); $this->assertEquals($row['float_col'],$floatCol); @@ -205,47 +198,47 @@ class CommandTest extends \yiiunit\TestCase function testBindValue() { $sql='INSERT INTO comments(content,post_id,author_id) VALUES (:content, 1, 1)'; - $command=$this->connection->createCommand($sql); + $command=$db->createCommand($sql); $command->bindValue(':content','test comment'); $command->execute(); $sql='SELECT post_id FROM comments WHERE content=:content'; - $command=$this->connection->createCommand($sql); + $command=$db->createCommand($sql); $command->bindValue(':content','test comment'); $this->assertEquals($command->queryScalar(),1); } function testQueryAll() { - $rows=$this->connection->createCommand('SELECT * FROM posts')->queryAll(); + $rows=$db->createCommand('SELECT * FROM posts')->queryAll(); $this->assertEquals(count($rows),5); $row=$rows[2]; $this->assertEquals($row['id'],3); $this->assertEquals($row['title'],'post 3'); - $rows=$this->connection->createCommand('SELECT * FROM posts WHERE id=10')->queryAll(); + $rows=$db->createCommand('SELECT * FROM posts WHERE id=10')->queryAll(); $this->assertEquals($rows,array()); } function testQueryRow() { $sql='SELECT * FROM posts'; - $row=$this->connection->createCommand($sql)->queryRow(); + $row=$db->createCommand($sql)->queryRow(); $this->assertEquals($row['id'],1); $this->assertEquals($row['title'],'post 1'); $sql='SELECT * FROM posts'; - $command=$this->connection->createCommand($sql); + $command=$db->createCommand($sql); $command->prepare(); $row=$command->queryRow(); $this->assertEquals($row['id'],1); $this->assertEquals($row['title'],'post 1'); $sql='SELECT * FROM posts WHERE id=10'; - $command=$this->connection->createCommand($sql); + $command=$db->createCommand($sql); $this->assertFalse($command->queryRow()); - $command=$this->connection->createCommand('bad SQL'); + $command=$db->createCommand('bad SQL'); $this->setExpectedException('CException'); $command->queryRow(); } @@ -253,13 +246,13 @@ class CommandTest extends \yiiunit\TestCase function testQueryColumn() { $sql='SELECT * FROM posts'; - $column=$this->connection->createCommand($sql)->queryColumn(); + $column=$db->createCommand($sql)->queryColumn(); $this->assertEquals($column,range(1,5)); - $command=$this->connection->createCommand('SELECT id FROM posts WHERE id=10'); + $command=$db->createCommand('SELECT id FROM posts WHERE id=10'); $this->assertEquals($command->queryColumn(),array()); - $command=$this->connection->createCommand('bad SQL'); + $command=$db->createCommand('bad SQL'); $this->setExpectedException('CException'); $command->queryColumn(); } @@ -267,29 +260,29 @@ class CommandTest extends \yiiunit\TestCase function testQueryScalar() { $sql='SELECT * FROM posts'; - $this->assertEquals($this->connection->createCommand($sql)->queryScalar(),1); + $this->assertEquals($db->createCommand($sql)->queryScalar(),1); $sql='SELECT id FROM posts'; - $command=$this->connection->createCommand($sql); + $command=$db->createCommand($sql); $command->prepare(); $this->assertEquals($command->queryScalar(),1); - $command=$this->connection->createCommand('SELECT id FROM posts WHERE id=10'); + $command=$db->createCommand('SELECT id FROM posts WHERE id=10'); $this->assertFalse($command->queryScalar()); - $command=$this->connection->createCommand('bad SQL'); + $command=$db->createCommand('bad SQL'); $this->setExpectedException('CException'); $command->queryScalar(); } function testFetchMode(){ $sql='SELECT * FROM posts'; - $command=$this->connection->createCommand($sql); + $command=$db->createCommand($sql); $result = $command->queryRow(); $this->assertTrue(is_array($result)); $sql='SELECT * FROM posts'; - $command=$this->connection->createCommand($sql); + $command=$db->createCommand($sql); $command->setFetchMode(PDO::FETCH_OBJ); $result = $command->queryRow(); $this->assertTrue(is_object($result)); diff --git a/tests/unit/framework/db/dao/ConnectionTest.php b/tests/unit/framework/db/dao/ConnectionTest.php index e11c16d..fd3db3c 100644 --- a/tests/unit/framework/db/dao/ConnectionTest.php +++ b/tests/unit/framework/db/dao/ConnectionTest.php @@ -4,17 +4,11 @@ namespace yiiunit\framework\db\dao; use yii\db\dao\Connection; -class ConnectionTest extends \yiiunit\TestCase +class ConnectionTest extends \yiiunit\MysqlTestCase { - function setUp() - { - if(!extension_loaded('pdo') || !extension_loaded('pdo_mysql')) - $this->markTestSkipped('pdo and pdo_mysql extensions are required.'); - } - function testConstruct() { - $connection = $this->createConnection(); + $connection = $this->getConnection(); $params = $this->getParam('mysql'); $this->assertEquals($params['dsn'], $connection->dsn); @@ -24,7 +18,7 @@ class ConnectionTest extends \yiiunit\TestCase function testOpenClose() { - $connection = $this->createConnection(); + $connection = $this->getConnection(); $this->assertFalse($connection->active); $this->assertEquals(null, $connection->pdo); @@ -44,14 +38,14 @@ class ConnectionTest extends \yiiunit\TestCase function testGetDriverName() { - $connection = $this->createConnection(); + $connection = $this->getConnection(); $this->assertEquals('mysql', $connection->driverName); $this->assertFalse($connection->active); } function testQuoteValue() { - $connection = $this->createConnection(); + $connection = $this->getConnection(); $this->assertEquals(123, $connection->quoteValue(123)); $this->assertEquals("'string'", $connection->quoteValue('string')); $this->assertEquals("'It\'s interesting'", $connection->quoteValue("It's interesting")); @@ -59,23 +53,25 @@ class ConnectionTest extends \yiiunit\TestCase function testQuoteTableName() { - $connection = $this->createConnection(); + $connection = $this->getConnection(); $this->assertEquals('`table`', $connection->quoteTableName('table')); $this->assertEquals('`table`', $connection->quoteTableName('`table`')); $this->assertEquals('`schema`.`table`', $connection->quoteTableName('schema.table')); + $this->assertEquals('`schema.table`', $connection->quoteTableName('schema.table', true)); } function testQuoteColumnName() { - $connection = $this->createConnection(); + $connection = $this->getConnection(); $this->assertEquals('`column`', $connection->quoteColumnName('column')); $this->assertEquals('`column`', $connection->quoteColumnName('`column`')); $this->assertEquals('`table`.`column`', $connection->quoteColumnName('table.column')); + $this->assertEquals('`table.column`', $connection->quoteColumnName('table.column', true)); } function testGetPdoType() { - $connection = $this->createConnection(); + $connection = $this->getConnection(); $this->assertEquals(\PDO::PARAM_BOOL, $connection->getPdoType('boolean')); $this->assertEquals(\PDO::PARAM_INT, $connection->getPdoType('integer')); $this->assertEquals(\PDO::PARAM_STR, $connection->getPdoType('string')); @@ -86,10 +82,4 @@ class ConnectionTest extends \yiiunit\TestCase { } - - function createConnection() - { - $params = $this->getParam('mysql'); - return new Connection($params['dsn'], $params['username'], $params['password']); - } }