diff --git a/.gitignore b/.gitignore index 13fcf4a..f2915a9 100644 --- a/.gitignore +++ b/.gitignore @@ -17,3 +17,6 @@ Thumbs.db # composer itself is not needed composer.phar + +# Mac DS_Store Files +.DS_Store diff --git a/.travis.yml b/.travis.yml index 41bd6a9..2add223 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,17 +5,24 @@ php: - 5.4 - 5.5 +env: + - CUBRID_VERSION=9.1.0 + services: - redis-server + - memcached before_script: - composer self-update && composer --version - composer require satooshi/php-coveralls 0.6.* - mysql -e 'CREATE DATABASE yiitest;'; - psql -U postgres -c 'CREATE DATABASE yiitest;'; + - tests/unit/data/travis/apc-setup.sh + - tests/unit/data/travis/memcache-setup.sh + - tests/unit/data/travis/cubrid-setup.sh script: - - phpunit --coverage-clover tests/unit/runtime/coveralls/clover.xml + - phpunit --coverage-clover tests/unit/runtime/coveralls/clover.xml --verbose --exclude-group mssql,oci,wincache,xcache,zenddata after_script: - php vendor/bin/coveralls diff --git a/apps/advanced/README.md b/apps/advanced/README.md index 7055360..6860c11 100644 --- a/apps/advanced/README.md +++ b/apps/advanced/README.md @@ -74,6 +74,8 @@ You can then install the application using the following command: php composer.phar create-project --stability=dev yiisoft/yii2-app-advanced yii-advanced ~~~ +Note that in order to install some dependencies you must have `php_openssl` extension enabled. + ### Install from an Archive File diff --git a/apps/advanced/backend/config/main.php b/apps/advanced/backend/config/main.php index 377d34c..30c1825 100644 --- a/apps/advanced/backend/config/main.php +++ b/apps/advanced/backend/config/main.php @@ -17,13 +17,16 @@ return array( 'modules' => array( ), 'components' => array( + 'request' => array( + 'enableCsrfValidation' => true, + ), 'db' => $params['components.db'], 'cache' => $params['components.cache'], 'user' => array( - 'class' => 'yii\web\User', 'identityClass' => 'common\models\User', ), 'log' => array( + 'traceLevel' => YII_DEBUG ? 3 : 0, 'targets' => array( array( 'class' => 'yii\log\FileTarget', @@ -31,6 +34,9 @@ return array( ), ), ), + 'errorHandler' => array( + 'errorAction' => 'site/error', + ), ), 'params' => $params, ); diff --git a/apps/advanced/backend/controllers/SiteController.php b/apps/advanced/backend/controllers/SiteController.php index 480406a..28f2310 100644 --- a/apps/advanced/backend/controllers/SiteController.php +++ b/apps/advanced/backend/controllers/SiteController.php @@ -8,6 +8,36 @@ use common\models\LoginForm; class SiteController extends Controller { + public function behaviors() + { + return array( + 'access' => array( + 'class' => \yii\web\AccessControl::className(), + 'rules' => array( + array( + 'actions' => array('login'), + 'allow' => true, + 'roles' => array('?'), + ), + array( + 'actions' => array('logout', 'index'), + 'allow' => true, + 'roles' => array('@'), + ), + ), + ), + ); + } + + public function actions() + { + return array( + 'error' => array( + 'class' => 'yii\web\ErrorAction', + ), + ); + } + public function actionIndex() { return $this->render('index'); diff --git a/apps/advanced/backend/views/site/error.php b/apps/advanced/backend/views/site/error.php new file mode 100644 index 0000000..024e27d --- /dev/null +++ b/apps/advanced/backend/views/site/error.php @@ -0,0 +1,29 @@ +title = $name; +?> +
+ +

title); ?>

+ +
+ +
+ +

+ The above error occurred while the Web server was processing your request. +

+

+ Please contact us if you think this is a server error. Thank you. +

+ +
diff --git a/apps/advanced/environments/dev/backend/config/main-local.php b/apps/advanced/environments/dev/backend/config/main-local.php index fdc131d..2689ed1 100644 --- a/apps/advanced/environments/dev/backend/config/main-local.php +++ b/apps/advanced/environments/dev/backend/config/main-local.php @@ -1,17 +1,11 @@ array( + //'debug', + ), 'modules' => array( // 'debug' => array( // 'class' => 'yii\debug\Module', // ), ), - 'components' => array( - 'log' => array( - 'targets' => array( -// array( -// 'class' => 'yii\log\DebugTarget', -// ) - ), - ), - ), ); diff --git a/apps/advanced/environments/dev/backend/web/index.php b/apps/advanced/environments/dev/backend/web/index.php index 7d47419..2113419 100644 --- a/apps/advanced/environments/dev/backend/web/index.php +++ b/apps/advanced/environments/dev/backend/web/index.php @@ -1,6 +1,6 @@ array( + //'debug', + ), 'modules' => array( // 'debug' => array( // 'class' => 'yii\debug\Module', // ), ), - 'components' => array( - 'log' => array( - 'targets' => array( -// array( -// 'class' => 'yii\log\DebugTarget', -// ) - ), - ), - ), ); diff --git a/apps/advanced/environments/dev/frontend/web/index.php b/apps/advanced/environments/dev/frontend/web/index.php index 82ca04c..9a7cbae 100644 --- a/apps/advanced/environments/dev/frontend/web/index.php +++ b/apps/advanced/environments/dev/frontend/web/index.php @@ -1,7 +1,6 @@ dirname(dirname(__DIR__)) . '/vendor', 'controllerNamespace' => 'frontend\controllers', 'modules' => array( + 'gii' => 'yii\gii\Module' ), 'components' => array( + 'request' => array( + 'enableCsrfValidation' => true, + ), 'db' => $params['components.db'], 'cache' => $params['components.cache'], 'user' => array( - 'class' => 'yii\web\User', 'identityClass' => 'common\models\User', ), 'log' => array( + 'traceLevel' => YII_DEBUG ? 3 : 0, 'targets' => array( array( 'class' => 'yii\log\FileTarget', @@ -30,6 +34,9 @@ return array( ), ), ), + 'errorHandler' => array( + 'errorAction' => 'site/error', + ), ), 'params' => $params, ); diff --git a/apps/advanced/frontend/controllers/SiteController.php b/apps/advanced/frontend/controllers/SiteController.php index 0c1b2f5..be9a634 100644 --- a/apps/advanced/frontend/controllers/SiteController.php +++ b/apps/advanced/frontend/controllers/SiteController.php @@ -12,11 +12,37 @@ use yii\helpers\Security; class SiteController extends Controller { + public function behaviors() + { + return array( + 'access' => array( + 'class' => \yii\web\AccessControl::className(), + 'only' => array('login', 'logout', 'signup'), + 'rules' => array( + array( + 'actions' => array('login', 'signup'), + 'allow' => true, + 'roles' => array('?'), + ), + array( + 'actions' => array('logout'), + 'allow' => true, + 'roles' => array('@'), + ), + ), + ), + ); + } + public function actions() { return array( + 'error' => array( + 'class' => 'yii\web\ErrorAction', + ), 'captcha' => array( 'class' => 'yii\captcha\CaptchaAction', + 'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null, ), ); } diff --git a/apps/advanced/frontend/views/site/error.php b/apps/advanced/frontend/views/site/error.php new file mode 100644 index 0000000..024e27d --- /dev/null +++ b/apps/advanced/frontend/views/site/error.php @@ -0,0 +1,29 @@ +title = $name; +?> +
+ +

title); ?>

+ +
+ +
+ +

+ The above error occurred while the Web server was processing your request. +

+

+ Please contact us if you think this is a server error. Thank you. +

+ +
diff --git a/apps/basic/README.md b/apps/basic/README.md index b5e1ec2..aaa7fba 100644 --- a/apps/basic/README.md +++ b/apps/basic/README.md @@ -56,6 +56,8 @@ php composer.phar create-project --stability=dev yiisoft/yii2-app-basic yii-basi Now you should be able to access the application using the URL `http://localhost/yii-basic/web/`, assuming `yii-basic` is directly under the document root of your Web server. +Note that in order to install some dependencies you must have `php_openssl` extension enabled. + ### Install from an Archive File diff --git a/apps/basic/config/web.php b/apps/basic/config/web.php index 1433a64..e7d9420 100644 --- a/apps/basic/config/web.php +++ b/apps/basic/config/web.php @@ -1,9 +1,12 @@ 'bootstrap', 'basePath' => dirname(__DIR__), 'components' => array( + 'request' => array( + 'enableCsrfValidation' => true, + ), 'cache' => array( 'class' => 'yii\caching\FileCache', ), @@ -23,7 +26,7 @@ $config = array( ), ), ), - 'params' => require(__DIR__ . '/params.php'), + 'params' => $params, ); if (YII_ENV_DEV) { diff --git a/apps/basic/controllers/SiteController.php b/apps/basic/controllers/SiteController.php index cd0b3fb..785eddf 100644 --- a/apps/basic/controllers/SiteController.php +++ b/apps/basic/controllers/SiteController.php @@ -9,6 +9,28 @@ use app\models\ContactForm; class SiteController extends Controller { + public function behaviors() + { + return array( + 'access' => array( + 'class' => \yii\web\AccessControl::className(), + 'only' => array('login', 'logout'), + 'rules' => array( + array( + 'actions' => array('login'), + 'allow' => true, + 'roles' => array('?'), + ), + array( + 'actions' => array('logout'), + 'allow' => true, + 'roles' => array('@'), + ), + ), + ), + ); + } + public function actions() { return array( diff --git a/apps/basic/views/layouts/main.php b/apps/basic/views/layouts/main.php index 04a2f33..240c2a3 100644 --- a/apps/basic/views/layouts/main.php +++ b/apps/basic/views/layouts/main.php @@ -36,7 +36,7 @@ app\config\AppAsset::register($this); array('label' => 'Contact', 'url' => array('/site/contact')), Yii::$app->user->isGuest ? array('label' => 'Login', 'url' => array('/site/login')) : - array('label' => 'Logout (' . Yii::$app->user->identity->username .')' , 'url' => array('/site/logout')), + array('label' => 'Logout (' . Html::encode(Yii::$app->user->identity->username) .')' , 'url' => array('/site/logout')), ), )); NavBar::end(); diff --git a/apps/basic/views/site/login.php b/apps/basic/views/site/login.php index 524b0cc..f61d9d7 100644 --- a/apps/basic/views/site/login.php +++ b/apps/basic/views/site/login.php @@ -15,20 +15,33 @@ $this->params['breadcrumbs'][] = $this->title;

Please fill out the following fields to login:

-
-
- 'login-form')); ?> - field($model, 'username'); ?> - field($model, 'password')->passwordInput(); ?> - field($model, 'rememberMe')->checkbox(); ?> -
- 'btn btn-primary')); ?> -
- -
-
- You may login with admin/admin or demo/demo.
- To modify the username/password, please check out the code app\models\User::$users. + 'login-form', + 'options' => array('class' => 'form-horizontal'), + 'fieldConfig' => array( + 'template' => "{label}\n
{input}
\n
{error}
", + 'labelOptions' => array('class' => 'col-lg-1 control-label'), + ), + )); ?> + + field($model, 'username'); ?> + + field($model, 'password')->passwordInput(); ?> + + field($model, 'rememberMe', array( + 'template' => "
{input}
\n
{error}
", + ))->checkbox(); ?> + +
+
+ 'btn btn-primary')); ?>
+ + + +
+ You may login with admin/admin or demo/demo.
+ To modify the username/password, please check out the code app\models\User::$users. +
diff --git a/apps/benchmark/README.md b/apps/benchmark/README.md index 2aeb0ae..2d5871a 100644 --- a/apps/benchmark/README.md +++ b/apps/benchmark/README.md @@ -54,3 +54,5 @@ http://localhost/yii-benchmark/index.php/site/hello In the above, we assume `yii-benchmark` is directly under the document root of your Web server. +Note that in order to install some dependencies you must have `php_openssl` extension enabled. + diff --git a/build/controllers/PhpDocController.php b/build/controllers/PhpDocController.php new file mode 100644 index 0000000..5aac7e5 --- /dev/null +++ b/build/controllers/PhpDocController.php @@ -0,0 +1,328 @@ + + * @author Alexander Makarov + * @since 2.0 + */ +class PhpDocController extends Controller +{ + public $defaultAction = 'property'; + + /** + * @var bool whether to update class docs directly. Setting this to false will just output docs + * for copy and paste. + */ + public $updateFiles = true; + + /** + * Generates @property annotations in class files from getters and setters + * + * Property description will be taken from getter or setter or from an @property annotation + * in the getters docblock if there is one defined. + * + * See https://github.com/yiisoft/yii2/wiki/Core-framework-code-style#documentation for details. + * + * @param null $root the directory to parse files from. Defaults to YII_PATH. + */ + public function actionProperty($root=null) + { + if ($root === null) { + $root = YII_PATH; + } + $root = FileHelper::normalizePath($root); + $options = array( + 'filter' => function ($path) { + if (is_file($path)) { + $file = basename($path); + if ($file[0] < 'A' || $file[0] > 'Z') { + return false; + } + } + return null; + }, + 'only' => array('.php'), + 'except' => array( + 'YiiBase.php', + 'Yii.php', + '/debug/views/', + '/requirements/', + '/gii/views/', + '/gii/generators/', + ), + ); + $files = FileHelper::findFiles($root, $options); + $nFilesTotal = 0; + $nFilesUpdated = 0; + foreach ($files as $file) { + $result = $this->generateClassPropertyDocs($file); + if ($result !== false) { + list($className, $phpdoc) = $result; + if ($this->updateFiles) { + if ($this->updateClassPropertyDocs($file, $className, $phpdoc)) { + $nFilesUpdated++; + } + } elseif (!empty($phpdoc)) { + $this->stdout("\n[ " . $file . " ]\n\n", Console::BOLD); + $this->stdout($phpdoc); + } + } + $nFilesTotal++; + } + + $this->stdout("\nParsed $nFilesTotal files.\n"); + $this->stdout("Updated $nFilesUpdated files.\n"); + } + + public function globalOptions() + { + return array_merge(parent::globalOptions(), array('updateFiles')); + } + + protected function updateClassPropertyDocs($file, $className, $propertyDoc) + { + $ref = new \ReflectionClass($className); + if ($ref->getFileName() != $file) { + $this->stderr("[ERR] Unable to create ReflectionClass for class: $className loaded class is not from file: $file\n", Console::FG_RED); + } + + if (!$ref->isSubclassOf('yii\base\Object') && $className != 'yii\base\Object') { + $this->stderr("[INFO] Skipping class $className as it is not a subclass of yii\\base\\Object.\n", Console::FG_BLUE, Console::BOLD); + return false; + } + + $oldDoc = $ref->getDocComment(); + $newDoc = $this->cleanDocComment($this->updateDocComment($oldDoc, $propertyDoc)); + + $seenSince = false; + $seenAuthor = false; + + // TODO move these checks to different action + $lines = explode("\n", $newDoc); + if (trim($lines[1]) == '*' || substr(trim($lines[1]), 0, 3) == '* @') { + $this->stderr("[WARN] Class $className has no short description.\n", Console::FG_YELLOW, Console::BOLD); + } + foreach($lines as $line) { + if (substr(trim($line), 0, 9) == '* @since ') { + $seenSince = true; + } elseif (substr(trim($line), 0, 10) == '* @author ') { + $seenAuthor = true; + } + } + + if (!$seenSince) { + $this->stderr("[ERR] No @since found in class doc in file: $file\n", Console::FG_RED); + } + if (!$seenAuthor) { + $this->stderr("[ERR] No @author found in class doc in file: $file\n", Console::FG_RED); + } + + if (trim($oldDoc) != trim($newDoc)) { + + $fileContent = explode("\n", file_get_contents($file)); + $start = $ref->getStartLine() - 2; + $docStart = $start - count(explode("\n", $oldDoc)) + 1; + + $newFileContent = array(); + $n = count($fileContent); + for($i = 0; $i < $n; $i++) { + if ($i > $start || $i < $docStart) { + $newFileContent[] = $fileContent[$i]; + } else { + $newFileContent[] = trim($newDoc); + $i = $start; + } + } + + file_put_contents($file, implode("\n", $newFileContent)); + + return true; + } + return false; + } + + /** + * remove multi empty lines and trim trailing whitespace + * + * @param $doc + * @return string + */ + protected function cleanDocComment($doc) + { + $lines = explode("\n", $doc); + $n = count($lines); + for($i = 0; $i < $n; $i++) { + $lines[$i] = rtrim($lines[$i]); + if (trim($lines[$i]) == '*' && trim($lines[$i + 1]) == '*') { + unset($lines[$i]); + } + } + return implode("\n", $lines); + } + + /** + * replace property annotations in doc comment + * @param $doc + * @param $properties + * @return string + */ + protected function updateDocComment($doc, $properties) + { + $lines = explode("\n", $doc); + $propertyPart = false; + $propertyPosition = false; + foreach($lines as $i => $line) { + if (substr(trim($line), 0, 12) == '* @property ') { + $propertyPart = true; + } elseif ($propertyPart && trim($line) == '*') { + $propertyPosition = $i; + $propertyPart = false; + } + if (substr(trim($line), 0, 10) == '* @author ' && $propertyPosition === false) { + $propertyPosition = $i - 1; + $propertyPart = false; + } + if ($propertyPart) { + unset($lines[$i]); + } + } + $finalDoc = ''; + foreach($lines as $i => $line) { + $finalDoc .= $line . "\n"; + if ($i == $propertyPosition) { + $finalDoc .= $properties; + } + } + return $finalDoc; + } + + protected function generateClassPropertyDocs($fileName) + { + $phpdoc = ""; + $file = str_replace("\r", "", str_replace("\t", " ", file_get_contents($fileName, true))); + $ns = $this->match('#\nnamespace (?[\w\\\\]+);\n#', $file); + $namespace = reset($ns); + $namespace = $namespace['name']; + $classes = $this->match('#\n(?:abstract )?class (?\w+)( |\n)(extends )?.+\{(?.*)\n\}(\n|$)#', $file); + + if (count($classes) > 1) { + $this->stderr("[ERR] There should be only one class in a file: $fileName\n", Console::FG_RED); + return false; + } + if (count($classes) < 1) { + $interfaces = $this->match('#\ninterface (?\w+)\n\{(?.+)\n\}(\n|$)#', $file); + if (count($interfaces) == 1) { + return false; + } elseif (count($interfaces) > 1) { + $this->stderr("[ERR] There should be only one interface in a file: $fileName\n", Console::FG_RED); + } else { + $this->stderr("[ERR] No class in file: $fileName\n", Console::FG_RED); + } + return false; + } + + $className = null; + foreach ($classes as &$class) { + + $className = $namespace . '\\' . $class['name']; + + $gets = $this->match( + '#\* @return (?[\w\\|\\\\\\[\\]]+)(?: (?(?:(?!\*/|\* @).)+?)(?:(?!\*/).)+|[\s\n]*)\*/' . + '[\s\n]{2,}public function (?get)(?\w+)\((?:,? ?\$\w+ ?= ?[^,]+)*\)#', + $class['content']); + $sets = $this->match( + '#\* @param (?[\w\\|\\\\\\[\\]]+) \$\w+(?: (?(?:(?!\*/|\* @).)+?)(?:(?!\*/).)+|[\s\n]*)\*/' . + '[\s\n]{2,}public function (?set)(?\w+)\(\$\w+(?:, ?\$\w+ ?= ?[^,]+)*\)#', + $class['content']); + // check for @property annotations in getter and setter + $properties = $this->match( + '#\* @(?property) (?[\w\\|\\\\\\[\\]]+)(?: (?(?:(?!\*/|\* @).)+?)(?:(?!\*/).)+|[\s\n]*)\*/' . + '[\s\n]{2,}public function [g|s]et(?\w+)\(((?:,? ?\$\w+ ?= ?[^,]+)*|\$\w+(?:, ?\$\w+ ?= ?[^,]+)*)\)#', + $class['content']); + $acrs = array_merge($properties, $gets, $sets); + //print_r($acrs); continue; + + $props = array(); + foreach ($acrs as &$acr) { + $acr['name'] = lcfirst($acr['name']); + $acr['comment'] = trim(preg_replace('#(^|\n)\s+\*\s?#', '$1 * ', $acr['comment'])); + $props[$acr['name']][$acr['kind']] = array( + 'type' => $acr['type'], + 'comment' => $this->fixSentence($acr['comment']), + ); + } + + ksort($props); + + if (count($props) > 0) { + $phpdoc .= " *\n"; + foreach ($props as $propName => &$prop) { + $docline = ' * @'; + $docline .= 'property'; // Do not use property-read and property-write as few IDEs support complex syntax. + $note = ''; + if (isset($prop['get']) && isset($prop['set'])) { + if ($prop['get']['type'] != $prop['set']['type']) { + $note = ' Note that the type of this property differs in getter and setter.' + . ' See [[get'.ucfirst($propName).'()]] and [[set'.ucfirst($propName).'()]] for details.'; + } + } elseif (isset($prop['get'])) { + $note = ' This property is read-only.'; +// $docline .= '-read'; + } elseif (isset($prop['set'])) { + $note = ' This property is write-only.'; +// $docline .= '-write'; + } else { + continue; + } + $docline .= ' ' . $this->getPropParam($prop, 'type') . " $$propName "; + $comment = explode("\n", $this->getPropParam($prop, 'comment') . $note); + foreach ($comment as &$cline) { + $cline = ltrim($cline, '* '); + } + $docline = wordwrap($docline . implode(' ', $comment), 110, "\n * ") . "\n"; + + $phpdoc .= $docline; + } + $phpdoc .= " *\n"; + } + } + return array($className, $phpdoc); + } + + protected function match($pattern, $subject) + { + $sets = array(); + preg_match_all($pattern . 'suU', $subject, $sets, PREG_SET_ORDER); + foreach ($sets as &$set) + foreach ($set as $i => $match) + if (is_numeric($i) /*&& $i != 0*/) + unset($set[$i]); + return $sets; + } + + protected function fixSentence($str) + { + // TODO fix word wrap + if ($str == '') + return ''; + return strtoupper(substr($str, 0, 1)) . substr($str, 1) . ($str[strlen($str) - 1] != '.' ? '.' : ''); + } + + protected function getPropParam($prop, $param) + { + return isset($prop['property']) ? $prop['property'][$param] : (isset($prop['get']) ? $prop['get'][$param] : $prop['set'][$param]); + } +} \ No newline at end of file diff --git a/docs/guide/active-record.md b/docs/guide/active-record.md index bb39115..fc98f98 100644 --- a/docs/guide/active-record.md +++ b/docs/guide/active-record.md @@ -1,17 +1,15 @@ Active Record ============= -ActiveRecord implements the [Active Record design pattern](http://en.wikipedia.org/wiki/Active_record). -The idea is that an [[ActiveRecord]] object is associated with a row in a database table and its attributes are mapped -to the columns of the corresponding table columns. Reading an ActiveRecord attribute is equivalent to accessing -the corresponding table column. For example, a `Customer` object is associated with a row in the -`tbl_customer` table, and its `name` attribute is mapped to the `name` column in the `tbl_customer` table. -To get the value of the `name` column in the table row, you can simply use the expression `$customer->name`, -just like reading an object property. - -Instead of writing raw SQL statements to perform database queries, you can call intuitive methods provided -by ActiveRecord to achieve the same goals. For example, calling [[ActiveRecord::save()|save()]] would -insert or update a row in the associated table of the ActiveRecord class: +Active Record implements the [Active Record design pattern](http://en.wikipedia.org/wiki/Active_record). +The premise behind Active Record is that an individual [[ActiveRecord]] object is associated with a specific row in a database table. The object's attributes are mapped to the columns of the corresponding table. Referencing an Active Record attribute is equivalent to accessing +the corresponding table column for that record. + +As an example, say that the `Customer` ActiveRecord class is associated with the +`tbl_customer` table. This would mean that the class's `name` attribute is automatically mapped to the `name` column in `tbl_customer`. +Thanks to Active Record, assuming the variable `$customer` is an object of type `Customer`, to get the value of the `name` column for the table row, you can use the expression `$customer->name`. In this example, Active Record is providing an object-oriented interface for accessing data stored in the database. But Active Record provides much more functionality than this. + +With Active Record, instead of writing raw SQL statements to perform database queries, you can call intuitive methods to achieve the same goals. For example, calling [[ActiveRecord::save()|save()]] would perform an INSERT or UPDATE query, creating or updating a row in the associated table of the ActiveRecord class: ```php $customer = new Customer(); @@ -24,7 +22,7 @@ Declaring ActiveRecord Classes ------------------------------ To declare an ActiveRecord class you need to extend [[\yii\db\ActiveRecord]] and -implement the `tableName` method like the following: +implement the `tableName` method: ```php use yii\db\ActiveRecord; @@ -41,13 +39,19 @@ class Customer extends ActiveRecord } ``` -Connecting to Database +The `tableName` method only has to return the name of the database table associated with the class. + +Class instances are obtained in one of two ways: + +* Using the `new` operator to create a new, empty object +* Using a method to fetch an existing record (or records) from the database + +Connecting to the Database ---------------------- ActiveRecord relies on a [[Connection|DB connection]] to perform the underlying DB operations. -By default, it assumes that there is an application component named `db` which gives the needed -[[Connection]] instance. Usually this component is configured via application configuration -like the following: +By default, ActiveRecord assumes that there is an application component named `db` which provides the needed +[[Connection]] instance. Usually this component is configured in application configuration file: ```php return array( @@ -62,16 +66,9 @@ return array( ); ``` -Please read the [Database basics](database-basics.md) section to learn more on how to configure -and use database connections. - -> Tip: To use a different database connection, you may override the [[ActiveRecord::getDb()]] method. -You may create a base ActiveRecord class and override its [[ActiveRecord::getDb()]] method. You -then extend from this base class for all those ActiveRecord classes that need to use the same -DB connection. +Please read the [Database basics](database-basics.md) section to learn more on how to configure and use database connections. - -Querying Data from Database +Querying Data from the Database --------------------------- There are two ActiveRecord methods for querying data from database: @@ -79,8 +76,8 @@ There are two ActiveRecord methods for querying data from database: - [[ActiveRecord::find()]] - [[ActiveRecord::findBySql()]] -They both return an [[ActiveQuery]] instance which extends from [[Query]] and thus supports -the same set of flexible and powerful DB query methods. The followings are some examples, +Both methods return an [[ActiveQuery]] instance, which extends [[Query]], and thus supports +the same set of flexible and powerful DB query methods. The following examples demonstrate some of the possibilities. ```php // to retrieve all *active* customers and order them by their ID: @@ -121,27 +118,26 @@ $customers = Customer::find()->indexBy('id')->all(); Accessing Column Data --------------------- -ActiveRecord maps each column of the corresponding database table row to an *attribute* in the ActiveRecord -object. An attribute is like a regular object property whose name is the same as the corresponding column -name and is case-sensitive. +ActiveRecord maps each column of the corresponding database table row to an attribute in the ActiveRecord +object. The attribute behaves like any regular object public property. The attribute's name will be the same as the corresponding column +name, and is case-sensitive. -To read the value of a column, you can use the following expression: +To read the value of a column, you can use the following syntax: ```php -// "id" is the name of a column in the table associated with $customer ActiveRecord object +// "id" and "email" are the names of columns in the table associated with $customer ActiveRecord object $id = $customer->id; -// or alternatively, -$id = $customer->getAttribute('id'); +$email = $customer->email; ``` -You can get all column values through the [[ActiveRecord::attributes]] property: +To change the value of a column, assign a new value to the associated property and save the object: -```php -$values = $customer->attributes; +``` +$customer->email = 'jane@example.com'; +$customer->save(); ``` - -Manipulating Data in Database +Manipulating Data in the Database ----------------------------- ActiveRecord provides the following methods to insert, update and delete data in the database: @@ -156,10 +152,8 @@ ActiveRecord provides the following methods to insert, update and delete data in - [[ActiveRecord::deleteAll()|deleteAll()]] Note that [[ActiveRecord::updateAll()|updateAll()]], [[ActiveRecord::updateAllCounters()|updateAllCounters()]] -and [[ActiveRecord::deleteAll()|deleteAll()]] are static methods and apply to the whole database -table, while the rest of the methods only apply to the row associated with the ActiveRecord object. - -The followings are some examples: +and [[ActiveRecord::deleteAll()|deleteAll()]] are static methods that apply to the whole database +table. The other methods only apply to the row associated with the ActiveRecord object through which the method is being called. ```php // to insert a new customer record @@ -181,12 +175,21 @@ $customer->delete(); Customer::updateAllCounters(array('age' => 1)); ``` +Notice that you can always use the `save` method, and ActiveRecord will automatically perform an INSERT for new records and an UPDATE for existing ones. + +Data Input and Validation +------------------------- + +ActiveRecord inherits data validation and data input features from [[\yii\base\Model]]. Data validation is called +automatically when `save()` is performed. If data validation fails, the saving operation will be cancelled. + +For more details refer to the [Model](model.md) section of this guide. Querying Relational Data ------------------------ -You can use ActiveRecord to query the relational data of a table. The relational data returned can -be accessed like a property of the ActiveRecord object associated with the primary table. +You can use ActiveRecord to also query a table's relational data (i.e., selection of data from Table A can also pull in related data from Table B). Thanks to ActiveRecord, the relational data returned can be accessed like a property of the ActiveRecord object associated with the primary table. + For example, with an appropriate relation declaration, by accessing `$customer->orders` you may obtain an array of `Order` objects which represent the orders placed by the specified customer. @@ -405,15 +408,6 @@ The [[link()]] call above will set the `customer_id` of the order to be the prim value of `$customer` and then call [[save()]] to save the order into database. -Data Input and Validation -------------------------- - -ActiveRecord inherits data validation and data input features from [[\yii\base\Model]]. Data validation is called -automatically when `save()` is performed. If data validation fails, the saving operation will be cancelled. - -For more details refer to the [Model](model.md) section of this guide. - - Life Cycles of an ActiveRecord Object ------------------------------------- diff --git a/docs/guide/bootstrap-widgets.md b/docs/guide/bootstrap-widgets.md index 0739847..3f56839 100644 --- a/docs/guide/bootstrap-widgets.md +++ b/docs/guide/bootstrap-widgets.md @@ -1,13 +1,12 @@ Bootstrap widgets ================= -Yii includes support of [Bootstrap 3](http://getbootstrap.com/) markup and components framework out of the box. It is an -excellent framework that allows you to speed up development a lot. +Yii includes support for the [Bootstrap 3](http://getbootstrap.com/) markup and components framework out of the box. Bootstrap is an excellent, responsive framework that can greatly speed up your development process. -Bootstrap is generally about two parts: +The core of Bootstrap is represented by two parts: -- Basics such as grid system, typography, helper classes and responsive utilities. -- Ready to use components such as menus, pagination, modal boxes, tabs etc. +- CSS basics, such as grid layout system, typography, helper classes, and responsive utilities. +- Ready to use components, such as menus, pagination, modal boxes, tabs etc. Basics ------ diff --git a/docs/guide/database-basics.md b/docs/guide/database-basics.md index 71510f4..85bc042 100644 --- a/docs/guide/database-basics.md +++ b/docs/guide/database-basics.md @@ -2,8 +2,14 @@ Database basics =============== Yii has a database access layer built on top of PHP's [PDO](http://www.php.net/manual/en/ref.pdo.php). It provides -uniform API and solves some inconsistencies between different DBMS. By default Yii supports MySQL, SQLite, PostgreSQL, -Oracle and MSSQL. +uniform API and solves some inconsistencies between different DBMS. By default Yii supports the following DBMS: + +- [MySQL](http://www.mysql.com/) +- [SQLite](http://sqlite.org/) +- [PostgreSQL](http://www.postgresql.org/) +- [CUBRID](http://www.cubrid.org/) (version 9.1.0 and higher). +- Oracle +- MSSQL Configuration @@ -22,6 +28,7 @@ return array( 'dsn' => 'mysql:host=localhost;dbname=mydatabase', // MySQL, MariaDB //'dsn' => 'sqlite:/path/to/database/file', // SQLite //'dsn' => 'pgsql:host=localhost;port=5432;dbname=mydatabase', // PostgreSQL + //'dsn' => 'cubrid:dbname=demodb;host=localhost;port=33000', // CUBRID //'dsn' => 'sqlsrv:Server=localhost;Database=mydatabase', // MS SQL Server, sqlsrv driver //'dsn' => 'dblib:host=localhost;dbname=mydatabase', // MS SQL Server, dblib driver //'dsn' => 'mssql:host=localhost;dbname=mydatabase', // MS SQL Server, mssql driver @@ -34,8 +41,10 @@ return array( // ... ); ``` +Please refer to the [PHP manual](http://www.php.net/manual/en/function.PDO-construct.php) for more details +on the format of the DSN string. -After the component is configured you can access it using the following syntax: +After the connection component is configured you can access it using the following syntax: ```php $connection = \Yii::$app->db; @@ -79,7 +88,7 @@ When only a single row is returned: ```php $command = $connection->createCommand('SELECT * FROM tbl_post WHERE id=1'); -$post = $command->query(); +$post = $command->queryOne(); ``` When there are multiple values from the same column: diff --git a/docs/guide/overview.md b/docs/guide/overview.md index d2ccb19..ef71aa0 100644 --- a/docs/guide/overview.md +++ b/docs/guide/overview.md @@ -1,8 +1,7 @@ What is Yii =========== -Yii is a high-performance, component-based PHP framework for developing -large-scale Web applications rapidly. It enables maximum reusability in Web +Yii is a high-performance, component-based PHP framework for rapidly developing large-scale Web applications. Yii enables maximum reusability in Web programming and can significantly accelerate your Web application development process. The name Yii (pronounced `Yee` or `[ji:]`) is an acronym for **Yes It Is!**. @@ -12,7 +11,7 @@ Requirements ------------ To run a Yii-powered Web application, you need a Web server that supports -PHP 5.3.?. +PHP 5.3.? or greater. For developers who want to use Yii, understanding object-oriented programming (OOP) is very helpful, because Yii is a pure OOP framework. @@ -31,10 +30,9 @@ management systems (CMS), e-commerce systems, etc. How does Yii Compare with Other Frameworks? ------------------------------------------- -- Like most PHP frameworks, Yii is an MVC (Model-View-Controller) framework. -- It is a fullstack framework providing many solutions and components such as logging, session management, caching etc. -- It has a good balance of simplicity and features. -- Syntax and overall development usability are taken seriously. -- Performance is one of the key goals. -- We are constantly watching other web frameworks out there and getting the best ideas in. Initial Yii release was heavily - influenced by Ruby on Rails. Still, we aren't blindly copying anything. +- Like most PHP frameworks, Yii is uses the MVC (Model-View-Controller) design approach. +- Yii is a fullstack framework providing many solutions and components, such as logging, session management, caching etc. +- Yii strikes a good balance between simplicity and features. +- Syntax and overall development usability are taken seriously by the Yii development team. +- Performance is one of the key goals for the Yii framework. +- The Yii development team is constantly watching what other Web frameworks are doing to see what best practices and features should be incorporated into Yii. The initial Yii release was heavily influenced by Ruby on Rails. Still, no framework or feature is being blindly copied into Yii; all decisions are based upon what's best for Web developers and in keeping with Yii's philosophy. diff --git a/docs/guide/template.md b/docs/guide/template.md index f2a6fc4..6d2db88 100644 --- a/docs/guide/template.md +++ b/docs/guide/template.md @@ -1,8 +1,7 @@ Using template engines ====================== -By default Yii uses PHP as template language but you can configure it to be able -to render templates with special engines such as Twig or Smarty. +By default Yii uses PHP as template language, but you can configure it to support other rendering engines, such as [Twig](http://twig.sensiolabs.org/) or [Smarty](http://www.smarty.net/). The component responsible for rendering a view is called `view`. You can add a custom template engines as follows: diff --git a/docs/guide/validation.md b/docs/guide/validation.md index 7bfeb96..0322573 100644 --- a/docs/guide/validation.md +++ b/docs/guide/validation.md @@ -7,22 +7,176 @@ In order to learn model validation basics please refer to [Model, Validation sub Standard Yii validators ----------------------- -- `boolean`: [[BooleanValidator]] -- `captcha`: [[CaptchaValidator]] -- `compare`: [[CompareValidator]] -- `date`: [[DateValidator]] -- `default`: [[DefaultValueValidator]] -- `double`: [[NumberValidator]] -- `email`: [[EmailValidator]] -- `exist`: [[ExistValidator]] -- `file`: [[FileValidator]] -- `filter`: [[FilterValidator]] -- `in`: [[RangeValidator]] -- `integer`: [[NumberValidator]] -- `match`: [[RegularExpressionValidator]] -- `required`: [[RequiredValidator]] -- `string`: [[StringValidator]] -- `unique`: [[UniqueValidator]] -- `url`: [[UrlValidator]] +Standard Yii validators could be specified using aliases instead of referring to class names. Here's the list of all +validators budled with Yii with their most useful properties: + +### `boolean`: [[BooleanValidator]] + +Checks if the attribute value is a boolean value. + +- `trueValue`, the value representing true status. _(1)_ +- `falseValue`, the value representing false status. _(0)_ +- `strict`, whether to compare the type of the value and `trueValue`/`falseValue`. _(false)_ + +### `captcha`: [[CaptchaValidator]] + +Validates that the attribute value is the same as the verification code displayed in the CAPTCHA. Should be used together +with [[CaptchaAction]]. + +- `caseSensitive` whether the comparison is case sensitive. _(false)_ +- `captchaAction` the route of the controller action that renders the CAPTCHA image. _('site/captcha')_ + +### `compare`: [[CompareValidator]] + +Compares the specified attribute value with another value and validates if they are equal. + +- `compareAttribute` the name of the attribute to be compared with. _(currentAttribute_repeat)_ +- `compareValue` the constant value to be compared with. +- `operator` the operator for comparison. _('==')_ + +### `date`: [[DateValidator]] + +Verifies if the attribute represents a date, time or datetime in a proper format. + +- `format` the date format that the value being validated should follow accodring to [[http://www.php.net/manual/en/datetime.createfromformat.php]]. _('Y-m-d')_ +- `timestampAttribute` the name of the attribute to receive the parsing result. + +### `default`: [[DefaultValueValidator]] + +Sets the attribute to be the specified default value. + +- `value` the default value to be set to the specified attributes. + +### `double`: [[NumberValidator]] + +Validates that the attribute value is a number. + +- `max` limit of the number. _(null)_ +- `min` lower limit of the number. _(null)_ + +### `email`: [[EmailValidator]] + +Validates that the attribute value is a valid email address. + +- `allowName` whether to allow name in the email address (e.g. `John Smith `). _(false)_. +- `checkMX` whether to check the MX record for the email address. _(false)_ +- `checkPort` whether to check port 25 for the email address. _(false)_ +- `enableIDN` whether validation process should take into account IDN (internationalized domain names). _(false)_ + +### `exist`: [[ExistValidator]] + +Validates that the attribute value exists in a table. + +- `className` the ActiveRecord class name or alias of the class that should be used to look for the attribute value being + validated. _(ActiveRecord class of the attribute being validated)_ +- `attributeName` the ActiveRecord attribute name that should be used to look for the attribute value being validated. + _(name of the attribute being validated)_ + +### `file`: [[FileValidator]] + +Verifies if an attribute is receiving a valid uploaded file. + +- `types` a list of file name extensions that are allowed to be uploaded. _(any)_ +- `minSize` the minimum number of bytes required for the uploaded file. +- `maxSize` the maximum number of bytes required for the uploaded file. +- `maxFiles` the maximum file count the given attribute can hold. _(1)_ + +### `filter`: [[FilterValidator]] + +Converts the attribute value according to a filter. + +- `filter` PHP callback that defines a filter. + +Typically a callback is either the name of PHP function: + +```php +array('password', 'filter', 'filter' => 'trim'), +``` + +Or an anonymous function: + +```php +array('text', 'filter', 'filter' => function ($value) { + // here we are removing all swear words from text + return $newValue; +}), +``` + +### `in`: [[RangeValidator]] + +Validates that the attribute value is among a list of values. + +- `range` list of valid values that the attribute value should be among. +- `strict` whether the comparison is strict (both type and value must be the same). _(false)_ +- `not` whether to invert the validation logic. _(false)_ + +### `integer`: [[NumberValidator]] + +Validates that the attribute value is an integer number. + +- `max` limit of the number. _(null)_ +- `min` lower limit of the number. _(null)_ + +### `match`: [[RegularExpressionValidator]] + +Validates that the attribute value matches the specified pattern defined by regular expression. + +- `pattern` the regular expression to be matched with. +- `not` whether to invert the validation logic. _(false)_ + +### `required`: [[RequiredValidator]] + +Validates that the specified attribute does not have null or empty value. + +- `requiredValue` the desired value that the attribute must have. _(any)_ +- `strict` whether the comparison between the attribute value and [[requiredValue]] is strict. _(false)_ + +### `safe`: [[SafeValidator]] + +Serves as a dummy validator whose main purpose is to mark the attributes to be safe for massive assignment. + +### `string`: [[StringValidator]] + +Validates that the attribute value is of certain length. + +- `length` specifies the length limit of the value to be validated. Can be `exactly X`, `array(min X)`, `array(min X, max Y)`. +- `max` maximum length. If not set, it means no maximum length limit. +- `min` minimum length. If not set, it means no minimum length limit. +- `encoding` the encoding of the string value to be validated. _([[\yii\base\Application::charset]])_ + +### `unique`: [[UniqueValidator]] + +Validates that the attribute value is unique in the corresponding database table. + +- `className` the ActiveRecord class name or alias of the class that should be used to look for the attribute value being + validated. _(ActiveRecord class of the attribute being validated)_ +- `attributeName` the ActiveRecord attribute name that should be used to look for the attribute value being validated. + _(name of the attribute being validated)_ + +### `url`: [[UrlValidator]] + +Validates that the attribute value is a valid http or https URL. + +- `validSchemes` list of URI schemes which should be considered valid. _array('http', 'https')_ +- `defaultScheme` the default URI scheme. If the input doesn't contain the scheme part, the default scheme will be + prepended to it. _(null)_ +- `enableIDN` whether validation process should take into account IDN (internationalized domain names). _(false)_ + +Validating values out of model context +-------------------------------------- + +Sometimes you need to validate a value that is not bound to any model such as email. In Yii `Validator` class has +`validateValue` method that can help you with it. Not all validator classes have it implemented but the ones that can +operate without model do. In our case to validate an email we can do the following: + +```php +$email = 'test@example.com'; +$validator = new yii\validators\EmailValidator(); +if ($validator->validateValue($email)) { + echo 'Email is valid.'; +} else { + echo 'Email is not valid.' +} +``` TBD: refer to http://www.yiiframework.com/wiki/56/ for the format \ No newline at end of file diff --git a/extensions/mutex/yii/mutex/FileMutex.php b/extensions/mutex/yii/mutex/FileMutex.php index 4a949d0..5ac9262 100644 --- a/extensions/mutex/yii/mutex/FileMutex.php +++ b/extensions/mutex/yii/mutex/FileMutex.php @@ -9,6 +9,7 @@ namespace yii\mutex; use Yii; use yii\base\InvalidConfigException; +use yii\helpers\FileHelper; /** * @author resurtm @@ -18,10 +19,23 @@ class FileMutex extends Mutex { /** * @var string the directory to store mutex files. You may use path alias here. - * If not set, it will use the "mutex" subdirectory under the application runtime path. + * Defaults to the "mutex" subdirectory under the application runtime path. */ public $mutexPath = '@runtime/mutex'; /** + * @var integer the permission to be set for newly created mutex files. + * This value will be used by PHP chmod() function. No umask will be applied. + * If not set, the permission will be determined by the current environment. + */ + public $fileMode; + /** + * @var integer the permission to be set for newly created directories. + * This value will be used by PHP chmod() function. No umask will be applied. + * Defaults to 0775, meaning the directory is read-writable by owner and group, + * but read-only for other users. + */ + public $dirMode = 0775; + /** * @var resource[] stores all opened lock files. Keys are lock names and values are file handles. */ private $_files = array(); @@ -39,22 +53,26 @@ class FileMutex extends Mutex } $this->mutexPath = Yii::getAlias($this->mutexPath); if (!is_dir($this->mutexPath)) { - mkdir($this->mutexPath, 0777, true); + FileHelper::createDirectory($this->mutexPath, $this->dirMode, true); } } /** - * This method should be extended by concrete mutex implementations. Acquires lock by given name. + * Acquires lock by given name. * @param string $name of the lock to be acquired. * @param integer $timeout to wait for lock to become released. * @return boolean acquiring result. */ protected function acquireLock($name, $timeout = 0) { - $file = fopen($this->mutexPath . '/' . md5($name) . '.lock', 'w+'); + $fileName = $this->mutexPath . '/' . md5($name) . '.lock'; + $file = fopen($fileName, 'w+'); if ($file === false) { return false; } + if ($this->fileMode !== null) { + @chmod($fileName, $this->fileMode); + } $waitTime = 0; while (!flock($file, LOCK_EX | LOCK_NB)) { $waitTime++; @@ -69,7 +87,7 @@ class FileMutex extends Mutex } /** - * This method should be extended by concrete mutex implementations. Releases lock by given name. + * Releases lock by given name. * @param string $name of the lock to be released. * @return boolean release result. */ diff --git a/extensions/mutex/yii/mutex/Mutex.php b/extensions/mutex/yii/mutex/Mutex.php index 297abaf..8f0a560 100644 --- a/extensions/mutex/yii/mutex/Mutex.php +++ b/extensions/mutex/yii/mutex/Mutex.php @@ -45,6 +45,7 @@ abstract class Mutex extends Component } /** + * Acquires lock by given name. * @param string $name of the lock to be acquired. Must be unique. * @param integer $timeout to wait for lock to be released. Defaults to zero meaning that method will return * false immediately in case lock was already acquired. diff --git a/extensions/mutex/yii/mutex/MysqlMutex.php b/extensions/mutex/yii/mutex/MysqlMutex.php index b04427a..f1c7cd1 100644 --- a/extensions/mutex/yii/mutex/MysqlMutex.php +++ b/extensions/mutex/yii/mutex/MysqlMutex.php @@ -29,7 +29,7 @@ class MysqlMutex extends Mutex } /** - * This method should be extended by concrete mutex implementations. Acquires lock by given name. + * Acquires lock by given name. * @param string $name of the lock to be acquired. * @param integer $timeout to wait for lock to become released. * @return boolean acquiring result. @@ -43,7 +43,7 @@ class MysqlMutex extends Mutex } /** - * This method should be extended by concrete mutex implementations. Releases lock by given name. + * Releases lock by given name. * @param string $name of the lock to be released. * @return boolean release result. * @see http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock diff --git a/framework/yii/YiiBase.php b/framework/yii/YiiBase.php index a5a3833..f04903d 100644 --- a/framework/yii/YiiBase.php +++ b/framework/yii/YiiBase.php @@ -100,7 +100,6 @@ class YiiBase */ public static $objectConfig = array(); - private static $_imported = array(); // alias => class name or directory /** * @return string the version of Yii framework @@ -111,40 +110,6 @@ class YiiBase } /** - * Imports a class by its alias. - * - * This method is provided to support autoloading of non-namespaced classes. - * Such a class can be specified in terms of an alias. For example, the alias `@old/code/Sample` - * may represent the `Sample` class under the directory `@old/code` (a path alias). - * - * By importing a class, the class is put in an internal storage such that when - * the class is used for the first time, the class autoloader will be able to - * find the corresponding class file and include it. For this reason, this method - * is much lighter than `include()`. - * - * You may import the same class multiple times. Only the first importing will count. - * - * @param string $alias the class to be imported. This may be either a class alias or a fully-qualified class name. - * If the latter, it will be returned back without change. - * @return string the actual class name that `$alias` refers to - * @throws Exception if the alias is invalid - */ - public static function import($alias) - { - if (strncmp($alias, '@', 1)) { - return $alias; - } else { - $alias = static::getAlias($alias); - if (!isset(self::$_imported[$alias])) { - $className = basename($alias); - self::$_imported[$alias] = $className; - self::$classMap[$className] = $alias . '.php'; - } - return self::$_imported[$alias]; - } - } - - /** * Imports a set of namespaces. * * By importing a namespace, the method will create an alias for the directory corresponding @@ -370,7 +335,7 @@ class YiiBase include($classFile); - if (!class_exists($className, false) && !interface_exists($className, false) && + if (YII_DEBUG && !class_exists($className, false) && !interface_exists($className, false) && (!function_exists('trait_exists') || !trait_exists($className, false))) { throw new UnknownClassException("Unable to find '$className' in file: $classFile"); } @@ -431,10 +396,6 @@ class YiiBase throw new InvalidConfigException('Object configuration must be an array containing a "class" element.'); } - if (!class_exists($class, false)) { - $class = static::import($class); - } - $class = ltrim($class, '\\'); if (isset(self::$objectConfig[$class])) { diff --git a/framework/yii/assets/yii.js b/framework/yii/assets/yii.js index 31a57d5..eb5ecf6 100644 --- a/framework/yii/assets/yii.js +++ b/framework/yii/assets/yii.js @@ -43,7 +43,20 @@ */ yii = (function ($) { var pub = { - version: '2.0', + /** + * @return string|undefined the CSRF variable name. Undefined is returned is CSRF validation is not enabled. + */ + getCsrfVar: function() { + return $('meta[name=csrf-var]').prop('content'); + }, + + /** + * @return string|undefined the CSRF token. Undefined is returned is CSRF validation is not enabled. + */ + getCsrfToken: function() { + return $('meta[name=csrf-token]').prop('content'); + }, + initModule: function (module) { if (module.isActive === undefined || module.isActive) { if ($.isFunction(module.init)) { diff --git a/framework/yii/base/Action.php b/framework/yii/base/Action.php index a4ae163..2693003 100644 --- a/framework/yii/base/Action.php +++ b/framework/yii/base/Action.php @@ -28,6 +28,9 @@ use Yii; * And the parameters provided for the action are: `array('id' => 1)`. * Then the `run()` method will be invoked as `run(1)` automatically. * + * @property string $uniqueId The unique ID of this action among the whole application. This property is + * read-only. + * * @author Qiang Xue * @since 2.0 */ diff --git a/framework/yii/base/Application.php b/framework/yii/base/Application.php index 0d0dd89..e8c496c 100644 --- a/framework/yii/base/Application.php +++ b/framework/yii/base/Application.php @@ -14,6 +14,24 @@ use yii\web\HttpException; /** * Application is the base class for all application classes. * + * @property \yii\rbac\Manager $authManager The auth manager for this application. This property is read-only. + * @property \yii\caching\Cache $cache The cache application component. Null if the component is not enabled. + * This property is read-only. + * @property \yii\db\Connection $db The database connection. This property is read-only. + * @property ErrorHandler $errorHandler The error handler application component. This property is read-only. + * @property \yii\base\Formatter $formatter The formatter application component. This property is read-only. + * @property \yii\i18n\I18N $i18N The internationalization component. This property is read-only. + * @property \yii\log\Logger $log The log component. This property is read-only. + * @property \yii\web\Request|\yii\console\Request $request The request component. This property is read-only. + * @property string $runtimePath The directory that stores runtime files. Defaults to the "runtime" + * subdirectory under [[basePath]]. + * @property string $timeZone The time zone used by this application. + * @property string $uniqueId The unique ID of the module. This property is read-only. + * @property \yii\web\UrlManager $urlManager The URL manager for this application. This property is read-only. + * @property string $vendorPath The directory that stores vendor files. Defaults to "vendor" directory under + * [[basePath]]. + * @property View $view The view object that is used to render various view files. This property is read-only. + * * @author Qiang Xue * @since 2.0 */ @@ -68,7 +86,7 @@ abstract class Application extends Module */ public $controller; /** - * @var mixed the layout that should be applied for views in this application. Defaults to 'main'. + * @var string|boolean the layout that should be applied for views in this application. Defaults to 'main'. * If this is false, layout will be disabled. */ public $layout = 'main'; diff --git a/framework/yii/base/Component.php b/framework/yii/base/Component.php index 5ff8ae4..2ad2c94 100644 --- a/framework/yii/base/Component.php +++ b/framework/yii/base/Component.php @@ -11,6 +11,9 @@ use Yii; /** * @include @yii/base/Component.md + * + * @property Behavior[] $behaviors List of behaviors attached to this component. This property is read-only. + * * @author Qiang Xue * @since 2.0 */ @@ -35,9 +38,9 @@ class Component extends Object * Do not call this method directly as it is a PHP magic method that * will be implicitly called when executing `$value = $component->property;`. * @param string $name the property name - * @return mixed the property value, event handlers attached to the event, - * the behavior, or the value of a behavior's property + * @return mixed the property value or the value of a behavior's property * @throws UnknownPropertyException if the property is not defined + * @throws InvalidCallException if the property is write-only. * @see __set */ public function __get($name) @@ -55,7 +58,11 @@ class Component extends Object } } } - throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name); + if (method_exists($this, 'set' . $name)) { + throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name); + } else { + throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name); + } } /** @@ -172,9 +179,8 @@ class Component extends Object /** * Calls the named method which is not a class method. - * If the name refers to a component property whose value is - * an anonymous function, the method will execute the function. - * Otherwise, it will check if any attached behavior has + * + * This method will check if any attached behavior has * the named method and will execute it if available. * * Do not call this method directly as it is a PHP magic method that @@ -186,17 +192,9 @@ class Component extends Object */ public function __call($name, $params) { - $getter = 'get' . $name; - if (method_exists($this, $getter)) { - $func = $this->$getter(); - if ($func instanceof \Closure) { - return call_user_func_array($func, $params); - } - } - $this->ensureBehaviors(); foreach ($this->_behaviors as $object) { - if (method_exists($object, $name)) { + if ($object->hasMethod($name)) { return call_user_func_array(array($object, $name), $params); } } @@ -261,8 +259,8 @@ class Component extends Object return true; } } - return false; } + return false; } /** @@ -291,8 +289,34 @@ class Component extends Object return true; } } - return false; } + return false; + } + + /** + * Returns a value indicating whether a method is defined. + * A method is defined if: + * + * - the class has a method with the specified name + * - an attached behavior has a method with the given name (when `$checkBehaviors` is true). + * + * @param string $name the property name + * @param boolean $checkBehaviors whether to treat behaviors' methods as methods of this component + * @return boolean whether the property is defined + */ + public function hasMethod($name, $checkBehaviors = true) + { + if (method_exists($this, $name)) { + return true; + } elseif ($checkBehaviors) { + $this->ensureBehaviors(); + foreach ($this->_behaviors as $behavior) { + if ($behavior->hasMethod($name)) { + return true; + } + } + } + return false; } /** diff --git a/framework/yii/base/Controller.php b/framework/yii/base/Controller.php index 5289b5b..20f6e2b 100644 --- a/framework/yii/base/Controller.php +++ b/framework/yii/base/Controller.php @@ -12,6 +12,16 @@ use Yii; /** * Controller is the base class for classes containing controller logic. * + * @property array $actionParams The request parameters (name-value pairs) to be used for action parameter + * binding. This property is read-only. + * @property string $route The route (module ID, controller ID and action ID) of the current request. This + * property is read-only. + * @property string $uniqueId The controller ID that is prefixed with the module ID (if any). This property is + * read-only. + * @property View $view The view object that can be used to render views or view files. + * @property string $viewPath The directory containing the view files for this controller. This property is + * read-only. + * * @author Qiang Xue * @since 2.0 */ diff --git a/framework/yii/base/Formatter.php b/framework/yii/base/Formatter.php index 50b656a..84b4b8d 100644 --- a/framework/yii/base/Formatter.php +++ b/framework/yii/base/Formatter.php @@ -309,7 +309,7 @@ class Formatter extends Component /** * Normalizes the given datetime value as one that can be taken by various date/time formatting methods. * @param mixed $value the datetime value to be normalized. - * @return mixed the normalized datetime value + * @return integer the normalized datetime value */ protected function normalizeDatetimeValue($value) { diff --git a/framework/yii/base/Model.php b/framework/yii/base/Model.php index 82083da..93b5a6b 100644 --- a/framework/yii/base/Model.php +++ b/framework/yii/base/Model.php @@ -36,11 +36,17 @@ use yii\validators\Validator; * You may directly use Model to store model data, or extend it with customization. * You may also customize Model by attaching [[ModelBehavior|model behaviors]]. * - * @property ArrayObject $validators All the validators declared in the model. - * @property array $activeValidators The validators applicable to the current [[scenario]]. - * @property array $errors Errors for all attributes or the specified attribute. Empty array is returned if no error. + * @property \yii\validators\Validator[] $activeValidators The validators applicable to the current + * [[scenario]]. This property is read-only. * @property array $attributes Attribute values (name => value). - * @property string $scenario The scenario that this model is in. + * @property array $errors An array of errors for all attributes. Empty array is returned if no error. The + * result is a two-dimensional array. See [[getErrors()]] for detailed description. This property is read-only. + * @property array $firstErrors The first errors. An empty array will be returned if there is no error. This + * property is read-only. + * @property ArrayIterator $iterator An iterator for traversing the items in the list. This property is + * read-only. + * @property string $scenario The scenario that this model is in. Defaults to [[DEFAULT_SCENARIO]]. + * @property ArrayObject $validators All the validators declared in the model. This property is read-only. * * @author Qiang Xue * @since 2.0 @@ -48,6 +54,11 @@ use yii\validators\Validator; class Model extends Component implements IteratorAggregate, ArrayAccess { /** + * The name of the default scenario. + */ + const DEFAULT_SCENARIO = 'default'; + + /** * @event ModelEvent an event raised at the beginning of [[validate()]]. You may set * [[ModelEvent::isValid]] to be false to stop the validation. */ @@ -68,7 +79,7 @@ class Model extends Component implements IteratorAggregate, ArrayAccess /** * @var string current scenario */ - private $_scenario = 'default'; + private $_scenario = self::DEFAULT_SCENARIO; /** * Returns the validation rules for attributes. @@ -105,6 +116,10 @@ class Model extends Component implements IteratorAggregate, ArrayAccess * function validatorName($attribute, $params) * ~~~ * + * In the above `$attribute` refers to currently validated attribute name while `$params` contains an array of + * validator configuration options such as `max` in case of `length` validator. Currently validate attribute value + * can be accessed as `$this->[$attribute]`. + * * Yii also provides a set of [[Validator::builtInValidators|built-in validators]]. * They each has an alias name which can be used when specifying a validation rule. * @@ -153,23 +168,39 @@ class Model extends Component implements IteratorAggregate, ArrayAccess * If an attribute should NOT be massively assigned (thus considered unsafe), * please prefix the attribute with an exclamation character (e.g. '!rank'). * - * The default implementation of this method will return a 'default' scenario - * which corresponds to all attributes listed in the validation rules applicable - * to the 'default' scenario. + * The default implementation of this method will return all scenarios found in the [[rules()]] + * declaration. A special scenario named [[DEFAULT_SCENARIO]] will contain all attributes + * found in the [[rules()]]. Each scenario will be associated with the attributes that + * are being validated by the validation rules that apply to the scenario. * * @return array a list of scenarios and the corresponding active attributes. */ public function scenarios() { - $attributes = array(); - foreach ($this->getActiveValidators() as $validator) { - foreach ($validator->attributes as $name) { - $attributes[$name] = true; + $scenarios = array(); + $defaults = array(); + /** @var $validator Validator */ + foreach ($this->getValidators() as $validator) { + if (empty($validator->on)) { + foreach ($validator->attributes as $attribute) { + $defaults[$attribute] = true; + } + } else { + foreach ($validator->on as $scenario) { + foreach ($validator->attributes as $attribute) { + $scenarios[$scenario][$attribute] = true; + } + } } } - return array( - 'default' => array_keys($attributes), - ); + foreach ($scenarios as $scenario => $attributes) { + foreach (array_keys($defaults) as $attribute) { + $attributes[$attribute] = true; + } + $scenarios[$scenario] = array_keys($attributes); + } + $scenarios[self::DEFAULT_SCENARIO] = array_keys($defaults); + return $scenarios; } /** @@ -244,8 +275,8 @@ class Model extends Component implements IteratorAggregate, ArrayAccess * after the actual validation, respectively. If [[beforeValidate()]] returns false, * the validation will be cancelled and [[afterValidate()]] will not be called. * - * Errors found during the validation can be retrieved via [[getErrors()]] - * and [[getError()]]. + * Errors found during the validation can be retrieved via [[getErrors()]], + * [[getFirstErrors()]] and [[getFirstError()]]. * * @param array $attributes list of attributes that should be validated. * If this parameter is empty, it means any attribute listed in the applicable @@ -423,6 +454,8 @@ class Model extends Component implements IteratorAggregate, ArrayAccess /** * Returns the errors for all attribute or a single attribute. * @param string $attribute attribute name. Use null to retrieve errors for all attributes. + * @property array An array of errors for all attributes. Empty array is returned if no error. + * The result is a two-dimensional array. See [[getErrors()]] for detailed description. * @return array errors for all attributes or the specified attribute. Empty array is returned if no error. * Note that when returning errors for all attributes, the result is a two-dimensional array, like the following: * @@ -438,7 +471,8 @@ class Model extends Component implements IteratorAggregate, ArrayAccess * ) * ~~~ * - * @see getError + * @see getFirstErrors + * @see getFirstError */ public function getErrors($attribute = null) { @@ -452,6 +486,8 @@ class Model extends Component implements IteratorAggregate, ArrayAccess /** * Returns the first error of every attribute in the model. * @return array the first errors. An empty array will be returned if there is no error. + * @see getErrors + * @see getFirstError */ public function getFirstErrors() { @@ -473,6 +509,7 @@ class Model extends Component implements IteratorAggregate, ArrayAccess * @param string $attribute attribute name. * @return string the error message. Null is returned if no error. * @see getErrors + * @see getFirstErrors */ public function getFirstError($attribute) { @@ -581,7 +618,7 @@ class Model extends Component implements IteratorAggregate, ArrayAccess * Scenario affects how validation is performed and which attributes can * be massively assigned. * - * @return string the scenario that this model is in. Defaults to 'default'. + * @return string the scenario that this model is in. Defaults to [[DEFAULT_SCENARIO]]. */ public function getScenario() { diff --git a/framework/yii/base/Module.php b/framework/yii/base/Module.php index a85385b..de75ce7 100644 --- a/framework/yii/base/Module.php +++ b/framework/yii/base/Module.php @@ -20,16 +20,16 @@ use Yii; * [[components|Components]] may be registered with the module so that they are globally * accessible within the module. * - * @property string $uniqueId An ID that uniquely identifies this module among all modules within - * the current application. - * @property string $basePath The root directory of the module. Defaults to the directory containing the module class. - * @property string $controllerPath The directory containing the controller classes. Defaults to "[[basePath]]/controllers". - * @property string $viewPath The directory containing the view files within this module. Defaults to "[[basePath]]/views". - * @property string $layoutPath The directory containing the layout view files within this module. Defaults to "[[viewPath]]/layouts". - * @property array $modules The configuration of the currently installed modules (module ID => configuration). - * @property array $components The components (indexed by their IDs) registered within this module. - * @property array $import List of aliases to be imported. This property is write-only. - * @property array $aliases List of aliases to be defined. This property is write-only. + * @property array $aliases List of path aliases to be defined. The array keys are alias names (must start + * with '@') and the array values are the corresponding paths or aliases. See [[setAliases()]] for an example. + * This property is write-only. + * @property string $basePath The root directory of the module. + * @property array $components The components (indexed by their IDs). + * @property string $controllerPath The directory that contains the controller classes. + * @property string $layoutPath The root directory of layout files. Defaults to "[[viewPath]]/layouts". + * @property array $modules The modules (indexed by their IDs). + * @property string $uniqueId The unique ID of the module. This property is read-only. + * @property string $viewPath The root directory of view files. Defaults to "[[basePath]]/view". * * @author Qiang Xue * @since 2.0 @@ -304,6 +304,9 @@ abstract class Module extends Component * Defines path aliases. * This method calls [[Yii::setAlias()]] to register the path aliases. * This method is provided so that you can define path aliases when configuring a module. + * @property array list of path aliases to be defined. The array keys are alias names + * (must start with '@') and the array values are the corresponding paths or aliases. + * See [[setAliases()]] for an example. * @param array $aliases list of path aliases to be defined. The array keys are alias names * (must start with '@') and the array values are the corresponding paths or aliases. * For example, @@ -335,10 +338,9 @@ abstract class Module extends Component /** * Retrieves the named module. - * @param string $id module ID (case-sensitive) + * @param string $id module ID (case-sensitive). * @param boolean $load whether to load the module if it is not yet loaded. - * @return Module|null the module instance, null if the module - * does not exist. + * @return Module|null the module instance, null if the module does not exist. * @see hasModule() */ public function getModule($id, $load = true) diff --git a/framework/yii/base/Object.php b/framework/yii/base/Object.php index 50ad9e9..55754de 100644 --- a/framework/yii/base/Object.php +++ b/framework/yii/base/Object.php @@ -61,8 +61,7 @@ class Object implements Arrayable * Do not call this method directly as it is a PHP magic method that * will be implicitly called when executing `$value = $object->property;`. * @param string $name the property name - * @return mixed the property value, event handlers attached to the event, - * the named behavior, or the value of a behavior's property + * @return mixed the property value * @throws UnknownPropertyException if the property is not defined * @see __set */ @@ -71,6 +70,8 @@ class Object implements Arrayable $getter = 'get' . $name; if (method_exists($this, $getter)) { return $this->$getter(); + } elseif (method_exists($this, 'set' . $name)) { + throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name); } else { throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name); } @@ -142,8 +143,6 @@ class Object implements Arrayable /** * Calls the named method which is not a class method. - * If the name refers to a component property whose value is - * an anonymous function, the method will execute the function. * * Do not call this method directly as it is a PHP magic method that * will be implicitly called when an unknown method is being invoked. @@ -154,13 +153,6 @@ class Object implements Arrayable */ public function __call($name, $params) { - $getter = 'get' . $name; - if (method_exists($this, $getter)) { - $func = $this->$getter(); - if ($func instanceof \Closure) { - return call_user_func_array($func, $params); - } - } throw new UnknownMethodException('Unknown method: ' . get_class($this) . "::$name()"); } @@ -220,6 +212,19 @@ class Object implements Arrayable } /** + * Returns a value indicating whether a method is defined. + * + * The default implementation is a call to php function `method_exists()`. + * You may override this method when you implemented the php magic method `__call()`. + * @param string $name the property name + * @return boolean whether the property is defined + */ + public function hasMethod($name) + { + return method_exists($this, $name); + } + + /** * Converts the object into an array. * The default implementation will return all public property values as an array. * @return array the array representation of the object diff --git a/framework/yii/base/Request.php b/framework/yii/base/Request.php index 45556ab..0d660d6 100644 --- a/framework/yii/base/Request.php +++ b/framework/yii/base/Request.php @@ -8,6 +8,10 @@ namespace yii\base; /** + * + * @property boolean $isConsoleRequest The value indicating whether the current request is made via console. + * @property string $scriptFile Entry script file path (processed w/ realpath()). + * * @author Qiang Xue * @since 2.0 */ diff --git a/framework/yii/base/Theme.php b/framework/yii/base/Theme.php index ffd2732..658ada1 100644 --- a/framework/yii/base/Theme.php +++ b/framework/yii/base/Theme.php @@ -41,7 +41,6 @@ use yii\helpers\FileHelper; * that contains the entry script of the application. If your theme is designed to handle modules, * you may configure the [[pathMap]] property like described above. * - * * @author Qiang Xue * @since 2.0 */ diff --git a/framework/yii/base/View.php b/framework/yii/base/View.php index a5a3832..df0b2b2 100644 --- a/framework/yii/base/View.php +++ b/framework/yii/base/View.php @@ -21,6 +21,9 @@ use yii\widgets\FragmentCache; * * View provides a set of methods (e.g. [[render()]]) for rendering purpose. * + * @property \yii\web\AssetManager $assetManager The asset manager. Defaults to the "assetManager" application + * component. + * * @author Qiang Xue * @since 2.0 */ @@ -705,6 +708,13 @@ class View extends Component if (!empty($this->metaTags)) { $lines[] = implode("\n", $this->metaTags); } + + $request = Yii::$app->getRequest(); + if ($request instanceof \yii\web\Request && $request->enableCsrfValidation) { + $lines[] = Html::tag('meta', '', array('name' => 'csrf-var', 'content' => $request->csrfVar)); + $lines[] = Html::tag('meta', '', array('name' => 'csrf-token', 'content' => $request->getCsrfToken())); + } + if (!empty($this->linkTags)) { $lines[] = implode("\n", $this->linkTags); } diff --git a/framework/yii/base/Widget.php b/framework/yii/base/Widget.php index 0c948e9..943d007 100644 --- a/framework/yii/base/Widget.php +++ b/framework/yii/base/Widget.php @@ -12,6 +12,11 @@ use Yii; /** * Widget is the base class for widgets. * + * @property string $id ID of the widget. + * @property View $view The view object that can be used to render views or view files. + * @property string $viewPath The directory containing the view files for this widget. This property is + * read-only. + * * @author Qiang Xue * @since 2.0 */ diff --git a/framework/yii/bootstrap/Nav.php b/framework/yii/bootstrap/Nav.php index ee103d4..f24f729 100644 --- a/framework/yii/bootstrap/Nav.php +++ b/framework/yii/bootstrap/Nav.php @@ -56,7 +56,7 @@ class Nav extends Widget { /** * @var array list of items in the nav widget. Each array element represents a single - * menu item with the following structure: + * menu item which can be either a string or an array with the following structure: * * - label: string, required, the nav item label. * - url: optional, the item's URL. Defaults to "#". @@ -66,6 +66,8 @@ class Nav extends Widget * - active: boolean, optional, whether the item should be on active state or not. * - items: array|string, optional, the configuration array for creating a [[Dropdown]] widget, * or a string representing the dropdown menu. Note that Bootstrap does not support sub-dropdown menus. + * + * If a menu item is a string, it will be rendered directly without HTML encoding. */ public $items = array(); /** @@ -137,7 +139,7 @@ class Nav extends Widget /** * Renders a widget's item. - * @param mixed $item the item to render. + * @param string|array $item the item to render. * @return string the rendering result. * @throws InvalidConfigException */ diff --git a/framework/yii/caching/ApcCache.php b/framework/yii/caching/ApcCache.php index ff3acf5..6c2754a 100644 --- a/framework/yii/caching/ApcCache.php +++ b/framework/yii/caching/ApcCache.php @@ -21,6 +21,22 @@ namespace yii\caching; class ApcCache extends Cache { /** + * Checks whether a specified key exists in the cache. + * This can be faster than getting the value from the cache if the data is big. + * Note that this method does not check whether the dependency associated + * with the cached data, if there is any, has changed. So a call to [[get]] + * may return false while exists returns true. + * @param mixed $key a key identifying the cached value. This can be a simple string or + * a complex data structure consisting of factors representing the key. + * @return boolean true if a value exists in cache, false if the value is not in the cache or expired. + */ + public function exists($key) + { + $key = $this->buildKey($key); + return apc_exists($key); + } + + /** * Retrieves a value from cache with a specified key. * This is the implementation of the method declared in the parent class. * @param string $key a unique key identifying the cached value diff --git a/framework/yii/caching/Cache.php b/framework/yii/caching/Cache.php index a6ee455..56c6d96 100644 --- a/framework/yii/caching/Cache.php +++ b/framework/yii/caching/Cache.php @@ -47,7 +47,6 @@ use yii\helpers\StringHelper; * - [[deleteValue()]]: delete the value with the specified key from cache * - [[flushValues()]]: delete all values from cache * - * * @author Qiang Xue * @since 2.0 */ @@ -134,6 +133,25 @@ abstract class Cache extends Component implements \ArrayAccess } /** + * Checks whether a specified key exists in the cache. + * This can be faster than getting the value from the cache if the data is big. + * In case a cache does not support this feature natively, this method will try to simulate it + * but has no performance improvement over getting it. + * Note that this method does not check whether the dependency associated + * with the cached data, if there is any, has changed. So a call to [[get]] + * may return false while exists returns true. + * @param mixed $key a key identifying the cached value. This can be a simple string or + * a complex data structure consisting of factors representing the key. + * @return boolean true if a value exists in cache, false if the value is not in the cache or expired. + */ + public function exists($key) + { + $key = $this->buildKey($key); + $value = $this->getValue($key); + return $value !== false; + } + + /** * Retrieves multiple values from cache with the specified keys. * Some caches (such as memcache, apc) allow retrieving multiple cached values at the same time, * which may improve the performance. In case a cache does not support this feature natively, diff --git a/framework/yii/caching/ChainedDependency.php b/framework/yii/caching/ChainedDependency.php index 87debfe..d3b9953 100644 --- a/framework/yii/caching/ChainedDependency.php +++ b/framework/yii/caching/ChainedDependency.php @@ -14,8 +14,6 @@ namespace yii\caching; * considered changed; When [[dependOnAll]] is false, if one of the dependencies has NOT changed, * this dependency is considered NOT changed. * - * @property boolean $hasChanged Whether the dependency is changed or not. - * * @author Qiang Xue * @since 2.0 */ diff --git a/framework/yii/caching/DbCache.php b/framework/yii/caching/DbCache.php index 7571a42..b7b6692 100644 --- a/framework/yii/caching/DbCache.php +++ b/framework/yii/caching/DbCache.php @@ -89,6 +89,35 @@ class DbCache extends Cache } /** + * Checks whether a specified key exists in the cache. + * This can be faster than getting the value from the cache if the data is big. + * Note that this method does not check whether the dependency associated + * with the cached data, if there is any, has changed. So a call to [[get]] + * may return false while exists returns true. + * @param mixed $key a key identifying the cached value. This can be a simple string or + * a complex data structure consisting of factors representing the key. + * @return boolean true if a value exists in cache, false if the value is not in the cache or expired. + */ + public function exists($key) + { + $key = $this->buildKey($key); + + $query = new Query; + $query->select(array('COUNT(*)')) + ->from($this->cacheTable) + ->where('[[id]] = :id AND ([[expire]] = 0 OR [[expire]] >' . time() . ')', array(':id' => $key)); + if ($this->db->enableQueryCache) { + // temporarily disable and re-enable query caching + $this->db->enableQueryCache = false; + $result = $query->createCommand($this->db)->queryScalar(); + $this->db->enableQueryCache = true; + } else { + $result = $query->createCommand($this->db)->queryScalar(); + } + return $result > 0; + } + + /** * Retrieves a value from cache with a specified key. * This is the implementation of the method declared in the parent class. * @param string $key a unique key identifying the cached value diff --git a/framework/yii/caching/Dependency.php b/framework/yii/caching/Dependency.php index 1a8770b..91c0568 100644 --- a/framework/yii/caching/Dependency.php +++ b/framework/yii/caching/Dependency.php @@ -13,8 +13,6 @@ namespace yii\caching; * Child classes should override its [[generateDependencyData()]] for generating * the actual dependency data. * - * @property boolean $hasChanged Whether the dependency has changed. - * * @author Qiang Xue * @since 2.0 */ diff --git a/framework/yii/caching/FileCache.php b/framework/yii/caching/FileCache.php index a15751e..32cdf58 100644 --- a/framework/yii/caching/FileCache.php +++ b/framework/yii/caching/FileCache.php @@ -8,6 +8,7 @@ namespace yii\caching; use Yii; +use yii\helpers\FileHelper; /** * FileCache implements a cache component using files. @@ -45,6 +46,20 @@ class FileCache extends Cache * This number should be between 0 and 1000000. A value 0 means no GC will be performed at all. **/ public $gcProbability = 10; + /** + * @var integer the permission to be set for newly created cache files. + * This value will be used by PHP chmod() function. No umask will be applied. + * If not set, the permission will be determined by the current environment. + */ + public $fileMode; + /** + * @var integer the permission to be set for newly created directories. + * This value will be used by PHP chmod() function. No umask will be applied. + * Defaults to 0775, meaning the directory is read-writable by owner and group, + * but read-only for other users. + */ + public $dirMode = 0775; + /** * Initializes this component by ensuring the existence of the cache path. @@ -54,11 +69,27 @@ class FileCache extends Cache parent::init(); $this->cachePath = Yii::getAlias($this->cachePath); if (!is_dir($this->cachePath)) { - mkdir($this->cachePath, 0777, true); + FileHelper::createDirectory($this->cachePath, $this->dirMode, true); } } /** + * Checks whether a specified key exists in the cache. + * This can be faster than getting the value from the cache if the data is big. + * Note that this method does not check whether the dependency associated + * with the cached data, if there is any, has changed. So a call to [[get]] + * may return false while exists returns true. + * @param mixed $key a key identifying the cached value. This can be a simple string or + * a complex data structure consisting of factors representing the key. + * @return boolean true if a value exists in cache, false if the value is not in the cache or expired. + */ + public function exists($key) + { + $cacheFile = $this->getCacheFile($this->buildKey($key)); + return @filemtime($cacheFile) > time(); + } + + /** * Retrieves a value from cache with a specified key. * This is the implementation of the method declared in the parent class. * @param string $key a unique key identifying the cached value @@ -67,7 +98,7 @@ class FileCache extends Cache protected function getValue($key) { $cacheFile = $this->getCacheFile($key); - if (($time = @filemtime($cacheFile)) > time()) { + if (@filemtime($cacheFile) > time()) { return @file_get_contents($cacheFile); } else { return false; @@ -92,10 +123,12 @@ class FileCache extends Cache $cacheFile = $this->getCacheFile($key); if ($this->directoryLevel > 0) { - @mkdir(dirname($cacheFile), 0777, true); + @FileHelper::createDirectory(dirname($cacheFile), $this->dirMode, true); } if (@file_put_contents($cacheFile, $value, LOCK_EX) !== false) { - @chmod($cacheFile, 0777); + if ($this->fileMode !== null) { + @chmod($cacheFile, $this->fileMode); + } return @touch($cacheFile, $expire); } else { return false; diff --git a/framework/yii/caching/MemCache.php b/framework/yii/caching/MemCache.php index aaea696..53202f0 100644 --- a/framework/yii/caching/MemCache.php +++ b/framework/yii/caching/MemCache.php @@ -52,8 +52,10 @@ use yii\base\InvalidConfigException; * In the above, two memcache servers are used: server1 and server2. You can configure more properties of * each server, such as `persistent`, `weight`, `timeout`. Please see [[MemCacheServer]] for available options. * - * @property \Memcache|\Memcached $memCache The memcache instance (or memcached if [[useMemcached]] is true) used by this component. - * @property MemCacheServer[] $servers List of memcache server configurations. + * @property \Memcache|\Memcached $memcache The memcache (or memcached) object used by this cache component. + * This property is read-only. + * @property MemCacheServer[] $servers List of memcache server configurations. Note that the type of this + * property differs in getter and setter. See [[getServers()]] and [[setServers()]] for details. * * @author Qiang Xue * @since 2.0 diff --git a/framework/yii/caching/RedisCache.php b/framework/yii/caching/RedisCache.php index 0c8bf15..5c778fc 100644 --- a/framework/yii/caching/RedisCache.php +++ b/framework/yii/caching/RedisCache.php @@ -7,7 +7,7 @@ namespace yii\caching; -use yii\db\redis\Connection; +use yii\redis\Connection; /** * RedisCache implements a cache application component based on [redis](http://redis.io/). @@ -39,6 +39,8 @@ use yii\db\redis\Connection; * ) * ~~~ * + * @property Connection $connection The redis connection object. This property is read-only. + * * @author Carsten Brandt * @since 2.0 */ @@ -69,7 +71,7 @@ class RedisCache extends Cache */ public $dataTimeout = null; /** - * @var \yii\db\redis\Connection the redis connection + * @var Connection the redis connection */ private $_connection; @@ -86,9 +88,7 @@ class RedisCache extends Cache /** * Returns the redis connection object. * Establishes a connection to the redis server if it does not already exists. - * - * TODO throw exception on error - * @return \yii\db\redis\Connection + * @return Connection the redis connection object. */ public function getConnection() { @@ -104,6 +104,21 @@ class RedisCache extends Cache } /** + * Checks whether a specified key exists in the cache. + * This can be faster than getting the value from the cache if the data is big. + * Note that this method does not check whether the dependency associated + * with the cached data, if there is any, has changed. So a call to [[get]] + * may return false while exists returns true. + * @param mixed $key a key identifying the cached value. This can be a simple string or + * a complex data structure consisting of factors representing the key. + * @return boolean true if a value exists in cache, false if the value is not in the cache or expired. + */ + public function exists($key) + { + return (bool) $this->_connection->executeCommand('EXISTS', array($this->buildKey($key))); + } + + /** * Retrieves a value from cache with a specified key. * This is the implementation of the method declared in the parent class. * @param string $key a unique key identifying the cached value diff --git a/framework/yii/caching/WinCache.php b/framework/yii/caching/WinCache.php index eed580d..3679884 100644 --- a/framework/yii/caching/WinCache.php +++ b/framework/yii/caching/WinCache.php @@ -8,7 +8,7 @@ namespace yii\caching; /** - * WinCache provides XCache caching in terms of an application component. + * WinCache provides Windows Cache caching in terms of an application component. * * To use this application component, the [WinCache PHP extension](http://www.iis.net/expand/wincacheforphp) * must be loaded. Also note that "wincache.ucenabled" should be set to "On" in your php.ini file. @@ -21,6 +21,22 @@ namespace yii\caching; class WinCache extends Cache { /** + * Checks whether a specified key exists in the cache. + * This can be faster than getting the value from the cache if the data is big. + * Note that this method does not check whether the dependency associated + * with the cached data, if there is any, has changed. So a call to [[get]] + * may return false while exists returns true. + * @param mixed $key a key identifying the cached value. This can be a simple string or + * a complex data structure consisting of factors representing the key. + * @return boolean true if a value exists in cache, false if the value is not in the cache or expired. + */ + public function exists($key) + { + $key = $this->buildKey($key); + return wincache_ucache_exists($key); + } + + /** * Retrieves a value from cache with a specified key. * This is the implementation of the method declared in the parent class. * @param string $key a unique key identifying the cached value diff --git a/framework/yii/caching/XCache.php b/framework/yii/caching/XCache.php index 1f12f23..4221a39 100644 --- a/framework/yii/caching/XCache.php +++ b/framework/yii/caching/XCache.php @@ -22,6 +22,22 @@ namespace yii\caching; class XCache extends Cache { /** + * Checks whether a specified key exists in the cache. + * This can be faster than getting the value from the cache if the data is big. + * Note that this method does not check whether the dependency associated + * with the cached data, if there is any, has changed. So a call to [[get]] + * may return false while exists returns true. + * @param mixed $key a key identifying the cached value. This can be a simple string or + * a complex data structure consisting of factors representing the key. + * @return boolean true if a value exists in cache, false if the value is not in the cache or expired. + */ + public function exists($key) + { + $key = $this->buildKey($key); + return xcache_isset($key); + } + + /** * Retrieves a value from cache with a specified key. * This is the implementation of the method declared in the parent class. * @param string $key a unique key identifying the cached value diff --git a/framework/yii/captcha/CaptchaAction.php b/framework/yii/captcha/CaptchaAction.php index 771cc02..e1761a1 100644 --- a/framework/yii/captcha/CaptchaAction.php +++ b/framework/yii/captcha/CaptchaAction.php @@ -29,6 +29,8 @@ use yii\base\InvalidConfigException; * to be validated by the 'captcha' validator. * 3. In the controller view, insert a [[Captcha]] widget in the form. * + * @property string $verifyCode The verification code. This property is read-only. + * * @author Qiang Xue * @since 2.0 */ diff --git a/framework/yii/captcha/CaptchaValidator.php b/framework/yii/captcha/CaptchaValidator.php index e710573..97bfd1b 100644 --- a/framework/yii/captcha/CaptchaValidator.php +++ b/framework/yii/captcha/CaptchaValidator.php @@ -18,6 +18,8 @@ use yii\validators\Validator; * * CaptchaValidator should be used together with [[CaptchaAction]]. * + * @property \yii\captcha\CaptchaAction $captchaAction The action object. This property is read-only. + * * @author Qiang Xue * @since 2.0 */ diff --git a/framework/yii/console/Application.php b/framework/yii/console/Application.php index a69abe0..bbdd4e1 100644 --- a/framework/yii/console/Application.php +++ b/framework/yii/console/Application.php @@ -45,6 +45,8 @@ use yii\base\InvalidRouteException; * yii help * ~~~ * + * @property Response $response The response component. This property is read-only. + * * @author Qiang Xue * @since 2.0 */ diff --git a/framework/yii/console/Request.php b/framework/yii/console/Request.php index fe1e23b..dca0240 100644 --- a/framework/yii/console/Request.php +++ b/framework/yii/console/Request.php @@ -8,6 +8,9 @@ namespace yii\console; /** + * + * @property array $params The command line arguments. It does not include the entry script name. + * * @author Qiang Xue * @since 2.0 */ diff --git a/framework/yii/console/controllers/AssetController.php b/framework/yii/console/controllers/AssetController.php index c4d4b5a..1e95dd8 100644 --- a/framework/yii/console/controllers/AssetController.php +++ b/framework/yii/console/controllers/AssetController.php @@ -28,7 +28,8 @@ use yii\console\Controller; * Note: by default this command relies on an external tools to perform actual files compression, * check [[jsCompressor]] and [[cssCompressor]] for more details. * - * @property array|\yii\web\AssetManager $assetManager asset manager, which will be used for assets processing. + * @property \yii\web\AssetManager $assetManager Asset manager instance. Note that the type of this property + * differs in getter and setter. See [[getAssetManager()]] and [[setAssetManager()]] for details. * * @author Qiang Xue * @since 2.0 diff --git a/framework/yii/console/controllers/HelpController.php b/framework/yii/console/controllers/HelpController.php index bf97e90..f0e72cd 100644 --- a/framework/yii/console/controllers/HelpController.php +++ b/framework/yii/console/controllers/HelpController.php @@ -31,6 +31,8 @@ use yii\helpers\Inflector; * In the above, if the command name is not provided, all * available commands will be displayed. * + * @property array $commands All available command names. This property is read-only. + * * @author Qiang Xue * @since 2.0 */ diff --git a/framework/yii/data/ActiveDataProvider.php b/framework/yii/data/ActiveDataProvider.php index 6dfc9ed..aaf71b2 100644 --- a/framework/yii/data/ActiveDataProvider.php +++ b/framework/yii/data/ActiveDataProvider.php @@ -9,6 +9,7 @@ namespace yii\data; use Yii; use yii\base\InvalidConfigException; +use yii\base\Model; use yii\db\Query; use yii\db\ActiveQuery; use yii\db\Connection; @@ -47,6 +48,12 @@ use yii\db\Connection; * $posts = $provider->getModels(); * ~~~ * + * @property integer $count The number of data models in the current page. This property is read-only. + * @property array $keys The list of key values corresponding to [[models]]. Each data model in [[models]] is + * uniquely identified by the corresponding key value in this array. This property is read-only. + * @property array $models The list of data models in the current page. This property is read-only. + * @property integer $totalCount Total number of possible data models. + * * @author Qiang Xue * @since 2.0 */ @@ -214,4 +221,25 @@ class ActiveDataProvider extends DataProvider $this->_totalCount = null; $this->_keys = null; } + + /** + * @inheritdoc + */ + public function setSort($value) + { + parent::setSort($value); + if (($sort = $this->getSort()) !== false && empty($sort->attributes) && + $this->query instanceof ActiveQuery) { + + /** @var Model $model */ + $model = new $this->query->modelClass; + foreach($model->attributes() as $attribute) { + $sort->attributes[$attribute] = array( + 'asc' => array($attribute => Sort::ASC), + 'desc' => array($attribute => Sort::DESC), + 'label' => $model->getAttributeLabel($attribute), + ); + } + } + } } diff --git a/framework/yii/data/ArrayDataProvider.php b/framework/yii/data/ArrayDataProvider.php index e79a63e..d6eaca7 100644 --- a/framework/yii/data/ArrayDataProvider.php +++ b/framework/yii/data/ArrayDataProvider.php @@ -47,6 +47,11 @@ use yii\helpers\ArrayHelper; * Note: if you want to use the sorting feature, you must configure the [[sort]] property * so that the provider knows which columns can be sorted. * + * @property array $keys The list of key values corresponding to [[models]]. Each data model in [[models]] is + * uniquely identified by the corresponding key value in this array. + * @property array $models The list of data models in the current page. + * @property integer $totalCount Total number of possible data models. + * * @author Qiang Xue * @since 2.0 */ diff --git a/framework/yii/data/DataProvider.php b/framework/yii/data/DataProvider.php index 122e60a..84491d6 100644 --- a/framework/yii/data/DataProvider.php +++ b/framework/yii/data/DataProvider.php @@ -16,6 +16,13 @@ use yii\base\InvalidParamException; * * It implements the [[getPagination()]] and [[getSort()]] methods as specified by the [[IDataProvider]] interface. * + * @property integer $count The number of data models in the current page. This property is read-only. + * @property Pagination|boolean $pagination The pagination object. If this is false, it means the pagination + * is disabled. Note that the type of this property differs in getter and setter. See [[getPagination()]] and + * [[setPagination()]] for details. + * @property Sort|boolean $sort The sorting object. If this is false, it means the sorting is disabled. Note + * that the type of this property differs in getter and setter. See [[getSort()]] and [[setSort()]] for details. + * * @author Qiang Xue * @since 2.0 */ @@ -32,7 +39,7 @@ abstract class DataProvider extends Component implements IDataProvider private $_pagination; /** - * @return Pagination the pagination object. If this is false, it means the pagination is disabled. + * @return Pagination|boolean the pagination object. If this is false, it means the pagination is disabled. */ public function getPagination() { @@ -75,7 +82,7 @@ abstract class DataProvider extends Component implements IDataProvider } /** - * @return Sort the sorting object. If this is false, it means the sorting is disabled. + * @return Sort|boolean the sorting object. If this is false, it means the sorting is disabled. */ public function getSort() { diff --git a/framework/yii/data/Pagination.php b/framework/yii/data/Pagination.php index 8d4c067..04af828 100644 --- a/framework/yii/data/Pagination.php +++ b/framework/yii/data/Pagination.php @@ -53,12 +53,13 @@ use yii\base\Object; * )); * ~~~ * - * @property integer $pageCount Number of pages. - * @property integer $page The zero-based index of the current page. - * @property integer $offset The offset of the data. This may be used to set the - * OFFSET value for a SQL statement for fetching the current page of data. - * @property integer $limit The limit of the data. This may be used to set the - * LIMIT value for a SQL statement for fetching the current page of data. + * @property integer $limit The limit of the data. This may be used to set the LIMIT value for a SQL statement + * for fetching the current page of data. Note that if the page size is infinite, a value -1 will be returned. + * This property is read-only. + * @property integer $offset The offset of the data. This may be used to set the OFFSET value for a SQL + * statement for fetching the current page of data. This property is read-only. + * @property integer $page The zero-based current page number. + * @property integer $pageCount Number of pages. This property is read-only. * * @author Qiang Xue * @since 2.0 @@ -97,10 +98,10 @@ class Pagination extends Object */ public $validatePage = true; /** - * @var integer number of items on each page. Defaults to 10. + * @var integer number of items on each page. Defaults to 20. * If it is less than 1, it means the page size is infinite, and thus a single page contains all items. */ - public $pageSize = 10; + public $pageSize = 20; /** * @var integer total number of items. */ diff --git a/framework/yii/data/Sort.php b/framework/yii/data/Sort.php index 73e6f1c..78fe2e0 100644 --- a/framework/yii/data/Sort.php +++ b/framework/yii/data/Sort.php @@ -65,6 +65,11 @@ use yii\helpers\Inflector; * sorted by the orders specified by the Sort object. In the view, we show two hyperlinks * that can lead to pages with the data sorted by the corresponding attributes. * + * @property array $attributeOrders Sort directions indexed by attribute names. Sort direction can be either + * [[Sort::ASC]] for ascending order or [[Sort::DESC]] for descending order. This property is read-only. + * @property array $orders The columns (keys) and their corresponding sort directions (values). This can be + * passed to [[\yii\db\Query::orderBy()]] to construct a DB query. This property is read-only. + * * @author Qiang Xue * @since 2.0 */ @@ -125,9 +130,10 @@ class Sort extends Object * if it is not currently sorted (the default value is ascending order). * - The "label" element specifies what label should be used when calling [[link()]] to create * a sort link. If not set, [[Inflector::camel2words()]] will be called to get a label. + * Note that it will not be HTML-encoded. * * Note that if the Sort object is already created, you can only use the full format - * to configure every attribute. Each attribute must include these elements: asc, desc and label. + * to configure every attribute. Each attribute must include these elements: asc and desc. */ public $attributes = array(); /** @@ -195,13 +201,11 @@ class Sort extends Object $attributes[$attribute] = array( 'asc' => array($attribute => self::ASC), 'desc' => array($attribute => self::DESC), - 'label' => Inflector::camel2words($attribute), ); - } elseif (!isset($attribute['asc'], $attribute['desc'], $attribute['label'])) { + } elseif (!isset($attribute['asc'], $attribute['desc'])) { $attributes[$name] = array_merge(array( 'asc' => array($name => self::ASC), 'desc' => array($name => self::DESC), - 'label' => Inflector::camel2words($name), ), $attribute); } else { $attributes[$name] = $attribute; @@ -287,7 +291,11 @@ class Sort extends Object * Based on the sort direction, the CSS class of the generated hyperlink will be appended * with "asc" or "desc". * @param string $attribute the attribute name by which the data should be sorted by. - * @param array $options additional HTML attributes for the hyperlink tag + * @param array $options additional HTML attributes for the hyperlink tag. + * There is one special attribute `label` which will be used as the label of the hyperlink. + * If this is not set, the label defined in [[attributes]] will be used. + * If no label is defined, [[yii\helpers\Inflector::camel2words()]] will be called to get a label. + * Note that it will not be HTML-encoded. * @return string the generated hyperlink * @throws InvalidConfigException if the attribute is unknown */ @@ -304,7 +312,18 @@ class Sort extends Object $url = $this->createUrl($attribute); $options['data-sort'] = $this->createSortVar($attribute); - return Html::a($this->attributes[$attribute]['label'], $url, $options); + + if (isset($options['label'])) { + $label = $options['label']; + unset($options['label']); + } else { + if (isset($this->attributes[$attribute]['label'])) { + $label = $this->attributes[$attribute]['label']; + } else { + $label = Inflector::camel2words($attribute); + } + } + return Html::a($label, $url, $options); } /** diff --git a/framework/yii/db/ActiveQuery.php b/framework/yii/db/ActiveQuery.php index 4d08659..12997ee 100644 --- a/framework/yii/db/ActiveQuery.php +++ b/framework/yii/db/ActiveQuery.php @@ -156,6 +156,8 @@ class ActiveQuery extends Query if ($db === null) { $db = $modelClass::getDb(); } + + $params = $this->params; if ($this->sql === null) { if ($this->from === null) { $tableName = $modelClass::tableName(); @@ -164,11 +166,9 @@ class ActiveQuery extends Query } $this->from = array($tableName); } - /** @var $qb QueryBuilder */ - $qb = $db->getQueryBuilder(); - $this->sql = $qb->build($this); + list ($this->sql, $params) = $db->getQueryBuilder()->build($this); } - return $db->createCommand($this->sql, $this->params); + return $db->createCommand($this->sql, $params); } /** diff --git a/framework/yii/db/ActiveRecord.php b/framework/yii/db/ActiveRecord.php index 5aa9807..e1c4b4f 100644 --- a/framework/yii/db/ActiveRecord.php +++ b/framework/yii/db/ActiveRecord.php @@ -22,13 +22,16 @@ use yii\helpers\Inflector; * * @include @yii/db/ActiveRecord.md * - * @property Connection $db the database connection used by this AR class. - * @property TableSchema $tableSchema the schema information of the DB table associated with this AR class. - * @property array $oldAttributes the old attribute values (name-value pairs). - * @property array $dirtyAttributes the changed attribute values (name-value pairs). - * @property boolean $isNewRecord whether the record is new and should be inserted when calling [[save()]]. - * @property mixed $primaryKey the primary key value. - * @property mixed $oldPrimaryKey the old primary key value. + * @property array $dirtyAttributes The changed attribute values (name-value pairs). This property is + * read-only. + * @property boolean $isNewRecord Whether the record is new and should be inserted when calling [[save()]]. + * @property array $oldAttributes The old attribute values (name-value pairs). + * @property mixed $oldPrimaryKey The old primary key value. An array (column name => column value) is + * returned if the primary key is composite or `$asArray` is true. A string is returned otherwise (null will be + * returned if the key value is null). This property is read-only. + * @property mixed $primaryKey The primary key value. An array (column name => column value) is returned if + * the primary key is composite or `$asArray` is true. A string is returned otherwise (null will be returned if + * the key value is null). This property is read-only. * * @author Qiang Xue * @since 2.0 @@ -746,21 +749,21 @@ class ActiveRecord extends Model return false; } $db = static::getDb(); - $transaction = $this->isTransactional(self::OP_INSERT) && $db->getTransaction() === null ? $db->beginTransaction() : null; - try { - $result = $this->insertInternal($attributes); - if ($transaction !== null) { + if ($this->isTransactional(self::OP_INSERT) && $db->getTransaction() === null) { + $transaction = $db->beginTransaction(); + try { + $result = $this->insertInternal($attributes); if ($result === false) { $transaction->rollback(); } else { $transaction->commit(); } - } - } catch (\Exception $e) { - if ($transaction !== null) { + } catch (\Exception $e) { $transaction->rollback(); + throw $e; } - throw $e; + } else { + $result = $this->insertInternal($attributes); } return $result; } @@ -856,21 +859,21 @@ class ActiveRecord extends Model return false; } $db = static::getDb(); - $transaction = $this->isTransactional(self::OP_UPDATE) && $db->getTransaction() === null ? $db->beginTransaction() : null; - try { - $result = $this->updateInternal($attributes); - if ($transaction !== null) { + if ($this->isTransactional(self::OP_UPDATE) && $db->getTransaction() === null) { + $transaction = $db->beginTransaction(); + try { + $result = $this->updateInternal($attributes); if ($result === false) { $transaction->rollback(); } else { $transaction->commit(); } - } - } catch (\Exception $e) { - if ($transaction !== null) { + } catch (\Exception $e) { $transaction->rollback(); + throw $e; } - throw $e; + } else { + $result = $this->updateInternal($attributes); } return $result; } @@ -886,6 +889,7 @@ class ActiveRecord extends Model } $values = $this->getDirtyAttributes($attributes); if (empty($values)) { + $this->afterSave(false); return 0; } $condition = $this->getOldPrimaryKey(true); @@ -1007,6 +1011,16 @@ class ActiveRecord extends Model } /** + * Sets the value indicating whether the record is new. + * @param boolean $value whether the record is new and should be inserted when calling [[save()]]. + * @see getIsNewRecord + */ + public function setIsNewRecord($value) + { + $this->_oldAttributes = $value ? null : $this->_attributes; + } + + /** * Initializes the object. * This method is called at the end of the constructor. * The default implementation will trigger an [[EVENT_INIT]] event. @@ -1031,16 +1045,6 @@ class ActiveRecord extends Model } /** - * Sets the value indicating whether the record is new. - * @param boolean $value whether the record is new and should be inserted when calling [[save()]]. - * @see getIsNewRecord - */ - public function setIsNewRecord($value) - { - $this->_oldAttributes = $value ? null : $this->_attributes; - } - - /** * This method is called at the beginning of inserting or updating a record. * The default implementation will trigger an [[EVENT_BEFORE_INSERT]] event when `$insert` is true, * or an [[EVENT_BEFORE_UPDATE]] event if `$insert` is false. diff --git a/framework/yii/db/ActiveRelation.php b/framework/yii/db/ActiveRelation.php index 8f3c9ae..fa1def8 100644 --- a/framework/yii/db/ActiveRelation.php +++ b/framework/yii/db/ActiveRelation.php @@ -50,6 +50,16 @@ class ActiveRelation extends ActiveQuery */ public $via; + /** + * Clones internal objects. + */ + public function __clone() + { + if (is_object($this->via)) { + // make a clone of "via" object so that the same query object can be reused multiple times + $this->via = clone $this->via; + } + } /** * Specifies the relation associated with the pivot table. @@ -297,7 +307,7 @@ class ActiveRelation extends ActiveQuery /** @var $primaryModel ActiveRecord */ $primaryModel = reset($primaryModels); $db = $primaryModel->getDb(); - $sql = $db->getQueryBuilder()->build($this); - return $db->createCommand($sql, $this->params)->queryAll(); + list ($sql, $params) = $db->getQueryBuilder()->build($this); + return $db->createCommand($sql, $params)->queryAll(); } } diff --git a/framework/yii/db/Command.php b/framework/yii/db/Command.php index feb6c5e..bfb8a26 100644 --- a/framework/yii/db/Command.php +++ b/framework/yii/db/Command.php @@ -44,7 +44,9 @@ use yii\caching\Cache; * * To build SELECT SQL statements, please use [[QueryBuilder]] instead. * - * @property string $sql the SQL statement to be executed + * @property string $rawSql The raw SQL with parameter values inserted into the corresponding placeholders in + * [[sql]]. This property is read-only. + * @property string $sql The SQL statement to be executed. * * @author Qiang Xue * @since 2.0 @@ -60,7 +62,7 @@ class Command extends \yii\base\Component */ public $pdoStatement; /** - * @var mixed the default fetch mode for this command. + * @var integer the default fetch mode for this command. * @see http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php */ public $fetchMode = \PDO::FETCH_ASSOC; @@ -102,7 +104,7 @@ class Command extends \yii\base\Component * Returns the raw SQL by inserting parameter values into the corresponding placeholders in [[sql]]. * Note that the return value of this method should mainly be used for logging purpose. * It is likely that this method returns an invalid SQL due to improper replacement of parameter placeholders. - * @return string the raw SQL + * @return string the raw SQL with parameter values inserted into the corresponding placeholders in [[sql]]. */ public function getRawSql() { @@ -244,14 +246,14 @@ class Command extends \yii\base\Component } /** - * Determines the PDO type for the give PHP data value. + * Determines the PDO type for the given PHP data value. * @param mixed $data the data whose PDO type is to be determined * @return integer the PDO type * @see http://www.php.net/manual/en/pdo.constants.php */ private function getPdoType($data) { - static $typeMap = array( + static $typeMap = array( // php type => PDO type 'boolean' => \PDO::PARAM_BOOL, 'integer' => \PDO::PARAM_INT, 'string' => \PDO::PARAM_STR, @@ -312,7 +314,7 @@ class Command extends \yii\base\Component /** * Executes the SQL statement and returns ALL rows at once. - * @param mixed $fetchMode the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php) + * @param integer $fetchMode the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php) * for valid fetch modes. If this parameter is null, the value set in [[fetchMode]] will be used. * @return array all rows of the query result. Each array element is an array representing a row of data. * An empty array is returned if the query results in nothing. @@ -326,7 +328,7 @@ class Command extends \yii\base\Component /** * Executes the SQL statement and returns the first row of the result. * This method is best used when only the first row of result is needed for a query. - * @param mixed $fetchMode the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php) + * @param integer $fetchMode the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php) * for valid fetch modes. If this parameter is null, the value set in [[fetchMode]] will be used. * @return array|boolean the first row (in terms of an array) of the query result. False is returned if the query * results in nothing. @@ -369,7 +371,7 @@ class Command extends \yii\base\Component /** * Performs the actual DB query of a SQL statement. * @param string $method method of PDOStatement to be called - * @param mixed $fetchMode the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php) + * @param integer $fetchMode the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php) * for valid fetch modes. If this parameter is null, the value set in [[fetchMode]] will be used. * @return mixed the method execution result * @throws Exception if the query causes any problem @@ -470,7 +472,7 @@ class Command extends \yii\base\Component * ))->execute(); * ~~~ * - * Not that the values in each row must match the corresponding column names. + * Note that the values in each row must match the corresponding column names. * * @param string $table the table that new rows will be inserted into. * @param array $columns the column names @@ -499,7 +501,7 @@ class Command extends \yii\base\Component * * @param string $table the table to be updated. * @param array $columns the column data (name => value) to be updated. - * @param mixed $condition the condition that will be put in the WHERE part. Please + * @param string|array $condition the condition that will be put in the WHERE part. Please * refer to [[Query::where()]] on how to specify condition. * @param array $params the parameters to be bound to the command * @return Command the command object itself @@ -523,7 +525,7 @@ class Command extends \yii\base\Component * Note that the created command is not executed until [[execute()]] is called. * * @param string $table the table where the data will be deleted from. - * @param mixed $condition the condition that will be put in the WHERE part. Please + * @param string|array $condition the condition that will be put in the WHERE part. Please * refer to [[Query::where()]] on how to specify condition. * @param array $params the parameters to be bound to the command * @return Command the command object itself diff --git a/framework/yii/db/Connection.php b/framework/yii/db/Connection.php index 26c4537..69bf6a5 100644 --- a/framework/yii/db/Connection.php +++ b/framework/yii/db/Connection.php @@ -89,13 +89,16 @@ use yii\caching\Cache; * ) * ~~~ * + * @property string $driverName Name of the DB driver. This property is read-only. * @property boolean $isActive Whether the DB connection is established. This property is read-only. - * @property Transaction $transaction The currently active transaction. Null if no active transaction. - * @property Schema $schema The database schema information 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 array $querySummary The statistical results of SQL queries. + * @property string $lastInsertID The row ID of the last row inserted, or the last value retrieved from the + * sequence object. This property is read-only. + * @property QueryBuilder $queryBuilder The query builder for the current DB connection. This property is + * read-only. + * @property Schema $schema The schema information for the database opened by this connection. This property + * is read-only. + * @property Transaction $transaction The currently active transaction. Null if no active transaction. This + * property is read-only. * * @author Qiang Xue * @since 2.0 @@ -198,7 +201,7 @@ class Connection extends Component public $queryCache = 'cache'; /** * @var string the charset used for database connection. The property is only used - * for MySQL and PostgreSQL databases. Defaults to null, meaning using default charset + * for MySQL, PostgreSQL and CUBRID databases. Defaults to null, meaning using default charset * as specified by the database. * * Note that if you're using GBK or BIG5 then it's highly recommended to @@ -241,6 +244,7 @@ class Connection extends Component 'oci' => 'yii\db\oci\Schema', // Oracle driver 'mssql' => 'yii\db\mssql\Schema', // older MSSQL driver on MS Windows hosts 'dblib' => 'yii\db\mssql\Schema', // dblib drivers on GNU/Linux (and maybe other OSes) hosts + 'cubrid' => 'yii\db\cubrid\Schema', // CUBRID ); /** * @var Transaction the currently active transaction @@ -358,7 +362,7 @@ class Connection extends Component if ($this->emulatePrepare !== null && constant('PDO::ATTR_EMULATE_PREPARES')) { $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->emulatePrepare); } - if ($this->charset !== null && in_array($this->getDriverName(), array('pgsql', 'mysql', 'mysqli'))) { + if ($this->charset !== null && in_array($this->getDriverName(), array('pgsql', 'mysql', 'mysqli', 'cubrid'))) { $this->pdo->exec('SET NAMES ' . $this->pdo->quote($this->charset)); } $this->trigger(self::EVENT_AFTER_OPEN); diff --git a/framework/yii/db/DataReader.php b/framework/yii/db/DataReader.php index ce776c0..f2990c1 100644 --- a/framework/yii/db/DataReader.php +++ b/framework/yii/db/DataReader.php @@ -39,10 +39,10 @@ use yii\base\InvalidCallException; * [[fetchMode]]. See the [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php) * for more details about possible fetch mode. * - * @property boolean $isClosed whether the reader is closed or not. - * @property integer $rowCount number of rows contained in the result. - * @property integer $columnCount the number of columns in the result set. - * @property mixed $fetchMode fetch mode used when retrieving the data. + * @property integer $columnCount The number of columns in the result set. This property is read-only. + * @property integer $fetchMode Fetch mode. This property is write-only. + * @property boolean $isClosed Whether the reader is closed or not. This property is read-only. + * @property integer $rowCount Number of rows contained in the result. This property is read-only. * * @author Qiang Xue * @since 2.0 @@ -73,7 +73,7 @@ class DataReader extends \yii\base\Object implements \Iterator, \Countable * Binds a column to a PHP variable. * When rows of data are being fetched, the corresponding column value * will be set in the variable. Note, the fetch mode must include PDO::FETCH_BOUND. - * @param mixed $column Number of the column (1-indexed) or name of the column + * @param integer|string $column Number of the column (1-indexed) or name of the column * in the result set. If using the column name, be aware that the name * should match the case of the column, as returned by the driver. * @param mixed $value Name of the PHP variable to which the column will be bound. @@ -91,7 +91,7 @@ class DataReader extends \yii\base\Object implements \Iterator, \Countable /** * Set the default fetch mode for this statement - * @param mixed $mode fetch mode + * @param integer $mode fetch mode * @see http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php */ public function setFetchMode($mode) @@ -112,7 +112,7 @@ class DataReader extends \yii\base\Object implements \Iterator, \Countable /** * Returns a single column from the next row of a result set. * @param integer $columnIndex zero-based column index - * @return mixed the column of the current row, false if no more row available + * @return mixed the column of the current row, false if no more rows available */ public function readColumn($columnIndex) { diff --git a/framework/yii/db/Exception.php b/framework/yii/db/Exception.php index 9339211..25ae39f 100644 --- a/framework/yii/db/Exception.php +++ b/framework/yii/db/Exception.php @@ -16,19 +16,19 @@ namespace yii\db; class Exception extends \yii\base\Exception { /** - * @var mixed the error info provided by a PDO exception. This is the same as returned + * @var array the error info provided by a PDO exception. This is the same as returned * by [PDO::errorInfo](http://www.php.net/manual/en/pdo.errorinfo.php). */ - public $errorInfo; + public $errorInfo = array(); /** * Constructor. * @param string $message PDO error message - * @param mixed $errorInfo PDO error info + * @param array $errorInfo PDO error info * @param integer $code PDO error code * @param \Exception $previous The previous exception used for the exception chaining. */ - public function __construct($message, $errorInfo = null, $code = 0, \Exception $previous = null) + public function __construct($message, $errorInfo = array(), $code = 0, \Exception $previous = null) { $this->errorInfo = $errorInfo; parent::__construct($message, $code, $previous); diff --git a/framework/yii/db/Migration.php b/framework/yii/db/Migration.php index 7c6815b..7368788 100644 --- a/framework/yii/db/Migration.php +++ b/framework/yii/db/Migration.php @@ -162,7 +162,7 @@ class Migration extends \yii\base\Component * The method will properly escape the column names and bind the values to be updated. * @param string $table the table to be updated. * @param array $columns the column data (name => value) to be updated. - * @param mixed $condition the conditions that will be put in the WHERE part. Please + * @param array|string $condition the conditions that will be put in the WHERE part. Please * refer to [[Query::where()]] on how to specify conditions. * @param array $params the parameters to be bound to the query. */ @@ -177,7 +177,7 @@ class Migration extends \yii\base\Component /** * Creates and executes a DELETE SQL statement. * @param string $table the table where the data will be deleted from. - * @param mixed $condition the conditions that will be put in the WHERE part. Please + * @param array|string $condition the conditions that will be put in the WHERE part. Please * refer to [[Query::where()]] on how to specify conditions. * @param array $params the parameters to be bound to the query. */ diff --git a/framework/yii/db/Query.php b/framework/yii/db/Query.php index 19ea028..d1e7864 100644 --- a/framework/yii/db/Query.php +++ b/framework/yii/db/Query.php @@ -149,8 +149,8 @@ class Query extends Component if ($db === null) { $db = Yii::$app->getDb(); } - $sql = $db->getQueryBuilder()->build($this); - return $db->createCommand($sql, $this->params); + list ($sql, $params) = $db->getQueryBuilder()->build($this); + return $db->createCommand($sql, $params); } /** diff --git a/framework/yii/db/QueryBuilder.php b/framework/yii/db/QueryBuilder.php index 5317e67..3cc7971 100644 --- a/framework/yii/db/QueryBuilder.php +++ b/framework/yii/db/QueryBuilder.php @@ -55,22 +55,24 @@ class QueryBuilder extends \yii\base\Object /** * Generates a SELECT SQL statement from a [[Query]] object. * @param Query $query the [[Query]] object from which the SQL statement will be generated - * @return string the generated SQL statement + * @return array the generated SQL statement (the first array element) and the corresponding + * parameters to be bound to the SQL statement (the second array element). */ public function build($query) { + $params = $query->params; $clauses = array( $this->buildSelect($query->select, $query->distinct, $query->selectOption), $this->buildFrom($query->from), - $this->buildJoin($query->join, $query->params), - $this->buildWhere($query->where, $query->params), + $this->buildJoin($query->join, $params), + $this->buildWhere($query->where, $params), $this->buildGroupBy($query->groupBy), - $this->buildHaving($query->having, $query->params), - $this->buildUnion($query->union, $query->params), + $this->buildHaving($query->having, $params), + $this->buildUnion($query->union, $params), $this->buildOrderBy($query->orderBy), $this->buildLimit($query->limit, $query->offset), ); - return implode($this->separator, array_filter($clauses)); + return array(implode($this->separator, array_filter($clauses)), $params); } /** @@ -132,7 +134,7 @@ class QueryBuilder extends \yii\base\Object * ))->execute(); * ~~~ * - * Not that the values in each row must match the corresponding column names. + * Note that the values in each row must match the corresponding column names. * * @param string $table the table that new rows will be inserted into. * @param array $columns the column names @@ -161,7 +163,7 @@ class QueryBuilder extends \yii\base\Object * * @param string $table the table to be updated. * @param array $columns the column data (name => value) to be updated. - * @param mixed $condition the condition that will be put in the WHERE part. Please + * @param array|string $condition the condition that will be put in the WHERE part. Please * refer to [[Query::where()]] on how to specify condition. * @param array $params the binding parameters that will be modified by this method * so that they can be bound to the DB command later. @@ -205,7 +207,7 @@ class QueryBuilder extends \yii\base\Object * The method will properly escape the table and column names. * * @param string $table the table where the data will be deleted from. - * @param mixed $condition the condition that will be put in the WHERE part. Please + * @param array|string $condition the condition that will be put in the WHERE part. Please * refer to [[Query::where()]] on how to specify condition. * @param array $params the binding parameters that will be modified by this method * so that they can be bound to the DB command later. @@ -459,7 +461,7 @@ class QueryBuilder extends \yii\base\Object * The sequence will be reset such that the primary key of the next new row inserted * will have the specified value or 1. * @param string $table the name of the table whose primary key sequence will be reset - * @param mixed $value the value for the primary key of the next new row inserted. If this is not set, + * @param array|string $value the value for the primary key of the next new row inserted. If this is not set, * the next new row's primary key will have a value 1. * @return string the SQL statement for resetting sequence * @throws NotSupportedException if this is not supported by the underlying DBMS @@ -489,6 +491,7 @@ class QueryBuilder extends \yii\base\Object * physical types): * * - `pk`: an auto-incremental primary key type, will be converted into "int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY" + * - `bigpk`: an auto-incremental primary key type, will be converted into "bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY" * - `string`: string type, will be converted into "varchar(255)" * - `text`: a long string type, will be converted into "text" * - `smallint`: a small integer type, will be converted into "smallint(6)" @@ -718,9 +721,11 @@ class QueryBuilder extends \yii\base\Object } foreach ($unions as $i => $union) { if ($union instanceof Query) { + // save the original parameters so that we can restore them later to prevent from modifying the query object + $originalParams = $union->params; $union->addParams($params); - $unions[$i] = $this->build($union); - $params = $union->params; + list ($unions[$i], $params) = $this->build($union); + $union->params = $originalParams; } } return "UNION (\n" . implode("\n) UNION (\n", $unions) . "\n)"; @@ -799,7 +804,7 @@ class QueryBuilder extends \yii\base\Object $parts = array(); foreach ($condition as $column => $value) { if (is_array($value)) { // IN condition - $parts[] = $this->buildInCondition('in', array($column, $value), $params); + $parts[] = $this->buildInCondition('IN', array($column, $value), $params); } else { if (strpos($column, '(') === false) { $column = $this->db->quoteColumnName($column); @@ -851,8 +856,8 @@ class QueryBuilder extends \yii\base\Object $column = $this->db->quoteColumnName($column); } $phName1 = self::PARAM_PREFIX . count($params); - $phName2 = self::PARAM_PREFIX . count($params); $params[$phName1] = $value1; + $phName2 = self::PARAM_PREFIX . count($params); $params[$phName2] = $value2; return "$column $operator $phName1 AND $phName2"; @@ -908,11 +913,6 @@ class QueryBuilder extends \yii\base\Object protected function buildCompositeInCondition($operator, $columns, $values, &$params) { - foreach ($columns as $i => $column) { - if (strpos($column, '(') === false) { - $columns[$i] = $this->db->quoteColumnName($column); - } - } $vss = array(); foreach ($values as $value) { $vs = array(); @@ -927,6 +927,11 @@ class QueryBuilder extends \yii\base\Object } $vss[] = '(' . implode(', ', $vs) . ')'; } + foreach ($columns as $i => $column) { + if (strpos($column, '(') === false) { + $columns[$i] = $this->db->quoteColumnName($column); + } + } return '(' . implode(', ', $columns) . ") $operator (" . implode(', ', $vss) . ')'; } diff --git a/framework/yii/db/Schema.php b/framework/yii/db/Schema.php index 8804f77..1d86616 100644 --- a/framework/yii/db/Schema.php +++ b/framework/yii/db/Schema.php @@ -19,9 +19,12 @@ use yii\caching\GroupDependency; * * Schema represents the database schema information that is DBMS specific. * - * @property QueryBuilder $queryBuilder the query builder for the DBMS represented by this schema - * @property array $tableNames the names of all tables in this database. - * @property array $tableSchemas the schema information for all tables in this database. + * @property string $lastInsertID The row ID of the last row inserted, or the last value retrieved from the + * sequence object. This property is read-only. + * @property QueryBuilder $queryBuilder The query builder for this connection. This property is read-only. + * @property string[] $tableNames All table names in the database. This property is read-only. + * @property TableSchema[] $tableSchemas The metadata for all tables in the database. Each array element is an + * instance of [[TableSchema]] or its child class. This property is read-only. * * @author Qiang Xue * @since 2.0 @@ -32,6 +35,7 @@ abstract class Schema extends Object * The followings are the supported abstract column data types. */ const TYPE_PK = 'pk'; + const TYPE_BIGPK = 'bigpk'; const TYPE_STRING = 'string'; const TYPE_TEXT = 'text'; const TYPE_SMALLINT = 'smallint'; @@ -213,7 +217,7 @@ abstract class Schema extends Object * This method should be overridden by child classes in order to support this feature * because the default implementation simply throws an exception. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema. - * @return array all table names in the database. The names have NO the schema name prefix. + * @return array all table names in the database. The names have NO schema name prefix. * @throws NotSupportedException if this method is called */ protected function findTableNames($schema = '') diff --git a/framework/yii/db/TableSchema.php b/framework/yii/db/TableSchema.php index cad4c0a..910061d 100644 --- a/framework/yii/db/TableSchema.php +++ b/framework/yii/db/TableSchema.php @@ -13,7 +13,7 @@ use yii\base\InvalidParamException; /** * TableSchema represents the metadata of a database table. * - * @property array $columnNames list of column names + * @property array $columnNames List of column names. This property is read-only. * * @author Qiang Xue * @since 2.0 @@ -21,12 +21,6 @@ use yii\base\InvalidParamException; class TableSchema extends Object { /** - * @var string name of the catalog (database) that this table belongs to. - * Defaults to null, meaning no catalog (or the current database). - * This property is only meaningful for MSSQL. - */ - public $catalogName; - /** * @var string name of the schema that this table belongs to. */ public $schemaName; diff --git a/framework/yii/db/Transaction.php b/framework/yii/db/Transaction.php index 195a8c8..e0b90d9 100644 --- a/framework/yii/db/Transaction.php +++ b/framework/yii/db/Transaction.php @@ -29,7 +29,8 @@ use yii\base\InvalidConfigException; * } * ~~~ * - * @property boolean $isActive Whether the transaction is active. This property is read-only. + * @property boolean $isActive Whether this transaction is active. Only an active transaction can [[commit()]] + * or [[rollback()]]. This property is read-only. * * @author Qiang Xue * @since 2.0 diff --git a/framework/yii/db/cubrid/QueryBuilder.php b/framework/yii/db/cubrid/QueryBuilder.php new file mode 100644 index 0000000..4b7ef43 --- /dev/null +++ b/framework/yii/db/cubrid/QueryBuilder.php @@ -0,0 +1,117 @@ + + * @since 2.0 + */ +class QueryBuilder extends \yii\db\QueryBuilder +{ + /** + * @var array mapping from abstract column types (keys) to physical column types (values). + */ + public $typeMap = array( + Schema::TYPE_PK => 'int NOT NULL AUTO_INCREMENT PRIMARY KEY', + Schema::TYPE_BIGPK => 'bigint NOT NULL AUTO_INCREMENT PRIMARY KEY', + Schema::TYPE_STRING => 'varchar(255)', + Schema::TYPE_TEXT => 'varchar', + Schema::TYPE_SMALLINT => 'smallint', + Schema::TYPE_INTEGER => 'int', + Schema::TYPE_BIGINT => 'bigint', + Schema::TYPE_FLOAT => 'float(7)', + Schema::TYPE_DECIMAL => 'decimal(10,0)', + Schema::TYPE_DATETIME => 'datetime', + Schema::TYPE_TIMESTAMP => 'timestamp', + Schema::TYPE_TIME => 'time', + Schema::TYPE_DATE => 'date', + Schema::TYPE_BINARY => 'blob', + Schema::TYPE_BOOLEAN => 'smallint', + Schema::TYPE_MONEY => 'decimal(19,4)', + ); + + /** + * Creates a SQL statement for resetting the sequence value of a table's primary key. + * The sequence will be reset such that the primary key of the next new row inserted + * will have the specified value or 1. + * @param string $tableName the name of the table whose primary key sequence will be reset + * @param mixed $value the value for the primary key of the next new row inserted. If this is not set, + * the next new row's primary key will have a value 1. + * @return string the SQL statement for resetting sequence + * @throws InvalidParamException if the table does not exist or there is no sequence associated with the table. + */ + public function resetSequence($tableName, $value = null) + { + $table = $this->db->getTableSchema($tableName); + if ($table !== null && $table->sequenceName !== null) { + $tableName = $this->db->quoteTableName($tableName); + if ($value === null) { + $key = reset($table->primaryKey); + $value = (int)$this->db->createCommand("SELECT MAX(`$key`) FROM " . $this->db->schema->quoteTableName($tableName))->queryScalar() + 1; + } else { + $value = (int)$value; + } + return "ALTER TABLE " . $this->db->schema->quoteTableName($tableName) . " AUTO_INCREMENT=$value;"; + } elseif ($table === null) { + throw new InvalidParamException("Table not found: $tableName"); + } else { + throw new InvalidParamException("There is not sequence associated with table '$tableName'."); + } + } + + /** + * Generates a batch INSERT SQL statement. + * For example, + * + * ~~~ + * $connection->createCommand()->batchInsert('tbl_user', array('name', 'age'), array( + * array('Tom', 30), + * array('Jane', 20), + * array('Linda', 25), + * ))->execute(); + * ~~~ + * + * Note that the values in each row must match the corresponding column names. + * + * @param string $table the table that new rows will be inserted into. + * @param array $columns the column names + * @param array $rows the rows to be batch inserted into the table + * @return string the batch INSERT SQL statement + */ + public function batchInsert($table, $columns, $rows) + { + if (($tableSchema = $this->db->getTableSchema($table)) !== null) { + $columnSchemas = $tableSchema->columns; + } else { + $columnSchemas = array(); + } + + foreach ($columns as $i => $name) { + $columns[$i] = $this->db->quoteColumnName($name); + } + + $values = array(); + foreach ($rows as $row) { + $vs = array(); + foreach ($row as $i => $value) { + if (!is_array($value) && isset($columnSchemas[$columns[$i]])) { + $value = $columnSchemas[$columns[$i]]->typecast($value); + } + $vs[] = is_string($value) ? $this->db->quoteValue($value) : $value; + } + $values[] = '(' . implode(', ', $vs) . ')'; + } + + return 'INSERT INTO ' . $this->db->quoteTableName($table) + . ' (' . implode(', ', $columns) . ') VALUES ' . implode(', ', $values); + } +} diff --git a/framework/yii/db/cubrid/Schema.php b/framework/yii/db/cubrid/Schema.php new file mode 100644 index 0000000..ba7fcae --- /dev/null +++ b/framework/yii/db/cubrid/Schema.php @@ -0,0 +1,240 @@ + + * @since 2.0 + */ +class Schema extends \yii\db\Schema +{ + /** + * @var array mapping from physical column types (keys) to abstract column types (values) + * Please refer to [CUBRID manual](http://www.cubrid.org/manual/91/en/sql/datatype.html) for + * details on data types. + */ + public $typeMap = array( + // Numeric data types + 'short' => self::TYPE_SMALLINT, + 'smallint' => self::TYPE_SMALLINT, + 'int' => self::TYPE_INTEGER, + 'integer' => self::TYPE_INTEGER, + 'bigint' => self::TYPE_BIGINT, + 'numeric' => self::TYPE_DECIMAL, + 'decimal' => self::TYPE_DECIMAL, + 'float' => self::TYPE_FLOAT, + 'real' => self::TYPE_FLOAT, + 'double' => self::TYPE_FLOAT, + 'double precision' => self::TYPE_FLOAT, + 'monetary' => self::TYPE_MONEY, + // Date/Time data types + 'date' => self::TYPE_DATE, + 'time' => self::TYPE_TIME, + 'timestamp' => self::TYPE_TIMESTAMP, + 'datetime' => self::TYPE_DATETIME, + // String data types + 'char' => self::TYPE_STRING, + 'varchar' => self::TYPE_STRING, + 'char varying' => self::TYPE_STRING, + 'nchar' => self::TYPE_STRING, + 'nchar varying' => self::TYPE_STRING, + 'string' => self::TYPE_STRING, + // BLOB/CLOB data types + 'blob' => self::TYPE_BINARY, + 'clob' => self::TYPE_BINARY, + // Bit string data types + 'bit' => self::TYPE_STRING, + 'bit varying' => self::TYPE_STRING, + // Collection data types (considered strings for now) + 'set' => self::TYPE_STRING, + 'multiset' => self::TYPE_STRING, + 'list' => self::TYPE_STRING, + 'sequence' => self::TYPE_STRING, + 'enum' => self::TYPE_STRING, + ); + + /** + * Quotes a table name for use in a query. + * A simple table name has no schema prefix. + * @param string $name table name + * @return string the properly quoted table name + */ + public function quoteSimpleTableName($name) + { + return strpos($name, '"') !== false ? $name : '"' . $name . '"'; + } + + /** + * Quotes a column name for use in a query. + * A simple column name has no prefix. + * @param string $name column name + * @return string the properly quoted column name + */ + public function quoteSimpleColumnName($name) + { + return strpos($name, '"') !== false || $name === '*' ? $name : '"' . $name . '"'; + } + + /** + * Quotes a string value for use in a query. + * Note that if the parameter is not a string, it will be returned without change. + * @param string $str string to be quoted + * @return string the properly quoted string + * @see http://www.php.net/manual/en/function.PDO-quote.php + */ + public function quoteValue($str) + { + if (!is_string($str)) { + return $str; + } + + $this->db->open(); + // workaround for broken PDO::quote() implementation in CUBRID 9.1.0 http://jira.cubrid.org/browse/APIS-658 + if (version_compare($this->db->pdo->getAttribute(\PDO::ATTR_CLIENT_VERSION), '9.1.0', '<=')) { + return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'"; + } else { + return $this->db->pdo->quote($str); + } + } + + /** + * Creates a query builder for the CUBRID database. + * @return QueryBuilder query builder instance + */ + public function createQueryBuilder() + { + return new QueryBuilder($this->db); + } + + /** + * Loads the metadata for the specified table. + * @param string $name table name + * @return TableSchema driver dependent table metadata. Null if the table does not exist. + */ + protected function loadTableSchema($name) + { + $this->db->open(); + $tableInfo = $this->db->pdo->cubrid_schema(\PDO::CUBRID_SCH_TABLE, $name); + + if (isset($tableInfo[0]['NAME'])) { + $table = new TableSchema(); + $table->name = $tableInfo[0]['NAME']; + + $sql = 'SHOW FULL COLUMNS FROM ' . $this->quoteSimpleTableName($table->name); + $columns = $this->db->createCommand($sql)->queryAll(); + + foreach ($columns as $info) { + $column = $this->loadColumnSchema($info); + $table->columns[$column->name] = $column; + if ($column->isPrimaryKey) { + $table->primaryKey[] = $column->name; + if ($column->autoIncrement) { + $table->sequenceName = ''; + } + } + } + + $foreignKeys = $this->db->pdo->cubrid_schema(\PDO::CUBRID_SCH_IMPORTED_KEYS, $table->name); + foreach($foreignKeys as $key) { + if (isset($table->foreignKeys[$key['FK_NAME']])) { + $table->foreignKeys[$key['FK_NAME']][$key['FKCOLUMN_NAME']] = $key['PKCOLUMN_NAME']; + } else { + $table->foreignKeys[$key['FK_NAME']] = array( + $key['PKTABLE_NAME'], + $key['FKCOLUMN_NAME'] => $key['PKCOLUMN_NAME'] + ); + } + } + $table->foreignKeys = array_values($table->foreignKeys); + + return $table; + } else { + return null; + } + } + + /** + * Loads the column information into a [[ColumnSchema]] object. + * @param array $info column information + * @return ColumnSchema the column schema object + */ + protected function loadColumnSchema($info) + { + $column = new ColumnSchema(); + + $column->name = $info['Field']; + $column->allowNull = $info['Null'] === 'YES'; + $column->isPrimaryKey = strpos($info['Key'], 'PRI') !== false; + $column->autoIncrement = stripos($info['Extra'], 'auto_increment') !== false; + + $column->dbType = strtolower($info['Type']); + $column->unsigned = strpos($column->dbType, 'unsigned') !== false; + + $column->type = self::TYPE_STRING; + if (preg_match('/^([\w ]+)(?:\(([^\)]+)\))?/', $column->dbType, $matches)) { + $type = $matches[1]; + if (isset($this->typeMap[$type])) { + $column->type = $this->typeMap[$type]; + } + if (!empty($matches[2])) { + if ($type === 'enum') { + $values = explode(',', $matches[2]); + foreach ($values as $i => $value) { + $values[$i] = trim($value, "'"); + } + $column->enumValues = $values; + } else { + $values = explode(',', $matches[2]); + $column->size = $column->precision = (int)$values[0]; + if (isset($values[1])) { + $column->scale = (int)$values[1]; + } + } + } + } + + $column->phpType = $this->getColumnPhpType($column); + + if ($column->type === 'timestamp' && $info['Default'] === 'CURRENT_TIMESTAMP' || + $column->type === 'datetime' && $info['Default'] === 'SYS_DATETIME' || + $column->type === 'date' && $info['Default'] === 'SYS_DATE' || + $column->type === 'time' && $info['Default'] === 'SYS_TIME' + ) { + $column->defaultValue = new Expression($info['Default']); + } else { + $column->defaultValue = $column->typecast($info['Default']); + } + + return $column; + } + + /** + * Returns all table names in the database. + * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema. + * @return array all table names in the database. The names have NO schema name prefix. + */ + protected function findTableNames($schema = '') + { + $this->db->open(); + $tables = $this->db->pdo->cubrid_schema(\PDO::CUBRID_SCH_TABLE); + $tableNames = array(); + foreach($tables as $table) { + // do not list system tables + if ($table['TYPE'] != 0) { + $tableNames[] = $table['NAME']; + } + } + return $tableNames; + } +} diff --git a/framework/yii/db/mssql/QueryBuilder.php b/framework/yii/db/mssql/QueryBuilder.php index e7f8f80..aeb5be8 100644 --- a/framework/yii/db/mssql/QueryBuilder.php +++ b/framework/yii/db/mssql/QueryBuilder.php @@ -22,6 +22,7 @@ class QueryBuilder extends \yii\db\QueryBuilder */ public $typeMap = array( Schema::TYPE_PK => 'int IDENTITY PRIMARY KEY', + Schema::TYPE_BIGPK => 'bigint IDENTITY PRIMARY KEY', Schema::TYPE_STRING => 'varchar(255)', Schema::TYPE_TEXT => 'text', Schema::TYPE_SMALLINT => 'smallint(6)', diff --git a/framework/yii/db/mssql/Schema.php b/framework/yii/db/mssql/Schema.php index ad0f7d4..9def3b4 100644 --- a/framework/yii/db/mssql/Schema.php +++ b/framework/yii/db/mssql/Schema.php @@ -7,7 +7,6 @@ namespace yii\db\mssql; -use yii\db\TableSchema; use yii\db\ColumnSchema; /** @@ -332,10 +331,8 @@ SQL; /** * Returns all table names in the database. - * This method should be overridden by child classes in order to support this feature - * because the default implementation simply throws an exception. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema. - * @return array all table names in the database. The names have NO the schema name prefix. + * @return array all table names in the database. The names have NO schema name prefix. */ protected function findTableNames($schema = '') { diff --git a/framework/yii/db/mssql/TableSchema.php b/framework/yii/db/mssql/TableSchema.php new file mode 100644 index 0000000..67ad85c --- /dev/null +++ b/framework/yii/db/mssql/TableSchema.php @@ -0,0 +1,23 @@ + + * @since 2.0 + */ +class TableSchema extends \yii\db\TableSchema +{ + /** + * @var string name of the catalog (database) that this table belongs to. + * Defaults to null, meaning no catalog (or the current database). + */ + public $catalogName; +} diff --git a/framework/yii/db/mysql/QueryBuilder.php b/framework/yii/db/mysql/QueryBuilder.php index 0307abd..386de2f 100644 --- a/framework/yii/db/mysql/QueryBuilder.php +++ b/framework/yii/db/mysql/QueryBuilder.php @@ -23,6 +23,7 @@ class QueryBuilder extends \yii\db\QueryBuilder */ public $typeMap = array( Schema::TYPE_PK => 'int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY', + Schema::TYPE_BIGPK => 'bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY', Schema::TYPE_STRING => 'varchar(255)', Schema::TYPE_TEXT => 'text', Schema::TYPE_SMALLINT => 'smallint(6)', @@ -152,7 +153,7 @@ class QueryBuilder extends \yii\db\QueryBuilder * ))->execute(); * ~~~ * - * Not that the values in each row must match the corresponding column names. + * Note that the values in each row must match the corresponding column names. * * @param string $table the table that new rows will be inserted into. * @param array $columns the column names diff --git a/framework/yii/db/mysql/Schema.php b/framework/yii/db/mysql/Schema.php index 225ef38..998f49a 100644 --- a/framework/yii/db/mysql/Schema.php +++ b/framework/yii/db/mysql/Schema.php @@ -236,10 +236,8 @@ class Schema extends \yii\db\Schema /** * Returns all table names in the database. - * This method should be overridden by child classes in order to support this feature - * because the default implementation simply throws an exception. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema. - * @return array all table names in the database. The names have NO the schema name prefix. + * @return array all table names in the database. The names have NO schema name prefix. */ protected function findTableNames($schema = '') { diff --git a/framework/yii/db/pgsql/QueryBuilder.php b/framework/yii/db/pgsql/QueryBuilder.php index 9701fd6..33c7bf6 100644 --- a/framework/yii/db/pgsql/QueryBuilder.php +++ b/framework/yii/db/pgsql/QueryBuilder.php @@ -21,7 +21,8 @@ class QueryBuilder extends \yii\db\QueryBuilder * @var array mapping from abstract column types (keys) to physical column types (values). */ public $typeMap = array( - Schema::TYPE_PK => 'serial not null primary key', + Schema::TYPE_PK => 'serial NOT NULL PRIMARY KEY', + Schema::TYPE_BIGPK => 'bigserial NOT NULL PRIMARY KEY', Schema::TYPE_STRING => 'varchar(255)', Schema::TYPE_TEXT => 'text', Schema::TYPE_SMALLINT => 'smallint', diff --git a/framework/yii/db/pgsql/Schema.php b/framework/yii/db/pgsql/Schema.php index 8acb7bd..d131342 100644 --- a/framework/yii/db/pgsql/Schema.php +++ b/framework/yii/db/pgsql/Schema.php @@ -129,6 +129,35 @@ class Schema extends \yii\db\Schema } /** + * Returns all table names in the database. + * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema. + * If not empty, the returned table names will be prefixed with the schema name. + * @return array all table names in the database. + */ + protected function findTableNames($schema = '') + { + if ($schema === '') { + $schema = $this->defaultSchema; + } + $sql = <<db->createCommand($sql); + $command->bindParam(':schema', $schema); + $rows = $command->queryAll(); + $names = array(); + foreach ($rows as $row) { + if ($schema === $this->defaultSchema) { + $names[] = $row['table_name']; + } else { + $names[] = $row['table_schema'] . '.' . $row['table_name']; + } + } + return $names; + } + + /** * Collects the foreign key column details for the given table. * @param TableSchema $table the table metadata */ @@ -171,7 +200,7 @@ SQL; } $citem = array($foreignTable); foreach ($columns as $idx => $column) { - $citem[] = array($fcolumns[$idx] => $column); + $citem[$fcolumns[$idx]] = $column; } $table->foreignKeys[] = $citem; } @@ -226,7 +255,7 @@ SELECT information_schema._pg_char_max_length(information_schema._pg_truetypid(a, t), information_schema._pg_truetypmod(a, t)) AS numeric ) AS size, - a.attnum = any (ct.conkey) as is_pkey + a.attnum = any (ct.conkey) as is_pkey FROM pg_class c LEFT JOIN pg_attribute a ON a.attrelid = c.oid diff --git a/framework/yii/db/sqlite/QueryBuilder.php b/framework/yii/db/sqlite/QueryBuilder.php index be0275a..4e210f8 100644 --- a/framework/yii/db/sqlite/QueryBuilder.php +++ b/framework/yii/db/sqlite/QueryBuilder.php @@ -24,6 +24,7 @@ class QueryBuilder extends \yii\db\QueryBuilder */ public $typeMap = array( Schema::TYPE_PK => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL', + Schema::TYPE_BIGPK => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL', Schema::TYPE_STRING => 'varchar(255)', Schema::TYPE_TEXT => 'text', Schema::TYPE_SMALLINT => 'smallint', diff --git a/framework/yii/db/sqlite/Schema.php b/framework/yii/db/sqlite/Schema.php index d4fb245..bca26c1 100644 --- a/framework/yii/db/sqlite/Schema.php +++ b/framework/yii/db/sqlite/Schema.php @@ -126,7 +126,13 @@ class Schema extends \yii\db\Schema $sql = "PRAGMA foreign_key_list(" . $this->quoteSimpleTableName($table->name) . ')'; $keys = $this->db->createCommand($sql)->queryAll(); foreach ($keys as $key) { - $table->foreignKeys[] = array($key['table'], $key['from'] => $key['to']); + $id = (int)$key['id']; + if (!isset($table->foreignKeys[$id])) { + $table->foreignKeys[$id] = array($key['table'], $key['from'] => $key['to']); + } else { + // composite FK + $table->foreignKeys[$id][$key['from']] = $key['to']; + } } } diff --git a/framework/yii/debug/LogTarget.php b/framework/yii/debug/LogTarget.php index 3e36cd5..b415b50 100644 --- a/framework/yii/debug/LogTarget.php +++ b/framework/yii/debug/LogTarget.php @@ -11,6 +11,8 @@ use Yii; use yii\log\Target; /** + * The debug LogTarget is used to store logs for later use in the debugger tool + * * @author Qiang Xue * @since 2.0 */ diff --git a/framework/yii/debug/Module.php b/framework/yii/debug/Module.php index 2246520..dd027a7 100644 --- a/framework/yii/debug/Module.php +++ b/framework/yii/debug/Module.php @@ -12,6 +12,8 @@ use yii\base\View; use yii\web\HttpException; /** + * The Yii Debug Module provides the debug toolbar and debugger + * * @author Qiang Xue * @since 2.0 */ diff --git a/framework/yii/debug/Panel.php b/framework/yii/debug/Panel.php index dc297f4..6782264 100644 --- a/framework/yii/debug/Panel.php +++ b/framework/yii/debug/Panel.php @@ -14,6 +14,11 @@ use yii\base\Component; * Panel is a base class for debugger panel classes. It defines how data should be collected, * what should be displayed at debug toolbar and on debugger details view. * + * @property string $detail Content that is displayed in debugger detail view. This property is read-only. + * @property string $name Name of the panel. This property is read-only. + * @property string $summary Content that is displayed at debug toolbar. This property is read-only. + * @property string $url URL pointing to panel detail view. This property is read-only. + * * @author Qiang Xue * @since 2.0 */ diff --git a/framework/yii/debug/assets/main.css b/framework/yii/debug/assets/main.css index 6cb65dd..7953873 100644 --- a/framework/yii/debug/assets/main.css +++ b/framework/yii/debug/assets/main.css @@ -131,6 +131,7 @@ ul.trace { margin: 2px 0 0 0; padding: 0; list-style: none; + white-space: normal; } .callout-danger { diff --git a/framework/yii/gii/CodeFile.php b/framework/yii/gii/CodeFile.php index d3dcd43..2f21b4c 100644 --- a/framework/yii/gii/CodeFile.php +++ b/framework/yii/gii/CodeFile.php @@ -16,6 +16,10 @@ use yii\helpers\StringHelper; /** * CodeFile represents a code file to be generated. * + * @property string $relativePath The code file path relative to the application base path. This property is + * read-only. + * @property string $type The code file extension (e.g. php, txt). This property is read-only. + * * @author Qiang Xue * @since 2.0 */ diff --git a/framework/yii/gii/Generator.php b/framework/yii/gii/Generator.php index 68ca640..eb5b8b4 100644 --- a/framework/yii/gii/Generator.php +++ b/framework/yii/gii/Generator.php @@ -27,6 +27,12 @@ use yii\base\View; * - [[generate()]]: generates the code based on the current user input and the specified code template files. * This is the place where main code generation code resides. * + * @property string $description The detailed description of the generator. This property is read-only. + * @property string $stickyDataFile The file path that stores the sticky attribute values. This property is + * read-only. + * @property string $templatePath The root path of the template files that are currently being used. This + * property is read-only. + * * @author Qiang Xue * @since 2.0 */ @@ -319,6 +325,28 @@ abstract class Generator extends Model } /** + * An inline validator that checks if the attribute value refers to a valid namespaced class name. + * The validator will check if the directory containing the new class file exist or not. + * @param string $attribute the attribute being validated + * @param array $params the validation options + */ + public function validateNewClass($attribute, $params) + { + $class = ltrim($this->$attribute, '\\'); + if (($pos = strrpos($class, '\\')) === false) { + $this->addError($attribute, "The class name must contain fully qualified namespace name."); + } else { + $ns = substr($class, 0, $pos); + $path = Yii::getAlias('@' . str_replace('\\', '/', $ns), false); + if ($path === false) { + $this->addError($attribute, "The class namespace is invalid: $ns"); + } elseif (!is_dir($path)) { + $this->addError($attribute, "Please make sure the directory containing this class exists: $path"); + } + } + } + + /** * @param string $value the attribute to be validated * @return boolean whether the value is a reserved PHP keyword. */ diff --git a/framework/yii/gii/assets/gii.js b/framework/yii/gii/assets/gii.js index 284006e..b581d3b 100644 --- a/framework/yii/gii/assets/gii.js +++ b/framework/yii/gii/assets/gii.js @@ -76,6 +76,11 @@ yii.gii = (function ($) { initPreviewDiffLinks(); initConfirmationCheckboxes(); + // model generator: hide class name input when table name input contains * + $('#model-generator #generator-tablename').on('change', function () { + $('#model-generator .field-generator-modelclass').toggle($(this).val().indexOf('*') == -1); + }).change(); + // hide Generate button if any input is changed $('.default-view .form-group input,select,textarea').change(function () { $('.default-view-results,.default-view-files').hide(); diff --git a/framework/yii/gii/controllers/DefaultController.php b/framework/yii/gii/controllers/DefaultController.php index 9bc444e..305ef35 100644 --- a/framework/yii/gii/controllers/DefaultController.php +++ b/framework/yii/gii/controllers/DefaultController.php @@ -7,6 +7,7 @@ namespace yii\gii\controllers; +use Yii; use yii\web\Controller; use yii\web\HttpException; @@ -35,7 +36,7 @@ class DefaultController extends Controller public function actionView($id) { $generator = $this->loadGenerator($id); - $params = array('generator' => $generator); + $params = array('generator' => $generator, 'id' => $id); if (isset($_POST['preview']) || isset($_POST['generate'])) { if ($generator->validate()) { $generator->saveStickyAttributes(); @@ -86,6 +87,26 @@ class DefaultController extends Controller throw new HttpException(404, "Code file not found: $file"); } + /** + * Runs an action defined in the generator. + * Given an action named "xyz", the method "actionXyz()" in the generator will be called. + * If the method does not exist, a 400 HTTP exception will be thrown. + * @param string $id the ID of the generator + * @param string $name the action name + * @return mixed the result of the action. + * @throws HttpException if the action method does not exist. + */ + public function actionAction($id, $name) + { + $generator = $this->loadGenerator($id); + $method = 'action' . $name; + if (method_exists($generator, $method)) { + return $generator->$method(); + } else { + throw new HttpException(400, "Unknown generator action: $name"); + } + } + public function createUrl($route, $params = array()) { if (!isset($params['id']) && $this->generator !== null) { @@ -99,6 +120,18 @@ class DefaultController extends Controller return parent::createUrl($route, $params); } + public function createActionUrl($name, $params = array()) + { + foreach ($this->module->generators as $id => $generator) { + if ($generator === $this->generator) { + $params['id'] = $id; + break; + } + } + $params['name'] = $name; + return parent::createUrl('action', $params); + } + /** * Loads the generator with the specified ID. * @param string $id the ID of the generator to be loaded. diff --git a/framework/yii/gii/generators/controller/Generator.php b/framework/yii/gii/generators/controller/Generator.php index c57b2b2..9de9c17 100644 --- a/framework/yii/gii/generators/controller/Generator.php +++ b/framework/yii/gii/generators/controller/Generator.php @@ -78,7 +78,7 @@ class Generator extends \yii\gii\Generator 'baseClass' => 'Base Class', 'controller' => 'Controller ID', 'actions' => 'Action IDs', - 'ns' => 'Namespace', + 'ns' => 'Controller Namespace', ); } diff --git a/framework/yii/gii/generators/crud/Generator.php b/framework/yii/gii/generators/crud/Generator.php index 15da2c2..9bce7ff 100644 --- a/framework/yii/gii/generators/crud/Generator.php +++ b/framework/yii/gii/generators/crud/Generator.php @@ -7,6 +7,14 @@ namespace yii\gii\generators\crud; +use Yii; +use yii\base\Model; +use yii\db\ActiveRecord; +use yii\db\Schema; +use yii\gii\CodeFile; +use yii\helpers\Inflector; +use yii\web\Controller; + /** * * @author Qiang Xue @@ -14,6 +22,13 @@ namespace yii\gii\generators\crud; */ class Generator extends \yii\gii\Generator { + public $modelClass; + public $moduleID; + public $controllerClass; + public $baseControllerClass = 'yii\web\Controller'; + public $indexWidgetType = 'grid'; + public $searchModelClass; + public function getName() { return 'CRUD Generator'; @@ -25,11 +40,350 @@ class Generator extends \yii\gii\Generator operations for the specified data model.'; } + public function rules() + { + return array_merge(parent::rules(), array( + array('moduleID, controllerClass, modelClass, searchModelClass, baseControllerClass', 'filter', 'filter' => 'trim'), + array('modelClass, searchModelClass, controllerClass, baseControllerClass, indexWidgetType', 'required'), + array('modelClass, controllerClass, baseControllerClass, searchModelClass', 'match', 'pattern' => '/^[\w\\\\]*$/', 'message' => 'Only word characters and backslashes are allowed.'), + array('modelClass', 'validateClass', 'params' => array('extends' => ActiveRecord::className())), + array('baseControllerClass', 'validateClass', 'params' => array('extends' => Controller::className())), + array('controllerClass', 'match', 'pattern' => '/Controller$/', 'message' => 'Controller class name must be suffixed with "Controller".'), + array('controllerClass, searchModelClass', 'validateNewClass'), + array('indexWidgetType', 'in', 'range' => array('grid', 'list')), + array('modelClass', 'validateModelClass'), + array('moduleID', 'validateModuleID'), + )); + } + + public function attributeLabels() + { + return array_merge(parent::attributeLabels(), array( + 'modelClass' => 'Model Class', + 'moduleID' => 'Module ID', + 'controllerClass' => 'Controller Class', + 'baseControllerClass' => 'Base Controller Class', + 'indexWidgetType' => 'Widget Used in Index Page', + 'searchModelClass' => 'Search Model Class', + )); + } + + /** + * @inheritdoc + */ + public function hints() + { + return array( + 'modelClass' => 'This is the ActiveRecord class associated with the table that CRUD will be built upon. + You should provide a fully qualified class name, e.g., app\models\Post.', + 'controllerClass' => 'This is the name of the controller class to be generated. You should + provide a fully qualified namespaced class, .e.g, app\controllers\PostController.', + 'baseControllerClass' => 'This is the class that the new CRUD controller class will extend from. + You should provide a fully qualified class name, e.g., yii\web\Controller.', + 'moduleID' => 'This is the ID of the module that the generated controller will belong to. + If not set, it means the controller will belong to the application.', + 'indexWidgetType' => 'This is the widget type to be used in the index page to display list of the models. + You may choose either GridView or ListView', + 'searchModelClass' => 'This is the class representing the data being collecting in the search form. + A fully qualified namespaced class name is required, e.g., app\models\search\PostSearch.', + ); + } + + public function requiredTemplates() + { + return array( + 'controller.php', + ); + } + + /** + * @inheritdoc + */ + public function stickyAttributes() + { + return array('baseControllerClass', 'moduleID', 'indexWidgetType'); + } + + public function validateModelClass() + { + /** @var ActiveRecord $class */ + $class = $this->modelClass; + $pk = $class::primaryKey(); + if (empty($pk)) { + $this->addError('modelClass', "The table associated with $class must have primary key(s)."); + } + } + + public function validateModuleID() + { + if (!empty($this->moduleID)) { + $module = Yii::$app->getModule($this->moduleID); + if ($module === null) { + $this->addError('moduleID', "Module '{$this->moduleID}' does not exist."); + } + } + } + /** * @inheritdoc */ public function generate() { - return array(); + $controllerFile = Yii::getAlias('@' . str_replace('\\', '/', ltrim($this->controllerClass, '\\')) . '.php'); + $searchModel = Yii::getAlias('@' . str_replace('\\', '/', ltrim($this->searchModelClass, '\\') . '.php')); + $files = array( + new CodeFile($controllerFile, $this->render('controller.php')), + new CodeFile($searchModel, $this->render('search.php')), + ); + + $viewPath = $this->getViewPath(); + $templatePath = $this->getTemplatePath() . '/views'; + foreach (scandir($templatePath) as $file) { + if (is_file($templatePath . '/' . $file) && pathinfo($file, PATHINFO_EXTENSION) === 'php') { + $files[] = new CodeFile("$viewPath/$file", $this->render("views/$file")); + } + } + + + return $files; + } + + /** + * @return string the controller ID (without the module ID prefix) + */ + public function getControllerID() + { + $pos = strrpos($this->controllerClass, '\\'); + $class = substr(substr($this->controllerClass, $pos + 1), 0, -10); + return Inflector::camel2id($class); + } + + /** + * @return string the action view file path + */ + public function getViewPath() + { + $module = empty($this->moduleID) ? Yii::$app : Yii::$app->getModule($this->moduleID); + return $module->getViewPath() . '/' . $this->getControllerID() ; + } + + public function getNameAttribute() + { + /** @var \yii\db\ActiveRecord $class */ + $class = $this->modelClass; + foreach ($class::getTableSchema()->columnNames as $name) { + if (!strcasecmp($name, 'name') || !strcasecmp($name, 'title')) { + return $name; + } + } + $pk = $class::primaryKey(); + return $pk[0]; + } + + /** + * @param string $attribute + * @return string + */ + public function generateActiveField($attribute) + { + $tableSchema = $this->getTableSchema(); + if (!isset($tableSchema->columns[$attribute])) { + return "\$form->field(\$model, '$attribute');"; + } + $column = $tableSchema->columns[$attribute]; + if ($column->phpType === 'boolean') { + return "\$form->field(\$model, '$attribute')->checkbox();"; + } elseif ($column->type === 'text') { + return "\$form->field(\$model, '$attribute')->textarea(array('rows' => 6));"; + } else { + if (preg_match('/^(password|pass|passwd|passcode)$/i', $column->name)) { + $input = 'passwordInput'; + } else { + $input = 'textInput'; + } + if ($column->phpType !== 'string' || $column->size === null) { + return "\$form->field(\$model, '$attribute')->$input();"; + } else { + return "\$form->field(\$model, '$attribute')->$input(array('maxlength' => $column->size));"; + } + } + } + + /** + * @param string $attribute + * @return string + */ + public function generateActiveSearchField($attribute) + { + $tableSchema = $this->getTableSchema(); + $column = $tableSchema->columns[$attribute]; + if ($column->phpType === 'boolean') { + return "\$form->field(\$model, '$attribute')->checkbox();"; + } else { + return "\$form->field(\$model, '$attribute');"; + } + } + + /** + * @param \yii\db\ColumnSchema $column + * @return string + */ + public function generateColumnFormat($column) + { + if ($column->phpType === 'boolean') { + return 'boolean'; + } elseif ($column->type === 'text') { + return 'ntext'; + } elseif (stripos($column->name, 'time') !== false && $column->phpType === 'integer') { + return 'datetime'; + } elseif (stripos($column->name, 'email') !== false) { + return 'email'; + } elseif (stripos($column->name, 'url') !== false) { + return 'url'; + } else { + return 'text'; + } + } + + /** + * Generates validation rules for the search model. + * @return array the generated validation rules + */ + public function generateSearchRules() + { + $table = $this->getTableSchema(); + $types = array(); + foreach ($table->columns as $column) { + switch ($column->type) { + case Schema::TYPE_SMALLINT: + case Schema::TYPE_INTEGER: + case Schema::TYPE_BIGINT: + $types['integer'][] = $column->name; + break; + case Schema::TYPE_BOOLEAN: + $types['boolean'][] = $column->name; + break; + case Schema::TYPE_FLOAT: + case Schema::TYPE_DECIMAL: + case Schema::TYPE_MONEY: + $types['number'][] = $column->name; + break; + case Schema::TYPE_DATE: + case Schema::TYPE_TIME: + case Schema::TYPE_DATETIME: + case Schema::TYPE_TIMESTAMP: + default: + $types['safe'][] = $column->name; + break; + } + } + + $rules = array(); + foreach ($types as $type => $columns) { + $rules[] = "array('" . implode(', ', $columns) . "', '$type')"; + } + + return $rules; + } + + public function getSearchAttributes() + { + return $this->getTableSchema()->getColumnNames(); + } + + /** + * Generates the attribute labels for the search model. + * @return array the generated attribute labels (name => label) + */ + public function generateSearchLabels() + { + $table = $this->getTableSchema(); + $labels = array(); + foreach ($table->columns as $column) { + if (!strcasecmp($column->name, 'id')) { + $labels[$column->name] = 'ID'; + } else { + $label = Inflector::camel2words($column->name); + if (strcasecmp(substr($label, -3), ' id') === 0) { + $label = substr($label, 0, -3) . ' ID'; + } + $labels[$column->name] = $label; + } + } + return $labels; + } + + public function generateSearchConditions() + { + $table = $this->getTableSchema(); + $conditions = array(); + foreach ($table->columns as $column) { + switch ($column->type) { + case Schema::TYPE_SMALLINT: + case Schema::TYPE_INTEGER: + case Schema::TYPE_BIGINT: + case Schema::TYPE_BOOLEAN: + case Schema::TYPE_FLOAT: + case Schema::TYPE_DECIMAL: + case Schema::TYPE_MONEY: + case Schema::TYPE_DATE: + case Schema::TYPE_TIME: + case Schema::TYPE_DATETIME: + case Schema::TYPE_TIMESTAMP: + $conditions[] = "\$this->addCondition(\$query, '{$column->name}');"; + break; + default: + $conditions[] = "\$this->addCondition(\$query, '{$column->name}', true);"; + break; + } + } + + return $conditions; + } + + public function generateUrlParams() + { + $pks = $this->getTableSchema()->primaryKey; + if (count($pks) === 1) { + return "'id' => \$model->{$pks[0]}"; + } else { + $params = array(); + foreach ($pks as $pk) { + $params[] = "'$pk' => \$model->$pk"; + } + return implode(', ', $params); + } + } + + public function generateActionParams() + { + $pks = $this->getTableSchema()->primaryKey; + if (count($pks) === 1) { + return '$id'; + } else { + return '$' . implode(', $', $pks); + } + } + + public function generateActionParamComments() + { + $table = $this->getTableSchema(); + $pks = $table->primaryKey; + if (count($pks) === 1) { + return array('@param ' . $table->columns[$pks[0]]->phpType . ' $id'); + } else { + $params = array(); + foreach ($pks as $pk) { + $params[] = '@param ' . $table->columns[$pk]->phpType . ' $' . $pk; + } + return $params; + } + } + + public function getTableSchema() + { + /** @var ActiveRecord $class */ + $class = $this->modelClass; + return $class::getTableSchema(); } } diff --git a/framework/yii/gii/generators/crud/form.php b/framework/yii/gii/generators/crud/form.php new file mode 100644 index 0000000..829b8a3 --- /dev/null +++ b/framework/yii/gii/generators/crud/form.php @@ -0,0 +1,16 @@ +field($generator, 'modelClass'); +echo $form->field($generator, 'searchModelClass'); +echo $form->field($generator, 'controllerClass'); +echo $form->field($generator, 'baseControllerClass'); +echo $form->field($generator, 'moduleID'); +echo $form->field($generator, 'indexWidgetType')->dropDownList(array( + 'grid' => 'GridView', + 'list' => 'ListView', +)); diff --git a/framework/yii/gii/generators/crud/templates/controller.php b/framework/yii/gii/generators/crud/templates/controller.php new file mode 100644 index 0000000..fd33eda --- /dev/null +++ b/framework/yii/gii/generators/crud/templates/controller.php @@ -0,0 +1,139 @@ +controllerClass); +$modelClass = StringHelper::basename($generator->modelClass); +$searchModelClass = StringHelper::basename($generator->searchModelClass); + +$pks = $generator->getTableSchema()->primaryKey; +$urlParams = $generator->generateUrlParams(); +$actionParams = $generator->generateActionParams(); +$actionParamComments = $generator->generateActionParamComments(); + +echo " + +namespace controllerClass, '\\')); ?>; + +use modelClass, '\\'); ?>; +use searchModelClass, '\\'); ?>; +use yii\data\ActiveDataProvider; +use baseControllerClass, '\\'); ?>; +use yii\web\HttpException; + +/** + * implements the CRUD actions for model. + */ +class extends baseControllerClass) . "\n"; ?> +{ + /** + * Lists all models. + * @return mixed + */ + public function actionIndex() + { + $searchModel = new ; + $dataProvider = $searchModel->search($_GET); + + return $this->render('index', array( + 'dataProvider' => $dataProvider, + 'searchModel' => $searchModel, + )); + } + + /** + * Displays a single model. + * + * @return mixed + */ + public function actionView() + { + return $this->render('view', array( + 'model' => $this->findModel(), + )); + } + + /** + * Creates a new model. + * If creation is successful, the browser will be redirected to the 'view' page. + * @return mixed + */ + public function actionCreate() + { + $model = new ; + + if ($model->load($_POST) && $model->save()) { + return $this->redirect(array('view', )); + } else { + return $this->render('create', array( + 'model' => $model, + )); + } + } + + /** + * Updates an existing model. + * If update is successful, the browser will be redirected to the 'view' page. + * + * @return mixed + */ + public function actionUpdate() + { + $model = $this->findModel(); + + if ($model->load($_POST) && $model->save()) { + return $this->redirect(array('view', )); + } else { + return $this->render('update', array( + 'model' => $model, + )); + } + } + + /** + * Deletes an existing model. + * If deletion is successful, the browser will be redirected to the 'index' page. + * + * @return mixed + */ + public function actionDelete() + { + $this->findModel()->delete(); + return $this->redirect(array('index')); + } + + /** + * Finds the model based on its primary key value. + * If the model is not found, a 404 HTTP exception will be thrown. + * + * @return the loaded model + * @throws HttpException if the model cannot be found + */ + protected function findModel() + { + \$$pk"; + } + $condition = 'array(' . implode(', ', $condition) . ')'; +} +?> + if (($model = ::find()) !== null) { + return $model; + } else { + throw new HttpException(404, 'The requested page does not exist.'); + } + } +} diff --git a/framework/yii/gii/generators/crud/templates/search.php b/framework/yii/gii/generators/crud/templates/search.php new file mode 100644 index 0000000..467cee5 --- /dev/null +++ b/framework/yii/gii/generators/crud/templates/search.php @@ -0,0 +1,83 @@ +modelClass); +$searchModelClass = StringHelper::basename($generator->searchModelClass); +$rules = $generator->generateSearchRules(); +$labels = $generator->generateSearchLabels(); +$searchAttributes = $generator->getSearchAttributes(); +$searchConditions = $generator->generateSearchConditions(); + +echo " + +namespace searchModelClass, '\\')); ?>; + +use yii\base\Model; +use yii\data\ActiveDataProvider; +use modelClass, '\\'); ?>; + +/** + * represents the model behind the search form about . + */ +class extends Model +{ + public $; + + public function rules() + { + return array( + , + ); + } + + /** + * @inheritdoc + */ + public function attributeLabels() + { + return array( + $label): ?> + '" . addslashes($label) . "',\n"; ?> + + ); + } + + public function search($params) + { + $query = ::find(); + $dataProvider = new ActiveDataProvider(array( + 'query' => $query, + )); + + if (!($this->load($params) && $this->validate())) { + return $dataProvider; + } + + + + return $dataProvider; + } + + protected function addCondition($query, $attribute, $partialMatch = false) + { + $value = $this->$attribute; + if (trim($value) === '') { + return; + } + if ($partialMatch) { + $value = '%' . strtr($value, array('%'=>'\%', '_'=>'\_', '\\'=>'\\\\')) . '%'; + $query->andWhere(array('like', $attribute, $value)); + } else { + $query->andWhere(array($attribute => $value)); + } + } +} diff --git a/framework/yii/gii/generators/crud/templates/views/_form.php b/framework/yii/gii/generators/crud/templates/views/_form.php new file mode 100644 index 0000000..2d9d5dc --- /dev/null +++ b/framework/yii/gii/generators/crud/templates/views/_form.php @@ -0,0 +1,44 @@ +modelClass; +$safeAttributes = $model->safeAttributes(); +if (empty($safeAttributes)) { + $safeAttributes = $model->getTableSchema()->columnNames; +} + +echo " + +use yii\helpers\Html; +use yii\widgets\ActiveForm; + +/** + * @var yii\base\View $this + * @var modelClass, '\\'); ?> $model + * @var yii\widgets\ActiveForm $form + */ +?> + +
+ + $form = ActiveForm::begin(); ?> + +generateActiveField($attribute) . " ?>\n\n"; +} ?> +
+ echo Html::submitButton($model->isNewRecord ? 'Create' : 'Update', array('class' => 'btn btn-primary')); ?> +
+ + ActiveForm::end(); ?> + +
diff --git a/framework/yii/gii/generators/crud/templates/views/_search.php b/framework/yii/gii/generators/crud/templates/views/_search.php new file mode 100644 index 0000000..a649589 --- /dev/null +++ b/framework/yii/gii/generators/crud/templates/views/_search.php @@ -0,0 +1,45 @@ + + +use yii\helpers\Html; +use yii\widgets\ActiveForm; + +/** + * @var yii\base\View $this + * @var searchModelClass, '\\'); ?> $model + * @var yii\widgets\ActiveForm $form + */ +?> + + diff --git a/framework/yii/gii/generators/crud/templates/views/create.php b/framework/yii/gii/generators/crud/templates/views/create.php new file mode 100644 index 0000000..669b99a --- /dev/null +++ b/framework/yii/gii/generators/crud/templates/views/create.php @@ -0,0 +1,33 @@ + + +use yii\helpers\Html; + +/** + * @var yii\base\View $this + * @var modelClass, '\\'); ?> $model + */ + +$this->title = 'Create modelClass)); ?>'; +$this->params['breadcrumbs'][] = array('label' => 'modelClass))); ?>', 'url' => array('index')); +$this->params['breadcrumbs'][] = $this->title; +?> +
+ +

echo Html::encode($this->title); ?>

+ + echo $this->render('_form', array( + 'model' => $model, + )); ?> + +
diff --git a/framework/yii/gii/generators/crud/templates/views/index.php b/framework/yii/gii/generators/crud/templates/views/index.php new file mode 100644 index 0000000..8efa53a --- /dev/null +++ b/framework/yii/gii/generators/crud/templates/views/index.php @@ -0,0 +1,71 @@ +generateUrlParams(); +$nameAttribute = $generator->getNameAttribute(); + +echo " + +use yii\helpers\Html; +use indexWidgetType === 'grid' ? 'yii\grid\GridView' : 'yii\widgets\ListView'; ?>; + +/** + * @var yii\base\View $this + * @var yii\data\ActiveDataProvider $dataProvider + * @var searchModelClass, '\\'); ?> $searchModel + */ + +$this->title = 'modelClass))); ?>'; +$this->params['breadcrumbs'][] = $this->title; +?> +
+ +

echo Html::encode($this->title); ?>

+ + echo $this->render('_search', array('model' => $searchModel)); ?> + +
+ +
+ echo Html::a('Create modelClass); ?>', array('create'), array('class' => 'btn btn-danger')); ?> +
+ +indexWidgetType === 'grid'): ?> + echo GridView::widget(array( + 'dataProvider' => $dataProvider, + 'filterModel' => $searchModel, + 'columns' => array( +getTableSchema()->columns as $column) { + $format = $generator->generateColumnFormat($column); + if (++$count < 6) { + echo "\t\t\t'" . $column->name . ($format === 'text' ? '' : ':' . $format) . "',\n"; + } else { + echo "\t\t\t// '" . $column->name . ($format === 'text' ? '' : ':' . $format) . "',\n"; + } +} +?> + ), + )); ?> + + echo ListView::widget(array( + 'dataProvider' => $dataProvider, + 'itemOptions' => array( + 'class' => 'item', + ), + 'itemView' => function ($model, $key, $index, $widget) { + return Html::a(Html::encode($model->), array('view', ); + }, + )); ?> + + +
diff --git a/framework/yii/gii/generators/crud/templates/views/update.php b/framework/yii/gii/generators/crud/templates/views/update.php new file mode 100644 index 0000000..cb892c2 --- /dev/null +++ b/framework/yii/gii/generators/crud/templates/views/update.php @@ -0,0 +1,36 @@ +generateUrlParams(); + +echo " + +use yii\helpers\Html; + +/** + * @var yii\base\View $this + * @var modelClass, '\\'); ?> $model + */ + +$this->title = 'Update modelClass)); ?>: ' . $model->getNameAttribute(); ?>; +$this->params['breadcrumbs'][] = array('label' => 'modelClass))); ?>', 'url' => array('index')); +$this->params['breadcrumbs'][] = array('label' => $model->getNameAttribute(); ?>, 'url' => array('view', )); +$this->params['breadcrumbs'][] = 'Update'; +?> +
+ +

echo Html::encode($this->title); ?>

+ + echo $this->render('_form', array( + 'model' => $model, + )); ?> + +
diff --git a/framework/yii/gii/generators/crud/templates/views/view.php b/framework/yii/gii/generators/crud/templates/views/view.php new file mode 100644 index 0000000..d08ec23 --- /dev/null +++ b/framework/yii/gii/generators/crud/templates/views/view.php @@ -0,0 +1,49 @@ +generateUrlParams(); + +echo " + +use yii\helpers\Html; +use yii\widgets\DetailView; + +/** + * @var yii\base\View $this + * @var modelClass, '\\'); ?> $model + */ + +$this->title = $model->getNameAttribute(); ?>; +$this->params['breadcrumbs'][] = array('label' => 'modelClass))); ?>', 'url' => array('index')); +$this->params['breadcrumbs'][] = $this->title; +?> +
+ +

echo Html::encode($this->title); ?>

+ +
+ echo Html::a('Update', array('update', ), array('class' => 'btn btn-danger')); ?> + echo Html::a('Delete', array('delete', ), array('class' => 'btn btn-danger')); ?> +
+ + echo DetailView::widget(array( + 'model' => $model, + 'attributes' => array( +getTableSchema()->columns as $column) { + $format = $generator->generateColumnFormat($column); + echo "\t\t\t'" . $column->name . ($format === 'text' ? '' : ':' . $format) . "',\n"; +} +?> + ), + )); ?> + +
diff --git a/framework/yii/gii/generators/model/Generator.php b/framework/yii/gii/generators/model/Generator.php index 7aa601a..b9c8f23 100644 --- a/framework/yii/gii/generators/model/Generator.php +++ b/framework/yii/gii/generators/model/Generator.php @@ -93,8 +93,11 @@ class Generator extends \yii\gii\Generator 'db' => 'This is the ID of the DB application component.', 'tableName' => 'This is the name of the DB table that the new ActiveRecord class is associated with, e.g. tbl_post. The table name may consist of the DB schema part if needed, e.g. public.tbl_post. - The table name may contain an asterisk at the end to match multiple table names, e.g. tbl_*. - In this case, multiple ActiveRecord classes will be generated, one for each matching table name.', + The table name may contain an asterisk to match multiple table names, e.g. tbl_* + will match tables who name starts with tbl_. In this case, multiple ActiveRecord classes + will be generated, one for each matching table name; and the class names will be generated from + the matching characters. For example, table tbl_post will generate Post + class.', 'modelClass' => 'This is the name of the ActiveRecord class to be generated. The class name should not contain the namespace part as it is specified in "Namespace". You do not need to specify the class name if "Table Name" contains an asterisk at the end, in which case multiple ActiveRecord classes will be generated.', diff --git a/framework/yii/gii/generators/module/templates/controller.php b/framework/yii/gii/generators/module/templates/controller.php index 34dd961..4d3da93 100644 --- a/framework/yii/gii/generators/module/templates/controller.php +++ b/framework/yii/gii/generators/module/templates/controller.php @@ -16,6 +16,6 @@ class DefaultController extends Controller { public function actionIndex() { - $this->render('index'); + return $this->render('index'); } } diff --git a/framework/yii/gii/generators/module/templates/module.php b/framework/yii/gii/generators/module/templates/module.php index 911cb29..40af635 100644 --- a/framework/yii/gii/generators/module/templates/module.php +++ b/framework/yii/gii/generators/module/templates/module.php @@ -16,7 +16,7 @@ echo "; -class extends \yii\web\Module +class extends \yii\base\Module { public $controllerNamespace = 'getControllerNamespace(); ?>'; diff --git a/framework/yii/gii/views/default/view.php b/framework/yii/gii/views/default/view.php index 821f6fc..9754918 100644 --- a/framework/yii/gii/views/default/view.php +++ b/framework/yii/gii/views/default/view.php @@ -28,15 +28,19 @@ foreach ($generator->templates as $name => $path) {

getDescription(); ?>

- array('class' => ActiveField::className()))); ?> + "$id-generator", + 'successCssClass' => '', + 'fieldConfig' => array('class' => ActiveField::className()), + )); ?>
-
+
renderFile($generator->formView(), array( 'generator' => $generator, 'form' => $form, )); ?> field($generator, 'template')->sticky() - ->label(array('label' => 'Code Template')) + ->label('Code Template') ->dropDownList($templates)->hint(' Please select which set of the templates should be used to generated the code. '); ?> diff --git a/framework/yii/grid/DataColumn.php b/framework/yii/grid/DataColumn.php index d31507d..295dece 100644 --- a/framework/yii/grid/DataColumn.php +++ b/framework/yii/grid/DataColumn.php @@ -28,6 +28,14 @@ class DataColumn extends Column */ public $attribute; /** + * @var string label to be displayed in the [[header|header cell]] and also to be used as the sorting + * link label when sorting is enabled for this column. + * If it is not set and the models provided by the GridViews data provider are instances + * of [[yii\db\ActiveRecord]], the label will be determined using [[yii\db\ActiveRecord::getAttributeLabel()]]. + * Otherwise [[yii\helpers\Inflector::camel2words()]] will be used to get a label. + */ + public $label; + /** * @var \Closure an anonymous function that returns the value to be displayed for every data model. * If this is not set, `$model[$attribute]` will be used to obtain the value. */ @@ -46,6 +54,11 @@ class DataColumn extends Column */ public $enableSorting = true; /** + * @var array the HTML attributes for the link tag in the header cell + * generated by [[Sort::link]] when sorting is enabled for this column. + */ + public $sortLinkOptions = array(); + /** * @var string|array|boolean the HTML code representing a filter input (e.g. a text field, a dropdown list) * that is used for this data column. This property is effective only when [[GridView::filterModel]] is set. * @@ -59,25 +72,36 @@ class DataColumn extends Column protected function renderHeaderCellContent() { - if ($this->attribute !== null && $this->header === null) { - $provider = $this->grid->dataProvider; - if ($this->enableSorting && ($sort = $provider->getSort()) !== false && $sort->hasAttribute($this->attribute)) { - return $sort->link($this->attribute); - } - $models = $provider->getModels(); - if (($model = reset($models)) instanceof Model) { + if ($this->header !== null || $this->label === null && $this->attribute === null) { + return parent::renderHeaderCellContent(); + } + + $provider = $this->grid->dataProvider; + + if ($this->label === null) { + if ($provider instanceof ActiveDataProvider && $provider->query instanceof ActiveQuery) { /** @var Model $model */ - return $model->getAttributeLabel($this->attribute); - } elseif ($provider instanceof ActiveDataProvider) { - if ($provider->query instanceof ActiveQuery) { + $model = new $provider->query->modelClass; + $label = $model->getAttributeLabel($this->attribute); + } else { + $models = $provider->getModels(); + if (($model = reset($models)) instanceof Model) { /** @var Model $model */ - $model = new $provider->query->modelClass; - return $model->getAttributeLabel($this->attribute); + $label = $model->getAttributeLabel($this->attribute); + } else { + $label = Inflector::camel2words($this->attribute); } } - return Inflector::camel2words($this->attribute); } else { - return parent::renderHeaderCellContent(); + $label = $this->label; + } + + if ($this->attribute !== null && $this->enableSorting && + ($sort = $provider->getSort()) !== false && $sort->hasAttribute($this->attribute)) { + + return $sort->link($this->attribute, array_merge($this->sortLinkOptions, array('label' => Html::encode($label)))); + } else { + return Html::encode($label); } } diff --git a/framework/yii/grid/GridView.php b/framework/yii/grid/GridView.php index 9490f27..a783a75 100644 --- a/framework/yii/grid/GridView.php +++ b/framework/yii/grid/GridView.php @@ -108,7 +108,7 @@ class GridView extends ListViewBase * 'class' => DataColumn::className(), * 'attribute' => 'name', * 'format' => 'text', - * 'header' => 'Name', + * 'label' => 'Name', * ), * array( * 'class' => CheckboxColumn::className(), @@ -119,21 +119,11 @@ class GridView extends ListViewBase * If a column is of class [[DataColumn]], the "class" element can be omitted. * * As a shortcut format, a string may be used to specify the configuration of a data column - * which only contains "attribute", "format", and/or "header" options: `"attribute:format:header"`. + * which only contains "attribute", "format", and/or "label" options: `"attribute:format:label"`. * For example, the above "name" column can also be specified as: `"name:text:Name"`. - * Both "format" and "header" are optional. They will take default values if absent. + * Both "format" and "label" are optional. They will take default values if absent. */ public $columns = array(); - /** - * @var string the layout that determines how different sections of the list view should be organized. - * The following tokens will be replaced with the corresponding section contents: - * - * - `{summary}`: the summary section. See [[renderSummary()]]. - * - `{items}`: the list items. See [[renderItems()]]. - * - `{sorter}`: the sorter. See [[renderSorter()]]. - * - `{pager}`: the pager. See [[renderPager()]]. - */ - public $layout = "{items}\n{summary}\n{pager}"; public $emptyCell = ' '; /** * @var \yii\base\Model the model that keeps the user-entered filter data. When this property is set, @@ -372,7 +362,7 @@ class GridView extends ListViewBase } /** - * Creates a [[DataColumn]] object based on a string in the format of "attribute:format:header". + * Creates a [[DataColumn]] object based on a string in the format of "attribute:format:label". * @param string $text the column specification string * @return DataColumn the column instance * @throws InvalidConfigException if the column specification is invalid @@ -380,14 +370,14 @@ class GridView extends ListViewBase protected function createDataColumn($text) { if (!preg_match('/^([\w\.]+)(:(\w*))?(:(.*))?$/', $text, $matches)) { - throw new InvalidConfigException('The column must be specified in the format of "attribute", "attribute:format" or "attribute:format:header'); + throw new InvalidConfigException('The column must be specified in the format of "attribute", "attribute:format" or "attribute:format:label'); } return Yii::createObject(array( 'class' => $this->dataColumnClass ?: DataColumn::className(), 'grid' => $this, 'attribute' => $matches[1], 'format' => isset($matches[3]) ? $matches[3] : 'text', - 'header' => isset($matches[5]) ? $matches[5] : null, + 'label' => isset($matches[5]) ? $matches[5] : null, )); } diff --git a/framework/yii/grid/SerialColumn.php b/framework/yii/grid/SerialColumn.php index 3a5e21b..2fdb770 100644 --- a/framework/yii/grid/SerialColumn.php +++ b/framework/yii/grid/SerialColumn.php @@ -9,7 +9,7 @@ namespace yii\grid; /** * SerialColumn displays a column of row numbers (1-based). - * + * * @author Qiang Xue * @since 2.0 */ diff --git a/framework/yii/helpers/ArrayHelperBase.php b/framework/yii/helpers/ArrayHelperBase.php index 2492246..59129de 100644 --- a/framework/yii/helpers/ArrayHelperBase.php +++ b/framework/yii/helpers/ArrayHelperBase.php @@ -143,7 +143,7 @@ class ArrayHelperBase * or an anonymous function returning the value. The anonymous function signature should be: * `function($array, $defaultValue)`. * @param mixed $default the default value to be returned if the specified key does not exist - * @return mixed the value of the + * @return mixed the value of the element if found, default value otherwise */ public static function getValue($array, $key, $default = null) { diff --git a/framework/yii/helpers/ConsoleBase.php b/framework/yii/helpers/ConsoleBase.php index 3593e74..a985291 100644 --- a/framework/yii/helpers/ConsoleBase.php +++ b/framework/yii/helpers/ConsoleBase.php @@ -665,8 +665,8 @@ class ConsoleBase /** * Prints text to STDOUT appended with a carriage return (PHP_EOL). * - * @param string $string - * @return mixed Number of bytes printed or bool false on error + * @param string $string the text to print + * @return integer|boolean number of bytes printed or false on error. */ public static function output($string = null) { @@ -676,8 +676,8 @@ class ConsoleBase /** * Prints text to STDERR appended with a carriage return (PHP_EOL). * - * @param string $string - * @return mixed Number of bytes printed or false on error + * @param string $string the text to print + * @return integer|boolean number of bytes printed or false on error. */ public static function error($string = null) { diff --git a/framework/yii/helpers/FileHelperBase.php b/framework/yii/helpers/FileHelperBase.php index 6358ea1..0e480da 100644 --- a/framework/yii/helpers/FileHelperBase.php +++ b/framework/yii/helpers/FileHelperBase.php @@ -133,7 +133,7 @@ class FileHelperBase * @param string $dst the destination directory * @param array $options options for directory copy. Valid options are: * - * - dirMode: integer, the permission to be set for newly copied directories. Defaults to 0777. + * - dirMode: integer, the permission to be set for newly copied directories. Defaults to 0775. * - fileMode: integer, the permission to be set for newly copied files. Defaults to the current environment setting. * - filter: callback, a PHP callback that is called for each directory or file. * The signature of the callback should be: `function ($path)`, where `$path` refers the full path to be filtered. @@ -162,7 +162,7 @@ class FileHelperBase public static function copyDirectory($src, $dst, $options = array()) { if (!is_dir($dst)) { - static::mkdir($dst, isset($options['dirMode']) ? $options['dirMode'] : 0777, true); + static::createDirectory($dst, isset($options['dirMode']) ? $options['dirMode'] : 0775, true); } $handle = opendir($src); @@ -302,25 +302,25 @@ class FileHelperBase } /** - * Makes directory. + * Creates a new directory. * * This method is similar to the PHP `mkdir()` function except that * it uses `chmod()` to set the permission of the created directory * in order to avoid the impact of the `umask` setting. * - * @param string $path path to be created. - * @param integer $mode the permission to be set for created directory. + * @param string $path path of the directory to be created. + * @param integer $mode the permission to be set for the created directory. * @param boolean $recursive whether to create parent directories if they do not exist. * @return boolean whether the directory is created successfully */ - public static function mkdir($path, $mode = 0777, $recursive = true) + public static function createDirectory($path, $mode = 0775, $recursive = true) { if (is_dir($path)) { return true; } $parentDir = dirname($path); if ($recursive && !is_dir($parentDir)) { - static::mkdir($parentDir, $mode, true); + static::createDirectory($parentDir, $mode, true); } $result = mkdir($path, $mode); chmod($path, $mode); diff --git a/framework/yii/helpers/HtmlBase.php b/framework/yii/helpers/HtmlBase.php index cfff8f5..a5786cb 100644 --- a/framework/yii/helpers/HtmlBase.php +++ b/framework/yii/helpers/HtmlBase.php @@ -238,7 +238,7 @@ class HtmlBase $method = 'post'; } if ($request->enableCsrfValidation) { - $hiddenInputs[] = static::hiddenInput($request->csrfTokenName, $request->getCsrfToken()); + $hiddenInputs[] = static::hiddenInput($request->csrfVar, $request->getCsrfToken()); } } @@ -1049,7 +1049,10 @@ class HtmlBase */ public static function activeFileInput($model, $attribute, $options = array()) { - return static::activeInput('file', $model, $attribute, $options); + // add a hidden field so that if a model only has a file field, we can + // still use isset($_POST[$modelClass]) to detect if the input is submitted + return static::activeHiddenInput($model, $attribute, array('id' => null, 'value' => '')) + . static::activeInput('file', $model, $attribute, $options); } /** diff --git a/framework/yii/helpers/SecurityBase.php b/framework/yii/helpers/SecurityBase.php index 05b2682..5b192de 100644 --- a/framework/yii/helpers/SecurityBase.php +++ b/framework/yii/helpers/SecurityBase.php @@ -133,19 +133,19 @@ class SecurityBase } /** - * Generates a random key. + * Generates a random key. The key may contain uppercase and lowercase latin letters, digits, underscore, dash and dot. * @param integer $length the length of the key that should be generated * @return string the generated random key */ public static function generateRandomKey($length = 32) { if (function_exists('openssl_random_pseudo_bytes')) { - $key = base64_encode(openssl_random_pseudo_bytes($length, $strong)); + $key = strtr(base64_encode(openssl_random_pseudo_bytes($length, $strong)), '+/=', '_-.'); if ($strong) { return substr($key, 0, $length); } } - $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-.'; return substr(str_shuffle(str_repeat($chars, 5)), 0, $length); } @@ -262,7 +262,7 @@ class SecurityBase protected static function generateSalt($cost = 13) { $cost = (int)$cost; - if ($cost < 4 || $cost > 30) { + if ($cost < 4 || $cost > 31) { throw new InvalidParamException('Cost must be between 4 and 31.'); } diff --git a/framework/yii/helpers/StringHelperBase.php b/framework/yii/helpers/StringHelperBase.php index 54dabda..cbb696e 100644 --- a/framework/yii/helpers/StringHelperBase.php +++ b/framework/yii/helpers/StringHelperBase.php @@ -47,8 +47,8 @@ class StringHelperBase /** * Returns the trailing name component of a path. - * This method does the same as the php function `basename()` except that it will - * always use \ and / as directory separators, independent of the operating system. + * This method is similar to the php function `basename()` except that it will + * treat both \ and / as directory separators, independent of the operating system. * This method was mainly created to work on php namespaces. When working with real * file paths, php's `basename()` should work fine for you. * Note: this method is not aware of the actual filesystem, or path components such as "..". @@ -70,6 +70,24 @@ class StringHelperBase } /** + * Returns parent directory's path. + * This method is similar to `dirname()` except that it will treat + * both \ and / as directory separators, independent of the operating system. + * @param string $path A path string. + * @return string the parent directory's path. + * @see http://www.php.net/manual/en/function.basename.php + */ + public static function dirname($path) + { + $pos = mb_strrpos(str_replace('\\', '/', $path), '/'); + if ($pos !== false) { + return mb_substr($path, 0, $pos); + } else { + return $path; + } + } + + /** * Compares two strings or string arrays, and return their differences. * This is a wrapper of the [phpspec/php-diff](https://packagist.org/packages/phpspec/php-diff) package. * @param string|array $lines1 the first string or string array to be compared. If it is a string, diff --git a/framework/yii/log/FileTarget.php b/framework/yii/log/FileTarget.php index 74a33be..970c71b 100644 --- a/framework/yii/log/FileTarget.php +++ b/framework/yii/log/FileTarget.php @@ -9,6 +9,7 @@ namespace yii\log; use Yii; use yii\base\InvalidConfigException; +use yii\helpers\FileHelper; /** * FileTarget records log messages in a file. @@ -37,6 +38,19 @@ class FileTarget extends Target * @var integer number of log files used for rotation. Defaults to 5. */ public $maxLogFiles = 5; + /** + * @var integer the permission to be set for newly created log files. + * This value will be used by PHP chmod() function. No umask will be applied. + * If not set, the permission will be determined by the current environment. + */ + public $fileMode; + /** + * @var integer the permission to be set for newly created directories. + * This value will be used by PHP chmod() function. No umask will be applied. + * Defaults to 0775, meaning the directory is read-writable by owner and group, + * but read-only for other users. + */ + public $dirMode = 0775; /** @@ -53,7 +67,7 @@ class FileTarget extends Target } $logPath = dirname($this->logFile); if (!is_dir($logPath)) { - @mkdir($logPath, 0777, true); + FileHelper::createDirectory($logPath, $this->dirMode, true); } if ($this->maxLogFiles < 1) { $this->maxLogFiles = 1; @@ -87,6 +101,9 @@ class FileTarget extends Target @flock($fp, LOCK_UN); @fclose($fp); } + if ($this->fileMode !== null) { + @chmod($this->logFile, $this->fileMode); + } } /** diff --git a/framework/yii/log/Logger.php b/framework/yii/log/Logger.php index bb7cea5..54f3a49 100644 --- a/framework/yii/log/Logger.php +++ b/framework/yii/log/Logger.php @@ -61,6 +61,13 @@ use yii\base\InvalidConfigException; * When the application ends or [[flushInterval]] is reached, Logger will call [[flush()]] * to send logged messages to different log targets, such as file, email, Web. * + * @property array $dbProfiling The first element indicates the number of SQL statements executed, and the + * second element the total time spent in SQL execution. This property is read-only. + * @property float $elapsedTime The total elapsed time in seconds for current request. This property is + * read-only. + * @property array $profiling The profiling results. Each array element has the following structure: + * `array($token, $category, $time)`. This property is read-only. + * * @author Qiang Xue * @since 2.0 */ diff --git a/framework/yii/log/Target.php b/framework/yii/log/Target.php index 48c340f..0cb72ef 100644 --- a/framework/yii/log/Target.php +++ b/framework/yii/log/Target.php @@ -22,7 +22,9 @@ use yii\base\InvalidConfigException; * satisfying both filter conditions will be handled. Additionally, you * may specify [[except]] to exclude messages of certain categories. * - * @property integer $levels the message levels that this target is interested in. + * @property integer $levels The message levels that this target is interested in. This is a bitmap of level + * values. Defaults to 0, meaning all available levels. Note that the type of this property differs in getter + * and setter. See [[getLevels()]] and [[setLevels()]] for details. * * @author Qiang Xue * @since 2.0 diff --git a/framework/yii/rbac/DbManager.php b/framework/yii/rbac/DbManager.php index 90d301e..46c375f 100644 --- a/framework/yii/rbac/DbManager.php +++ b/framework/yii/rbac/DbManager.php @@ -24,6 +24,8 @@ use yii\base\InvalidParamException; * the three tables used to store the authorization data by setting [[itemTable]], * [[itemChildTable]] and [[assignmentTable]]. * + * @property Item[] $items The authorization items of the specific type. This property is read-only. + * * @author Qiang Xue * @author Alexander Kochetov * @since 2.0 diff --git a/framework/yii/rbac/Item.php b/framework/yii/rbac/Item.php index 2504ad5..f7930c1 100644 --- a/framework/yii/rbac/Item.php +++ b/framework/yii/rbac/Item.php @@ -18,6 +18,9 @@ use yii\base\Object; * A user may be assigned one or several authorization items (called [[Assignment]] assignments). * He can perform an operation only when it is among his assigned items. * + * @property Item[] $children All child items of this item. This property is read-only. + * @property string $name The item name. + * * @author Qiang Xue * @author Alexander Kochetov * @since 2.0 diff --git a/framework/yii/rbac/Manager.php b/framework/yii/rbac/Manager.php index 23ac1a8..3d3aafc 100644 --- a/framework/yii/rbac/Manager.php +++ b/framework/yii/rbac/Manager.php @@ -33,9 +33,9 @@ use yii\base\InvalidParamException; * at appropriate places in the application code to check if the current user * has the needed permission for an operation. * - * @property array $roles Roles (name => Item). - * @property array $tasks Tasks (name => Item). - * @property array $operations Operations (name => Item). + * @property Item[] $operations Operations (name => AuthItem). This property is read-only. + * @property Item[] $roles Roles (name => AuthItem). This property is read-only. + * @property Item[] $tasks Tasks (name => AuthItem). This property is read-only. * * @author Qiang Xue * @author Alexander Kochetov diff --git a/framework/yii/rbac/PhpManager.php b/framework/yii/rbac/PhpManager.php index 3808541..203b17e 100644 --- a/framework/yii/rbac/PhpManager.php +++ b/framework/yii/rbac/PhpManager.php @@ -23,7 +23,7 @@ use yii\base\InvalidParamException; * (for example, the authorization data for a personal blog system). * Use [[DbManager]] for more complex authorization data. * - * @property array $authItems The authorization items of the specific type. + * @property Item[] $items The authorization items of the specific type. This property is read-only. * * @author Qiang Xue * @author Alexander Kochetov diff --git a/framework/yii/redis/Connection.php b/framework/yii/redis/Connection.php new file mode 100644 index 0000000..848b408 --- /dev/null +++ b/framework/yii/redis/Connection.php @@ -0,0 +1,428 @@ + + * @since 2.0 + */ +class Connection extends Component +{ + /** + * @event Event an event that is triggered after a DB connection is established + */ + const EVENT_AFTER_OPEN = 'afterOpen'; + + /** + * @var string the Data Source Name, or DSN, contains the information required to connect to the database. + * DSN format: redis://server:port[/db] + * Where db is a zero based integer which refers to the DB to use. + * If no DB is given, ID 0 is used. + * + * Example: redis://localhost:6379/2 + */ + public $dsn; + /** + * @var string the password for establishing DB connection. Defaults to null meaning no AUTH command is send. + * See http://redis.io/commands/auth + */ + public $password; + /** + * @var float timeout to use for connection to redis. If not set the timeout set in php.ini will be used: ini_get("default_socket_timeout") + */ + public $connectionTimeout = null; + /** + * @var float timeout to use for redis socket when reading and writing data. If not set the php default value will be used. + */ + public $dataTimeout = null; + + /** + * @var array List of available redis commands http://redis.io/commands + */ + public $redisCommands = array( + 'BRPOP', // key [key ...] timeout Remove and get the last element in a list, or block until one is available + 'BRPOPLPUSH', // source destination timeout Pop a value from a list, push it to another list and return it; or block until one is available + 'CLIENT KILL', // ip:port Kill the connection of a client + 'CLIENT LIST', // Get the list of client connections + 'CLIENT GETNAME', // Get the current connection name + 'CLIENT SETNAME', // connection-name Set the current connection name + 'CONFIG GET', // parameter Get the value of a configuration parameter + 'CONFIG SET', // parameter value Set a configuration parameter to the given value + 'CONFIG RESETSTAT', // Reset the stats returned by INFO + 'DBSIZE', // Return the number of keys in the selected database + 'DEBUG OBJECT', // key Get debugging information about a key + 'DEBUG SEGFAULT', // Make the server crash + 'DECR', // key Decrement the integer value of a key by one + 'DECRBY', // key decrement Decrement the integer value of a key by the given number + 'DEL', // key [key ...] Delete a key + 'DISCARD', // Discard all commands issued after MULTI + 'DUMP', // key Return a serialized version of the value stored at the specified key. + 'ECHO', // message Echo the given string + 'EVAL', // script numkeys key [key ...] arg [arg ...] Execute a Lua script server side + 'EVALSHA', // sha1 numkeys key [key ...] arg [arg ...] Execute a Lua script server side + 'EXEC', // Execute all commands issued after MULTI + 'EXISTS', // key Determine if a key exists + 'EXPIRE', // key seconds Set a key's time to live in seconds + 'EXPIREAT', // key timestamp Set the expiration for a key as a UNIX timestamp + 'FLUSHALL', // Remove all keys from all databases + 'FLUSHDB', // Remove all keys from the current database + 'GET', // key Get the value of a key + 'GETBIT', // key offset Returns the bit value at offset in the string value stored at key + 'GETRANGE', // key start end Get a substring of the string stored at a key + 'GETSET', // key value Set the string value of a key and return its old value + 'HDEL', // key field [field ...] Delete one or more hash fields + 'HEXISTS', // key field Determine if a hash field exists + 'HGET', // key field Get the value of a hash field + 'HGETALL', // key Get all the fields and values in a hash + 'HINCRBY', // key field increment Increment the integer value of a hash field by the given number + 'HINCRBYFLOAT', // key field increment Increment the float value of a hash field by the given amount + 'HKEYS', // key Get all the fields in a hash + 'HLEN', // key Get the number of fields in a hash + 'HMGET', // key field [field ...] Get the values of all the given hash fields + 'HMSET', // key field value [field value ...] Set multiple hash fields to multiple values + 'HSET', // key field value Set the string value of a hash field + 'HSETNX', // key field value Set the value of a hash field, only if the field does not exist + 'HVALS', // key Get all the values in a hash + 'INCR', // key Increment the integer value of a key by one + 'INCRBY', // key increment Increment the integer value of a key by the given amount + 'INCRBYFLOAT', // key increment Increment the float value of a key by the given amount + 'INFO', // [section] Get information and statistics about the server + 'KEYS', // pattern Find all keys matching the given pattern + 'LASTSAVE', // Get the UNIX time stamp of the last successful save to disk + 'LINDEX', // key index Get an element from a list by its index + 'LINSERT', // key BEFORE|AFTER pivot value Insert an element before or after another element in a list + 'LLEN', // key Get the length of a list + 'LPOP', // key Remove and get the first element in a list + 'LPUSH', // key value [value ...] Prepend one or multiple values to a list + 'LPUSHX', // key value Prepend a value to a list, only if the list exists + 'LRANGE', // key start stop Get a range of elements from a list + 'LREM', // key count value Remove elements from a list + 'LSET', // key index value Set the value of an element in a list by its index + 'LTRIM', // key start stop Trim a list to the specified range + 'MGET', // key [key ...] Get the values of all the given keys + 'MIGRATE', // host port key destination-db timeout Atomically transfer a key from a Redis instance to another one. + 'MONITOR', // Listen for all requests received by the server in real time + 'MOVE', // key db Move a key to another database + 'MSET', // key value [key value ...] Set multiple keys to multiple values + 'MSETNX', // key value [key value ...] Set multiple keys to multiple values, only if none of the keys exist + 'MULTI', // Mark the start of a transaction block + 'OBJECT', // subcommand [arguments [arguments ...]] Inspect the internals of Redis objects + 'PERSIST', // key Remove the expiration from a key + 'PEXPIRE', // key milliseconds Set a key's time to live in milliseconds + 'PEXPIREAT', // key milliseconds-timestamp Set the expiration for a key as a UNIX timestamp specified in milliseconds + 'PING', // Ping the server + 'PSETEX', // key milliseconds value Set the value and expiration in milliseconds of a key + 'PSUBSCRIBE', // pattern [pattern ...] Listen for messages published to channels matching the given patterns + 'PTTL', // key Get the time to live for a key in milliseconds + 'PUBLISH', // channel message Post a message to a channel + 'PUNSUBSCRIBE', // [pattern [pattern ...]] Stop listening for messages posted to channels matching the given patterns + 'QUIT', // Close the connection + 'RANDOMKEY', // Return a random key from the keyspace + 'RENAME', // key newkey Rename a key + 'RENAMENX', // key newkey Rename a key, only if the new key does not exist + 'RESTORE', // key ttl serialized-value Create a key using the provided serialized value, previously obtained using DUMP. + 'RPOP', // key Remove and get the last element in a list + 'RPOPLPUSH', // source destination Remove the last element in a list, append it to another list and return it + 'RPUSH', // key value [value ...] Append one or multiple values to a list + 'RPUSHX', // key value Append a value to a list, only if the list exists + 'SADD', // key member [member ...] Add one or more members to a set + 'SAVE', // Synchronously save the dataset to disk + 'SCARD', // key Get the number of members in a set + 'SCRIPT EXISTS', // script [script ...] Check existence of scripts in the script cache. + 'SCRIPT FLUSH', // Remove all the scripts from the script cache. + 'SCRIPT KILL', // Kill the script currently in execution. + 'SCRIPT LOAD', // script Load the specified Lua script into the script cache. + 'SDIFF', // key [key ...] Subtract multiple sets + 'SDIFFSTORE', // destination key [key ...] Subtract multiple sets and store the resulting set in a key + 'SELECT', // index Change the selected database for the current connection + 'SET', // key value Set the string value of a key + 'SETBIT', // key offset value Sets or clears the bit at offset in the string value stored at key + 'SETEX', // key seconds value Set the value and expiration of a key + 'SETNX', // key value Set the value of a key, only if the key does not exist + 'SETRANGE', // key offset value Overwrite part of a string at key starting at the specified offset + 'SHUTDOWN', // [NOSAVE] [SAVE] Synchronously save the dataset to disk and then shut down the server + 'SINTER', // key [key ...] Intersect multiple sets + 'SINTERSTORE', // destination key [key ...] Intersect multiple sets and store the resulting set in a key + 'SISMEMBER', // key member Determine if a given value is a member of a set + 'SLAVEOF', // host port Make the server a slave of another instance, or promote it as master + 'SLOWLOG', // subcommand [argument] Manages the Redis slow queries log + 'SMEMBERS', // key Get all the members in a set + 'SMOVE', // source destination member Move a member from one set to another + 'SORT', // key [BY pattern] [LIMIT offset count] [GET pattern [GET pattern ...]] [ASC|DESC] [ALPHA] [STORE destination] Sort the elements in a list, set or sorted set + 'SPOP', // key Remove and return a random member from a set + 'SRANDMEMBER', // key [count] Get one or multiple random members from a set + 'SREM', // key member [member ...] Remove one or more members from a set + 'STRLEN', // key Get the length of the value stored in a key + 'SUBSCRIBE', // channel [channel ...] Listen for messages published to the given channels + 'SUNION', // key [key ...] Add multiple sets + 'SUNIONSTORE', // destination key [key ...] Add multiple sets and store the resulting set in a key + 'SYNC', // Internal command used for replication + 'TIME', // Return the current server time + 'TTL', // key Get the time to live for a key + 'TYPE', // key Determine the type stored at key + 'UNSUBSCRIBE', // [channel [channel ...]] Stop listening for messages posted to the given channels + 'UNWATCH', // Forget about all watched keys + 'WATCH', // key [key ...] Watch the given keys to determine execution of the MULTI/EXEC block + 'ZADD', // key score member [score member ...] Add one or more members to a sorted set, or update its score if it already exists + 'ZCARD', // key Get the number of members in a sorted set + 'ZCOUNT', // key min max Count the members in a sorted set with scores within the given values + 'ZINCRBY', // key increment member Increment the score of a member in a sorted set + 'ZINTERSTORE', // destination numkeys key [key ...] [WEIGHTS weight [weight ...]] [AGGREGATE SUM|MIN|MAX] Intersect multiple sorted sets and store the resulting sorted set in a new key + 'ZRANGE', // key start stop [WITHSCORES] Return a range of members in a sorted set, by index + 'ZRANGEBYSCORE', // key min max [WITHSCORES] [LIMIT offset count] Return a range of members in a sorted set, by score + 'ZRANK', // key member Determine the index of a member in a sorted set + 'ZREM', // key member [member ...] Remove one or more members from a sorted set + 'ZREMRANGEBYRANK', // key start stop Remove all members in a sorted set within the given indexes + 'ZREMRANGEBYSCORE', // key min max Remove all members in a sorted set within the given scores + 'ZREVRANGE', // key start stop [WITHSCORES] Return a range of members in a sorted set, by index, with scores ordered from high to low + 'ZREVRANGEBYSCORE', // key max min [WITHSCORES] [LIMIT offset count] Return a range of members in a sorted set, by score, with scores ordered from high to low + 'ZREVRANK', // key member Determine the index of a member in a sorted set, with scores ordered from high to low + 'ZSCORE', // key member Get the score associated with the given member in a sorted set + 'ZUNIONSTORE', // destination numkeys key [key ...] [WEIGHTS weight [weight ...]] [AGGREGATE SUM|MIN|MAX] Add multiple sorted sets and store the resulting sorted set in a new key + ); + /** + * @var Transaction the currently active transaction + */ + private $_transaction; + /** + * @var resource redis socket connection + */ + private $_socket; + + /** + * Closes the connection when this component is being serialized. + * @return array + */ + public function __sleep() + { + $this->close(); + return array_keys(get_object_vars($this)); + } + + /** + * Returns a value indicating whether the DB connection is established. + * @return boolean whether the DB connection is established + */ + public function getIsActive() + { + return $this->_socket !== null; + } + + /** + * Establishes a DB connection. + * It does nothing if a DB connection has already been established. + * @throws Exception if connection fails + */ + public function open() + { + if ($this->_socket === null) { + if (empty($this->dsn)) { + throw new InvalidConfigException('Connection.dsn cannot be empty.'); + } + $dsn = explode('/', $this->dsn); + $host = $dsn[2]; + if (strpos($host, ':')===false) { + $host .= ':6379'; + } + $db = isset($dsn[3]) ? $dsn[3] : 0; + + \Yii::trace('Opening DB connection: ' . $this->dsn, __CLASS__); + $this->_socket = @stream_socket_client( + $host, + $errorNumber, + $errorDescription, + $this->connectionTimeout ? $this->connectionTimeout : ini_get("default_socket_timeout") + ); + if ($this->_socket) { + if ($this->dataTimeout !== null) { + stream_set_timeout($this->_socket, $timeout=(int)$this->dataTimeout, (int) (($this->dataTimeout - $timeout) * 1000000)); + } + if ($this->password !== null) { + $this->executeCommand('AUTH', array($this->password)); + } + $this->executeCommand('SELECT', array($db)); + $this->initConnection(); + } else { + \Yii::error("Failed to open DB connection ({$this->dsn}): " . $errorNumber . ' - ' . $errorDescription, __CLASS__); + $message = YII_DEBUG ? 'Failed to open DB connection: ' . $errorNumber . ' - ' . $errorDescription : 'Failed to open DB connection.'; + throw new Exception($message, $errorDescription, (int)$errorNumber); + } + } + } + + /** + * Closes the currently active DB connection. + * It does nothing if the connection is already closed. + */ + public function close() + { + if ($this->_socket !== null) { + \Yii::trace('Closing DB connection: ' . $this->dsn, __CLASS__); + $this->executeCommand('QUIT'); + stream_socket_shutdown($this->_socket, STREAM_SHUT_RDWR); + $this->_socket = null; + $this->_transaction = null; + } + } + + /** + * Initializes the DB connection. + * This method is invoked right after the DB connection is established. + * The default implementation triggers an [[EVENT_AFTER_OPEN]] event. + */ + protected function initConnection() + { + $this->trigger(self::EVENT_AFTER_OPEN); + } + + /** + * Returns the currently active transaction. + * @return Transaction the currently active transaction. Null if no active transaction. + */ + public function getTransaction() + { + return $this->_transaction && $this->_transaction->isActive ? $this->_transaction : null; + } + + /** + * Starts a transaction. + * @return Transaction the transaction initiated + */ + public function beginTransaction() + { + $this->open(); + $this->_transaction = new Transaction(array( + 'db' => $this, + )); + $this->_transaction->begin(); + return $this->_transaction; + } + + /** + * Returns the name of the DB driver for the current [[dsn]]. + * @return string name of the DB driver + */ + public function getDriverName() + { + if (($pos = strpos($this->dsn, ':')) !== false) { + return strtolower(substr($this->dsn, 0, $pos)); + } else { + return 'redis'; + } + } + + /** + * + * @param string $name + * @param array $params + * @return mixed + */ + public function __call($name, $params) + { + $redisCommand = strtoupper(Inflector::camel2words($name, false)); + if (in_array($redisCommand, $this->redisCommands)) { + return $this->executeCommand($name, $params); + } else { + return parent::__call($name, $params); + } + } + + /** + * Executes a redis command. + * For a list of available commands and their parameters see http://redis.io/commands. + * + * @param string $name the name of the command + * @param array $params list of parameters for the command + * @return array|bool|null|string Dependend on the executed command this method + * will return different data types: + * + * - `true` for commands that return "status reply". + * - `string` for commands that return "integer reply" + * as the value is in the range of a signed 64 bit integer. + * - `string` or `null` for commands that return "bulk reply". + * - `array` for commands that return "Multi-bulk replies". + * + * See [redis protocol description](http://redis.io/topics/protocol) + * for details on the mentioned reply types. + * @trows Exception for commands that return [error reply](http://redis.io/topics/protocol#error-reply). + */ + public function executeCommand($name, $params=array()) + { + $this->open(); + + array_unshift($params, $name); + $command = '*' . count($params) . "\r\n"; + foreach($params as $arg) { + $command .= '$' . mb_strlen($arg, '8bit') . "\r\n" . $arg . "\r\n"; + } + + \Yii::trace("Executing Redis Command: {$name}", __CLASS__); + fwrite($this->_socket, $command); + + return $this->parseResponse(implode(' ', $params)); + } + + private function parseResponse($command) + { + if(($line = fgets($this->_socket)) === false) { + throw new Exception("Failed to read from socket.\nRedis command was: " . $command); + } + $type = $line[0]; + $line = mb_substr($line, 1, -2, '8bit'); + switch($type) + { + case '+': // Status reply + return true; + case '-': // Error reply + throw new Exception("Redis error: " . $line . "\nRedis command was: " . $command); + case ':': // Integer reply + // no cast to int as it is in the range of a signed 64 bit integer + return $line; + case '$': // Bulk replies + if ($line == '-1') { + return null; + } + $length = $line + 2; + $data = ''; + while ($length > 0) { + if(($block = fread($this->_socket, $line + 2)) === false) { + throw new Exception("Failed to read from socket.\nRedis command was: " . $command); + } + $data .= $block; + $length -= mb_strlen($block, '8bit'); + } + return mb_substr($data, 0, -2, '8bit'); + case '*': // Multi-bulk replies + $count = (int) $line; + $data = array(); + for($i = 0; $i < $count; $i++) { + $data[] = $this->parseResponse($command); + } + return $data; + default: + throw new Exception('Received illegal data from redis: ' . $line . "\nRedis command was: " . $command); + } + } +} diff --git a/framework/yii/redis/Transaction.php b/framework/yii/redis/Transaction.php new file mode 100644 index 0000000..94cff7a --- /dev/null +++ b/framework/yii/redis/Transaction.php @@ -0,0 +1,93 @@ + + * @since 2.0 + */ +class Transaction extends \yii\base\Object +{ + /** + * @var Connection the database connection that this transaction is associated with. + */ + public $db; + /** + * @var boolean whether this transaction is active. Only an active transaction + * can [[commit()]] or [[rollBack()]]. This property is set true when the transaction is started. + */ + private $_active = false; + + /** + * Returns a value indicating whether this transaction is active. + * @return boolean whether this transaction is active. Only an active transaction + * can [[commit()]] or [[rollBack()]]. + */ + public function getIsActive() + { + return $this->_active; + } + + /** + * Begins a transaction. + * @throws InvalidConfigException if [[connection]] is null + */ + public function begin() + { + if (!$this->_active) { + if ($this->db === null) { + throw new InvalidConfigException('Transaction::db must be set.'); + } + \Yii::trace('Starting transaction', __CLASS__); + $this->db->open(); + $this->db->createCommand('MULTI')->execute(); + $this->_active = true; + } + } + + /** + * Commits a transaction. + * @throws Exception if the transaction or the DB connection is not active. + */ + public function commit() + { + if ($this->_active && $this->db && $this->db->isActive) { + \Yii::trace('Committing transaction', __CLASS__); + $this->db->createCommand('EXEC')->execute(); + // TODO handle result of EXEC + $this->_active = false; + } else { + throw new Exception('Failed to commit transaction: transaction was inactive.'); + } + } + + /** + * Rolls back a transaction. + * @throws Exception if the transaction or the DB connection is not active. + */ + public function rollback() + { + if ($this->_active && $this->db && $this->db->isActive) { + \Yii::trace('Rolling back transaction', __CLASS__); + $this->db->pdo->commit(); + $this->_active = false; + } else { + throw new Exception('Failed to roll back transaction: transaction was inactive.'); + } + } +} diff --git a/framework/yii/validators/ExistValidator.php b/framework/yii/validators/ExistValidator.php index 9c74890..8cbce5f 100644 --- a/framework/yii/validators/ExistValidator.php +++ b/framework/yii/validators/ExistValidator.php @@ -66,7 +66,7 @@ class ExistValidator extends Validator } /** @var $className \yii\db\ActiveRecord */ - $className = $this->className === null ? get_class($object) : Yii::import($this->className); + $className = $this->className === null ? get_class($object) : $this->className; $attributeName = $this->attributeName === null ? $attribute : $this->attributeName; $query = $className::find(); $query->where(array($attributeName => $value)); diff --git a/framework/yii/validators/FileValidator.php b/framework/yii/validators/FileValidator.php index 8a3ab9e..e2880af 100644 --- a/framework/yii/validators/FileValidator.php +++ b/framework/yii/validators/FileValidator.php @@ -13,13 +13,15 @@ use yii\web\UploadedFile; /** * FileValidator verifies if an attribute is receiving a valid uploaded file. * + * @property integer $sizeLimit The size limit for uploaded files. This property is read-only. + * * @author Qiang Xue * @since 2.0 */ class FileValidator extends Validator { /** - * @var mixed a list of file name extensions that are allowed to be uploaded. + * @var array|string a list of file name extensions that are allowed to be uploaded. * This can be either an array or a string consisting of file extension names * separated by space or comma (e.g. "gif, jpg"). * Extension names are case-insensitive. Defaults to null, meaning all file name @@ -133,7 +135,7 @@ class FileValidator extends Validator return; } foreach ($files as $i => $file) { - if (!$file instanceof UploadedFile || $file->getError() == UPLOAD_ERR_NO_FILE) { + if (!$file instanceof UploadedFile || $file->error == UPLOAD_ERR_NO_FILE) { unset($files[$i]); } } @@ -150,7 +152,7 @@ class FileValidator extends Validator } } else { $file = $object->$attribute; - if ($file instanceof UploadedFile && $file->getError() != UPLOAD_ERR_NO_FILE) { + if ($file instanceof UploadedFile && $file->error != UPLOAD_ERR_NO_FILE) { $this->validateFile($object, $attribute, $file); } else { $this->addError($object, $attribute, $this->uploadRequired); @@ -166,37 +168,37 @@ class FileValidator extends Validator */ protected function validateFile($object, $attribute, $file) { - switch ($file->getError()) { + switch ($file->error) { case UPLOAD_ERR_OK: - if ($this->maxSize !== null && $file->getSize() > $this->maxSize) { - $this->addError($object, $attribute, $this->tooBig, array('{file}' => $file->getName(), '{limit}' => $this->getSizeLimit())); + if ($this->maxSize !== null && $file->size > $this->maxSize) { + $this->addError($object, $attribute, $this->tooBig, array('{file}' => $file->name, '{limit}' => $this->getSizeLimit())); } - if ($this->minSize !== null && $file->getSize() < $this->minSize) { - $this->addError($object, $attribute, $this->tooSmall, array('{file}' => $file->getName(), '{limit}' => $this->minSize)); + if ($this->minSize !== null && $file->size < $this->minSize) { + $this->addError($object, $attribute, $this->tooSmall, array('{file}' => $file->name, '{limit}' => $this->minSize)); } - if (!empty($this->types) && !in_array(strtolower(pathinfo($file->getName(), PATHINFO_EXTENSION)), $this->types, true)) { - $this->addError($object, $attribute, $this->wrongType, array('{file}' => $file->getName(), '{extensions}' => implode(', ', $this->types))); + if (!empty($this->types) && !in_array(strtolower(pathinfo($file->name, PATHINFO_EXTENSION)), $this->types, true)) { + $this->addError($object, $attribute, $this->wrongType, array('{file}' => $file->name, '{extensions}' => implode(', ', $this->types))); } break; case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: - $this->addError($object, $attribute, $this->tooBig, array('{file}' => $file->getName(), '{limit}' => $this->getSizeLimit())); + $this->addError($object, $attribute, $this->tooBig, array('{file}' => $file->name, '{limit}' => $this->getSizeLimit())); break; case UPLOAD_ERR_PARTIAL: $this->addError($object, $attribute, $this->message); - Yii::warning('File was only partially uploaded: ' . $file->getName(), __METHOD__); + Yii::warning('File was only partially uploaded: ' . $file->name, __METHOD__); break; case UPLOAD_ERR_NO_TMP_DIR: $this->addError($object, $attribute, $this->message); - Yii::warning('Missing the temporary folder to store the uploaded file: ' . $file->getName(), __METHOD__); + Yii::warning('Missing the temporary folder to store the uploaded file: ' . $file->name, __METHOD__); break; case UPLOAD_ERR_CANT_WRITE: $this->addError($object, $attribute, $this->message); - Yii::warning('Failed to write the uploaded file to disk: ' . $file->getName(), __METHOD__); + Yii::warning('Failed to write the uploaded file to disk: ' . $file->name, __METHOD__); break; case UPLOAD_ERR_EXTENSION: $this->addError($object, $attribute, $this->message); - Yii::warning('File upload was stopped by some PHP extension: ' . $file->getName(), __METHOD__); + Yii::warning('File upload was stopped by some PHP extension: ' . $file->name, __METHOD__); break; default: break; diff --git a/framework/yii/validators/RegularExpressionValidator.php b/framework/yii/validators/RegularExpressionValidator.php index 4ae2099..df57e7d 100644 --- a/framework/yii/validators/RegularExpressionValidator.php +++ b/framework/yii/validators/RegularExpressionValidator.php @@ -30,7 +30,6 @@ class RegularExpressionValidator extends Validator /** * @var boolean whether to invert the validation logic. Defaults to false. If set to true, * the regular expression defined via [[pattern]] should NOT match the attribute value. - * @throws InvalidConfigException if the "pattern" is not a valid regular expression **/ public $not = false; @@ -82,7 +81,6 @@ class RegularExpressionValidator extends Validator * @param \yii\base\View $view the view object that is going to be used to render views or view files * containing a model form with this validator applied. * @return string the client-side validation script. - * @throws InvalidConfigException if the "pattern" is not a valid regular expression */ public function clientValidateAttribute($object, $attribute, $view) { diff --git a/framework/yii/validators/StringValidator.php b/framework/yii/validators/StringValidator.php index 2cbab6c..946ca6e 100644 --- a/framework/yii/validators/StringValidator.php +++ b/framework/yii/validators/StringValidator.php @@ -52,7 +52,7 @@ class StringValidator extends Validator */ public $tooLong; /** - * @var string user-defined error message used when the length of the value is not equal to [[is]]. + * @var string user-defined error message used when the length of the value is not equal to [[length]]. */ public $notEqual; /** diff --git a/framework/yii/validators/UniqueValidator.php b/framework/yii/validators/UniqueValidator.php index b650693..c3876e8 100644 --- a/framework/yii/validators/UniqueValidator.php +++ b/framework/yii/validators/UniqueValidator.php @@ -61,7 +61,7 @@ class UniqueValidator extends Validator } /** @var $className \yii\db\ActiveRecord */ - $className = $this->className === null ? get_class($object) : Yii::import($this->className); + $className = $this->className === null ? get_class($object) : $this->className; $attributeName = $this->attributeName === null ? $attribute : $this->attributeName; $table = $className::getTableSchema(); diff --git a/framework/yii/web/AccessControl.php b/framework/yii/web/AccessControl.php index 35d6cae..7f791b8 100644 --- a/framework/yii/web/AccessControl.php +++ b/framework/yii/web/AccessControl.php @@ -31,15 +31,17 @@ use yii\base\ActionFilter; * 'class' => \yii\web\AccessControl::className(), * 'only' => array('create', 'update'), * 'rules' => array( + * // deny all POST requests + * array( + * 'allow' => false, + * 'verbs' => array('POST') + * ), * // allow authenticated users * array( * 'allow' => true, * 'roles' => array('@'), * ), - * // deny all - * array( - * 'allow' => false, - * ), + * // everything else is denied * ), * ), * ); diff --git a/framework/yii/web/AccessRule.php b/framework/yii/web/AccessRule.php index 0de791c..7aeaac1 100644 --- a/framework/yii/web/AccessRule.php +++ b/framework/yii/web/AccessRule.php @@ -11,6 +11,7 @@ use yii\base\Component; use yii\base\Action; /** + * This class represents an access rule defined by the [[AccessControl]] action filter * * @author Qiang Xue * @since 2.0 diff --git a/framework/yii/web/Application.php b/framework/yii/web/Application.php index 249b0b4..5fd2310 100644 --- a/framework/yii/web/Application.php +++ b/framework/yii/web/Application.php @@ -11,7 +11,14 @@ use Yii; use yii\base\InvalidRouteException; /** - * Application is the base class for all application classes. + * Application is the base class for all web application classes. + * + * @property AssetManager $assetManager The asset manager component. This property is read-only. + * @property string $homeUrl The homepage URL. + * @property Request $request The request component. This property is read-only. + * @property Response $response The response component. This property is read-only. + * @property Session $session The session component. This property is read-only. + * @property User $user The user component. This property is read-only. * * @author Qiang Xue * @since 2.0 diff --git a/framework/yii/web/AssetManager.php b/framework/yii/web/AssetManager.php index 702fd30..c6f7fea 100644 --- a/framework/yii/web/AssetManager.php +++ b/framework/yii/web/AssetManager.php @@ -16,6 +16,9 @@ use yii\helpers\FileHelper; /** * AssetManager manages asset bundles and asset publishing. * + * @property IAssetConverter $converter The asset converter. Note that the type of this property differs in + * getter and setter. See [[getConverter()]] and [[setConverter()]] for details. + * * @author Qiang Xue * @since 2.0 */ @@ -55,16 +58,17 @@ class AssetManager extends Component public $linkAssets = false; /** * @var integer the permission to be set for newly published asset files. - * This value will be used by PHP chmod() function. + * This value will be used by PHP chmod() function. No umask will be applied. * If not set, the permission will be determined by the current environment. */ public $fileMode; /** * @var integer the permission to be set for newly generated asset directories. - * This value will be used by PHP chmod() function. - * Defaults to 0777, meaning the directory can be read, written and executed by all users. + * This value will be used by PHP chmod() function. No umask will be applied. + * Defaults to 0775, meaning the directory is read-writable by owner and group, + * but read-only for other users. */ - public $dirMode = 0777; + public $dirMode = 0775; /** * Initializes the component. @@ -202,7 +206,7 @@ class AssetManager extends Component $dstFile = $dstDir . DIRECTORY_SEPARATOR . $fileName; if (!is_dir($dstDir)) { - mkdir($dstDir, $this->dirMode, true); + FileHelper::createDirectory($dstDir, $this->dirMode, true); } if ($this->linkAssets) { diff --git a/framework/yii/web/CacheSession.php b/framework/yii/web/CacheSession.php index 79acd74..bb387e1 100644 --- a/framework/yii/web/CacheSession.php +++ b/framework/yii/web/CacheSession.php @@ -21,6 +21,8 @@ use yii\base\InvalidConfigException; * may be swapped out and get lost. Therefore, you must make sure the cache used by this component * is NOT volatile. If you want to use database as storage medium, use [[DbSession]] is a better choice. * + * @property boolean $useCustomStorage Whether to use custom storage. This property is read-only. + * * @author Qiang Xue * @since 2.0 */ diff --git a/framework/yii/web/Controller.php b/framework/yii/web/Controller.php index b094981..adb1b4d 100644 --- a/framework/yii/web/Controller.php +++ b/framework/yii/web/Controller.php @@ -12,8 +12,7 @@ use yii\base\InlineAction; use yii\helpers\Html; /** - * Controller is the base class of Web controllers. - * + * Controller is the base class of web controllers. * * @author Qiang Xue * @since 2.0 diff --git a/framework/yii/web/CookieCollection.php b/framework/yii/web/CookieCollection.php index 3e22092..6940493 100644 --- a/framework/yii/web/CookieCollection.php +++ b/framework/yii/web/CookieCollection.php @@ -15,7 +15,9 @@ use yii\base\Object; /** * CookieCollection maintains the cookies available in the current request. * - * @property integer $count the number of cookies in the collection + * @property integer $count The number of cookies in the collection. This property is read-only. + * @property ArrayIterator $iterator An iterator for traversing the cookies in the collection. This property + * is read-only. * * @author Qiang Xue * @since 2.0 diff --git a/framework/yii/web/DbSession.php b/framework/yii/web/DbSession.php index 30f5ed0..c508bb8 100644 --- a/framework/yii/web/DbSession.php +++ b/framework/yii/web/DbSession.php @@ -17,9 +17,9 @@ use yii\base\InvalidConfigException; * * By default, DbSession stores session data in a DB table named 'tbl_session'. This table * must be pre-created. The table name can be changed by setting [[sessionTable]]. - * + * * The following example shows how you can configure the application to use DbSession: - * + * * ~~~ * 'session' => array( * 'class' => 'yii\web\DbSession', @@ -28,6 +28,8 @@ use yii\base\InvalidConfigException; * ) * ~~~ * + * @property boolean $useCustomStorage Whether to use custom storage. This property is read-only. + * * @author Qiang Xue * @since 2.0 */ diff --git a/framework/yii/web/HeaderCollection.php b/framework/yii/web/HeaderCollection.php index 872a997..609058b 100644 --- a/framework/yii/web/HeaderCollection.php +++ b/framework/yii/web/HeaderCollection.php @@ -14,6 +14,10 @@ use ArrayIterator; /** * HeaderCollection is used by [[Response]] to maintain the currently registered HTTP headers. * + * @property integer $count The number of headers in the collection. This property is read-only. + * @property ArrayIterator $iterator An iterator for traversing the headers in the collection. This property + * is read-only. + * * @author Qiang Xue * @since 2.0 */ diff --git a/framework/yii/web/HttpCache.php b/framework/yii/web/HttpCache.php index cc9e6ed..d2f3923 100644 --- a/framework/yii/web/HttpCache.php +++ b/framework/yii/web/HttpCache.php @@ -12,6 +12,8 @@ use yii\base\ActionFilter; use yii\base\Action; /** + * The HttpCache provides functionality for caching via HTTP Last-Modified and Etag headers + * * @author Da:Sourcerer * @author Qiang Xue * @since 2.0 diff --git a/framework/yii/web/JqueryAsset.php b/framework/yii/web/JqueryAsset.php index 4585acd..9991eb4 100644 --- a/framework/yii/web/JqueryAsset.php +++ b/framework/yii/web/JqueryAsset.php @@ -8,6 +8,8 @@ namespace yii\web; /** + * This asset bundle provides the [jquery javascript library](http://jquery.com/) + * * @author Qiang Xue * @since 2.0 */ diff --git a/framework/yii/web/JsExpression.php b/framework/yii/web/JsExpression.php index 027c065..7daac08 100644 --- a/framework/yii/web/JsExpression.php +++ b/framework/yii/web/JsExpression.php @@ -11,8 +11,10 @@ use yii\base\Object; /** * JsExpression marks a string as a JavaScript expression. - * When using [[Json::encode()]] to encode a value, JsonExpression objects + * + * When using [[yii\helpers\Json::encode()]] to encode a value, JsonExpression objects * will be specially handled and encoded as a JavaScript expression instead of a string. + * * @author Qiang Xue * @since 2.0 */ diff --git a/framework/yii/web/PageCache.php b/framework/yii/web/PageCache.php index d28203e..9bc8981 100644 --- a/framework/yii/web/PageCache.php +++ b/framework/yii/web/PageCache.php @@ -14,6 +14,8 @@ use yii\base\View; use yii\caching\Dependency; /** + * The PageCache provides functionality for whole page caching + * * @author Qiang Xue * @since 2.0 */ diff --git a/framework/yii/web/Request.php b/framework/yii/web/Request.php index c2f5c4b..9e625f7 100644 --- a/framework/yii/web/Request.php +++ b/framework/yii/web/Request.php @@ -12,27 +12,89 @@ use yii\base\InvalidConfigException; use yii\helpers\Security; /** + * The web Request class represents an HTTP request + * + * It encapsulates the $_SERVER variable and resolves its inconsistency among different Web servers. + * Also it provides an interface to retrieve request parameters from $_POST, $_GET, $_COOKIES and REST + * parameters sent via other HTTP methods like PUT or DELETE. + * + * @property string $absoluteUrl The currently requested absolute URL. This property is read-only. + * @property string $acceptTypes User browser accept types, null if not present. This property is read-only. + * @property array $acceptedContentTypes The content types ordered by the preference level. The first element + * represents the most preferred content type. + * @property array $acceptedLanguages The languages ordered by the preference level. The first element + * represents the most preferred language. + * @property string $baseUrl The relative URL for the application. + * @property string $cookieValidationKey The secret key used for cookie validation. If it was not set + * previously, a random key will be generated and used. + * @property CookieCollection $cookies The cookie collection. This property is read-only. + * @property string $csrfToken The random token for CSRF validation. This property is read-only. + * @property string $hostInfo Schema and hostname part (with port number if needed) of the request URL (e.g. + * `http://www.yiiframework.com`). + * @property boolean $isAjax Whether this is an AJAX (XMLHttpRequest) request. This property is read-only. + * @property boolean $isDelete Whether this is a DELETE request. This property is read-only. + * @property boolean $isFlash Whether this is an Adobe Flash or Adobe Flex request. This property is + * read-only. + * @property boolean $isGet Whether this is a GET request. This property is read-only. + * @property boolean $isHead Whether this is a HEAD request. This property is read-only. + * @property boolean $isOptions Whether this is a OPTIONS request. This property is read-only. + * @property boolean $isPatch Whether this is a PATCH request. This property is read-only. + * @property boolean $isPost Whether this is a POST request. This property is read-only. + * @property boolean $isPut Whether this is a PUT request. This property is read-only. + * @property boolean $isSecureConnection If the request is sent via secure channel (https). This property is + * read-only. + * @property string $method Request method, such as GET, POST, HEAD, PUT, PATCH, DELETE. The value returned is + * turned into upper case. This property is read-only. + * @property string $pathInfo Part of the request URL that is after the entry script and before the question + * mark. Note, the returned path info is already URL-decoded. + * @property integer $port Port number for insecure requests. + * @property string $preferredLanguage The language that the application should use. Null is returned if both + * [[getAcceptedLanguages()]] and `$languages` are empty. This property is read-only. + * @property string $queryString Part of the request URL that is after the question mark. This property is + * read-only. + * @property string $rawBody The request body. This property is read-only. + * @property string $referrer URL referrer, null if not present. This property is read-only. + * @property array $restParams The RESTful request parameters. + * @property string $scriptFile The entry script file path. + * @property string $scriptUrl The relative URL of the entry script. + * @property integer $securePort Port number for secure requests. + * @property string $serverName Server name. This property is read-only. + * @property integer $serverPort Server port number. This property is read-only. + * @property string $url The currently requested relative URL. Note that the URI returned is URL-encoded. + * @property string $userAgent User agent, null if not present. This property is read-only. + * @property string $userHost User host name, null if cannot be determined. This property is read-only. + * @property string $userIP User IP address. This property is read-only. + * * @author Qiang Xue * @since 2.0 */ class Request extends \yii\base\Request { /** + * The name of the HTTP header for sending CSRF token. + */ + const CSRF_HEADER = 'X-CSRF-TOKEN'; + + /** * @var boolean whether to enable CSRF (Cross-Site Request Forgery) validation. Defaults to false. - * By setting this property to true, forms submitted to an Yii Web application must be originated + * When CSRF validation is enabled, forms submitted to an Yii Web application must be originated * from the same application. If not, a 400 HTTP exception will be raised. * * Note, this feature requires that the user client accepts cookie. Also, to use this feature, - * forms submitted via POST method must contain a hidden input whose name is specified by [[csrfTokenName]]. + * forms submitted via POST method must contain a hidden input whose name is specified by [[csrfVar]]. * You may use [[\yii\web\Html::beginForm()]] to generate his hidden input. + * + * In JavaScript, you may get the values of [[csrfVar]] and [[csrfToken]] via `yii.getCsrfVar()` and + * `yii.getCsrfToken()`, respectively. The [[\yii\web\YiiAsset]] asset must be registered. + * * @see http://en.wikipedia.org/wiki/Cross-site_request_forgery */ public $enableCsrfValidation = false; /** - * @var string the name of the token used to prevent CSRF. Defaults to 'YII_CSRF_TOKEN'. - * This property is effectively only when {@link enableCsrfValidation} is true. + * @var string the name of the token used to prevent CSRF. Defaults to '_csrf'. + * This property is used only when [[enableCsrfValidation]] is true. */ - public $csrfTokenName = '_csrf'; + public $csrfVar = '_csrf'; /** * @var array the configuration of the CSRF cookie. This property is used only when [[enableCsrfValidation]] is true. * @see Cookie @@ -87,6 +149,33 @@ class Request extends \yii\base\Request } /** + * Returns whether this is a GET request. + * @return boolean whether this is a GET request. + */ + public function getIsGet() + { + return $this->getMethod() === 'GET'; + } + + /** + * Returns whether this is an OPTIONS request. + * @return boolean whether this is a OPTIONS request. + */ + public function getIsOptions() + { + return $this->getMethod() === 'OPTIONS'; + } + + /** + * Returns whether this is a HEAD request. + * @return boolean whether this is a HEAD request. + */ + public function getIsHead() + { + return $this->getMethod() === 'HEAD'; + } + + /** * Returns whether this is a POST request. * @return boolean whether this is a POST request. */ @@ -898,7 +987,7 @@ class Request extends \yii\base\Request public function getCsrfToken() { if ($this->_csrfCookie === null) { - $this->_csrfCookie = $this->getCookies()->get($this->csrfTokenName); + $this->_csrfCookie = $this->getCookies()->get($this->csrfVar); if ($this->_csrfCookie === null) { $this->_csrfCookie = $this->createCsrfCookie(); Yii::$app->getResponse()->getCookies()->add($this->_csrfCookie); @@ -909,6 +998,14 @@ class Request extends \yii\base\Request } /** + * @return string the CSRF token sent via [[CSRF_HEADER]] by browser. Null is returned if no such header is sent. + */ + public function getCsrfTokenFromHeader() + { + return isset($_SERVER[self::CSRF_HEADER]) ? $_SERVER[self::CSRF_HEADER] : null; + } + + /** * Creates a cookie with a randomly generated CSRF token. * Initial values specified in [[csrfCookie]] will be applied to the generated cookie. * @return Cookie the generated cookie @@ -917,7 +1014,7 @@ class Request extends \yii\base\Request protected function createCsrfCookie() { $options = $this->csrfCookie; - $options['name'] = $this->csrfTokenName; + $options['name'] = $this->csrfVar; $options['value'] = sha1(uniqid(mt_rand(), true)); return new Cookie($options); } @@ -935,22 +1032,23 @@ class Request extends \yii\base\Request } $method = $this->getMethod(); if ($method === 'POST' || $method === 'PUT' || $method === 'PATCH' || $method === 'DELETE') { - $cookies = $this->getCookies(); + $trueToken = $this->getCookies()->getValue($this->csrfVar); switch ($method) { case 'POST': - $token = $this->getPost($this->csrfTokenName); + $token = $this->getPost($this->csrfVar); break; case 'PUT': - $token = $this->getPut($this->csrfTokenName); + $token = $this->getPut($this->csrfVar); break; case 'PATCH': - $token = $this->getPatch($this->csrfTokenName); + $token = $this->getPatch($this->csrfVar); break; case 'DELETE': - $token = $this->getDelete($this->csrfTokenName); + $token = $this->getDelete($this->csrfVar); } - if (empty($token) || $cookies->getValue($this->csrfTokenName) !== $token) { + $valid = !empty($token) && $token === $trueToken || $this->getCsrfTokenFromHeader() === $trueToken; + if (!$valid) { throw new HttpException(400, Yii::t('yii', 'Unable to verify your data submission.')); } } diff --git a/framework/yii/web/Response.php b/framework/yii/web/Response.php index 19a9ea2..cfbc537 100644 --- a/framework/yii/web/Response.php +++ b/framework/yii/web/Response.php @@ -17,6 +17,29 @@ use yii\helpers\Security; use yii\helpers\StringHelper; /** + * The web Response class represents an HTTP response + * + * It holds the [[headers]], [[cookies]] and [[content]] that is to be sent to the client. + * It also controls the HTTP [[statusCode|status code]]. + * + * @property CookieCollection $cookies The cookie collection. This property is read-only. + * @property HeaderCollection $headers The header collection. This property is read-only. + * @property boolean $isClientError Whether this response indicates a client error. This property is + * read-only. + * @property boolean $isEmpty Whether this response is empty. This property is read-only. + * @property boolean $isForbidden Whether this response indicates the current request is forbidden. This + * property is read-only. + * @property boolean $isInformational Whether this response is informational. This property is read-only. + * @property boolean $isInvalid Whether this response has a valid [[statusCode]]. This property is read-only. + * @property boolean $isNotFound Whether this response indicates the currently requested resource is not + * found. This property is read-only. + * @property boolean $isOk Whether this response is OK. This property is read-only. + * @property boolean $isRedirection Whether this response is a redirection. This property is read-only. + * @property boolean $isServerError Whether this response indicates a server error. This property is + * read-only. + * @property boolean $isSuccessful Whether this response is successful. This property is read-only. + * @property integer $statusCode The HTTP status code to send with the response. + * * @author Qiang Xue * @author Carsten Brandt * @since 2.0 diff --git a/framework/yii/web/Session.php b/framework/yii/web/Session.php index cbed8fc..fc9fe16 100644 --- a/framework/yii/web/Session.php +++ b/framework/yii/web/Session.php @@ -45,18 +45,27 @@ use yii\base\InvalidParamException; * useful for displaying confirmation messages. To use flash messages, simply * call methods such as [[setFlash()]], [[getFlash()]]. * + * @property array $allFlashes Flash messages (key => message). This property is read-only. + * @property array $cookieParams The session cookie parameters. + * @property integer $count The number of session variables. This property is read-only. + * @property string $flash The key identifying the flash message. Note that flash messages and normal session + * variables share the same name space. If you have a normal session variable using the same name, its value will + * be overwritten by this method. This property is write-only. + * @property float $gCProbability The probability (percentage) that the GC (garbage collection) process is + * started on every session initialization, defaults to 1 meaning 1% chance. * @property string $id The current session ID. + * @property boolean $isActive Whether the session has started. This property is read-only. + * @property SessionIterator $iterator An iterator for traversing the session variables. This property is + * read-only. * @property string $name The current session name. - * @property boolean $isActive Whether the session has started - * @property string $savePath The current session save path, defaults to {@link http://php.net/manual/en/session.configuration.php#ini.session.save-path}. - * @property array $cookieParams The session cookie parameters. - * @property boolean $useCookies Whether cookies should be used to store session IDs. - * @property float $gCProbability The probability (percentage) that the gc (garbage collection) process is started on every session initialization, defaults to 1 meaning 1% chance. - * @property boolean $useTransparentSessionID Whether transparent sid support is enabled or not, defaults to false. - * @property integer $timeout The number of seconds after which data will be seen as 'garbage' and cleaned up, defaults to 1440 seconds. - * @property SessionIterator $iterator An iterator for traversing the session variables. - * @property integer $count The number of session variables. - * @property array $allFlashes The list of all flash messages. + * @property string $savePath The current session save path, defaults to '/tmp'. + * @property integer $timeout The number of seconds after which data will be seen as 'garbage' and cleaned up. + * The default value is 1440 seconds (or the value of "session.gc_maxlifetime" set in php.ini). + * @property boolean|null $useCookies The value indicating whether cookies should be used to store session + * IDs. + * @property boolean $useCustomStorage Whether to use custom storage. This property is read-only. + * @property boolean $useTransparentSessionID Whether transparent sid support is enabled or not, defaults to + * false. * * @author Qiang Xue * @since 2.0 diff --git a/framework/yii/web/UploadedFile.php b/framework/yii/web/UploadedFile.php index ee3b1f0..c4e2f0f 100644 --- a/framework/yii/web/UploadedFile.php +++ b/framework/yii/web/UploadedFile.php @@ -7,41 +7,53 @@ namespace yii\web; +use yii\base\Object; use yii\helpers\Html; /** + * UploadedFile represents the information for an uploaded file. + * + * You can call [[getInstance()]] to retrieve the instance of an uploaded file, + * and then use [[saveAs()]] to save it on the server. + * You may also query other information about the file, including [[name]], + * [[tempName]], [[type]], [[size]] and [[error]]. + * + * @property boolean $hasError Whether there is an error with the uploaded file. Check [[error]] for detailed + * error code information. This property is read-only. + * * @author Qiang Xue * @since 2.0 */ -class UploadedFile extends \yii\base\Object +class UploadedFile extends Object { private static $_files; - private $_name; - private $_tempName; - private $_type; - private $_size; - private $_error; - /** - * Constructor. - * Instead of using the constructor to create a new instance, - * you should normally call [[getInstance()]] or [[getInstances()]] - * to obtain new instances. - * @param string $name the original name of the file being uploaded - * @param string $tempName the path of the uploaded file on the server. - * @param string $type the MIME-type of the uploaded file (such as "image/gif"). - * @param integer $size the actual size of the uploaded file in bytes - * @param integer $error the error code + * @var string the original name of the file being uploaded */ - public function __construct($name, $tempName, $type, $size, $error) - { - $this->_name = $name; - $this->_tempName = $tempName; - $this->_type = $type; - $this->_size = $size; - $this->_error = $error; - } + public $name; + /** + * @var string the path of the uploaded file on the server. + * Note, this is a temporary file which will be automatically deleted by PHP + * after the current request is processed. + */ + public $tempName; + /** + * @var string the MIME-type of the uploaded file (such as "image/gif"). + * Since this MIME type is not checked on the server side, do not take this value for granted. + * Instead, use [[FileHelper::getMimeType()]] to determine the exact MIME type. + */ + public $type; + /** + * @var integer the actual size of the uploaded file in bytes + */ + public $size; + /** + * @var integer an error code describing the status of this file uploading. + * @see http://www.php.net/manual/en/features.file-upload.errors.php + */ + public $error; + /** * String output. @@ -51,7 +63,7 @@ class UploadedFile extends \yii\base\Object */ public function __toString() { - return $this->_name; + return $this->name; } /** @@ -142,69 +154,23 @@ class UploadedFile extends \yii\base\Object */ public function saveAs($file, $deleteTempFile = true) { - if ($this->_error == UPLOAD_ERR_OK) { + if ($this->error == UPLOAD_ERR_OK) { if ($deleteTempFile) { - return move_uploaded_file($this->_tempName, $file); - } elseif (is_uploaded_file($this->_tempName)) { - return copy($this->_tempName, $file); + return move_uploaded_file($this->tempName, $file); + } elseif (is_uploaded_file($this->tempName)) { + return copy($this->tempName, $file); } } return false; } /** - * @return string the original name of the file being uploaded - */ - public function getName() - { - return $this->_name; - } - - /** - * @return string the path of the uploaded file on the server. - * Note, this is a temporary file which will be automatically deleted by PHP - * after the current request is processed. - */ - public function getTempName() - { - return $this->_tempName; - } - - /** - * @return string the MIME-type of the uploaded file (such as "image/gif"). - * Since this MIME type is not checked on the server side, do not take this value for granted. - * Instead, use [[FileHelper::getMimeType()]] to determine the exact MIME type. - */ - public function getType() - { - return $this->_type; - } - - /** - * @return integer the actual size of the uploaded file in bytes - */ - public function getSize() - { - return $this->_size; - } - - /** - * Returns an error code describing the status of this file uploading. - * @return integer the error code - * @see http://www.php.net/manual/en/features.file-upload.errors.php - */ - public function getError() - { - return $this->_error; - } - - /** * @return boolean whether there is an error with the uploaded file. * Check [[error]] for detailed error code information. */ public function getHasError() { - return $this->_error != UPLOAD_ERR_OK; + return $this->error != UPLOAD_ERR_OK; } /** @@ -240,7 +206,13 @@ class UploadedFile extends \yii\base\Object self::loadFilesRecursive($key . '[' . $i . ']', $name, $tempNames[$i], $types[$i], $sizes[$i], $errors[$i]); } } else { - self::$_files[$key] = new static($names, $tempNames, $types, $sizes, $errors); + self::$_files[$key] = new static(array( + 'name' => $names, + 'tempName' => $tempNames, + 'type' => $types, + 'size' => $sizes, + 'error' => $errors, + )); } } } diff --git a/framework/yii/web/UrlManager.php b/framework/yii/web/UrlManager.php index 6617947..0d9547f 100644 --- a/framework/yii/web/UrlManager.php +++ b/framework/yii/web/UrlManager.php @@ -14,6 +14,10 @@ use yii\caching\Cache; /** * UrlManager handles HTTP request parsing and creation of URLs based on a set of rules. * + * @property string $baseUrl The base URL that is used by [[createUrl()]] to prepend URLs it creates. + * @property string $hostInfo The host info (e.g. "http://www.example.com") that is used by + * [[createAbsoluteUrl()]] to prepend URLs it creates. + * * @author Qiang Xue * @since 2.0 */ diff --git a/framework/yii/web/User.php b/framework/yii/web/User.php index 0ad8f68..22b85e5 100644 --- a/framework/yii/web/User.php +++ b/framework/yii/web/User.php @@ -10,6 +10,7 @@ namespace yii\web; use Yii; use yii\base\Component; use yii\base\InvalidConfigException; +use yii\base\InvalidParamException; /** * User is the class for the "user" application component that manages the user authentication status. @@ -20,6 +21,14 @@ use yii\base\InvalidConfigException; * User works with a class implementing the [[Identity]] interface. This class implements * the actual user authentication logic and is often backed by a user database table. * + * @property string|integer $id The unique identifier for the user. If null, it means the user is a guest. + * This property is read-only. + * @property Identity $identity The identity object associated with the currently logged user. Null is + * returned if the user is not logged in (not authenticated). + * @property boolean $isGuest Whether the current user is a guest. This property is read-only. + * @property string $returnUrl The URL that the user should be redirected to after login. Note that the type + * of this property differs in getter and setter. See [[getReturnUrl()]] and [[setReturnUrl()]] for details. + * * @author Qiang Xue * @since 2.0 */ @@ -132,7 +141,7 @@ class User extends Component $this->_identity = null; } else { /** @var $class Identity */ - $class = Yii::import($this->identityClass); + $class = $this->identityClass; $this->_identity = $class::findIdentity($id); } } @@ -247,20 +256,34 @@ class User extends Component * This property is usually used by the login action. If the login is successful, * the action should read this property and use it to redirect the user browser. * @param string|array $defaultUrl the default return URL in case it was not set previously. - * If this is null, it means [[Application::homeUrl]] will be redirected to. - * Please refer to [[\yii\helpers\Html::url()]] on acceptable URL formats. + * If this is null and the return URL was not set previously, [[Application::homeUrl]] will be redirected to. + * Please refer to [[setReturnUrl()]] on accepted format of the URL. * @return string the URL that the user should be redirected to after login. * @see loginRequired */ public function getReturnUrl($defaultUrl = null) { $url = Yii::$app->getSession()->get($this->returnUrlVar, $defaultUrl); + if (is_array($url)) { + if (isset($url[0])) { + $route = array_shift($url); + return Yii::$app->getUrlManager()->createUrl($route, $url); + } else { + $url = null; + } + } return $url === null ? Yii::$app->getHomeUrl() : $url; } /** * @param string|array $url the URL that the user should be redirected to after login. - * Please refer to [[\yii\helpers\Html::url()]] on acceptable URL formats. + * If an array is given, [[UrlManager::createUrl()]] will be called to create the corresponding URL. + * The first element of the array should be the route, and the rest of + * the name-value pairs are GET parameters used to construct the URL. For example, + * + * ~~~ + * array('admin/index', 'ref' => 1) + * ~~~ */ public function setReturnUrl($url) { diff --git a/framework/yii/web/UserEvent.php b/framework/yii/web/UserEvent.php index 4e39380..3e403da 100644 --- a/framework/yii/web/UserEvent.php +++ b/framework/yii/web/UserEvent.php @@ -10,6 +10,7 @@ namespace yii\web; use yii\base\Event; /** + * This event class is used for Events triggered by the [[User]] class. * * @author Qiang Xue * @since 2.0 diff --git a/framework/yii/web/YiiAsset.php b/framework/yii/web/YiiAsset.php index 8a4d77a..2ad5384 100644 --- a/framework/yii/web/YiiAsset.php +++ b/framework/yii/web/YiiAsset.php @@ -7,6 +7,9 @@ namespace yii\web; +use Yii; +use yii\base\View; + /** * @author Qiang Xue * @since 2.0 diff --git a/framework/yii/widgets/ActiveField.php b/framework/yii/widgets/ActiveField.php index bba1ead..ea8aa1b 100644 --- a/framework/yii/widgets/ActiveField.php +++ b/framework/yii/widgets/ActiveField.php @@ -216,22 +216,19 @@ class ActiveField extends Component /** * Generates a label tag for [[attribute]]. - * The label text is the label associated with the attribute, obtained via [[Model::getAttributeLabel()]]. + * @param string $label the label to use. If null, it will be generated via [[Model::getAttributeLabel()]]. + * Note that this will NOT be [[Html::encode()|encoded]]. * @param array $options the tag options in terms of name-value pairs. It will be merged with [[labelOptions]]. * The options will be rendered as the attributes of the resulting tag. The values will be HTML-encoded * using [[Html::encode()]]. If a value is null, the corresponding attribute will not be rendered. - * - * The following options are specially handled: - * - * - label: this specifies the label to be displayed. Note that this will NOT be [[encoded()]]. - * If this is not set, [[Model::getAttributeLabel()]] will be called to get the label for display - * (after encoding). - * * @return ActiveField the field object itself */ - public function label($options = array()) + public function label($label = null, $options = array()) { $options = array_merge($this->labelOptions, $options); + if ($label !== null) { + $options['label'] = $label; + } $this->parts['{label}'] = Html::activeLabel($this->model, $this->attribute, $options); return $this; } @@ -374,7 +371,6 @@ class ActiveField extends Component */ public function radio($options = array(), $enclosedByLabel = true) { - $options = array_merge($this->inputOptions, $options); if ($enclosedByLabel) { if (!isset($options['label'])) { $options['label'] = Html::encode($this->model->getAttributeLabel($this->attribute)); diff --git a/framework/yii/widgets/FragmentCache.php b/framework/yii/widgets/FragmentCache.php index 8632566..3f4027b 100644 --- a/framework/yii/widgets/FragmentCache.php +++ b/framework/yii/widgets/FragmentCache.php @@ -13,6 +13,10 @@ use yii\caching\Cache; use yii\caching\Dependency; /** + * + * @property string|boolean $cachedContent The cached content. False is returned if valid content is not found + * in the cache. This property is read-only. + * * @author Qiang Xue * @since 2.0 */ diff --git a/framework/yii/widgets/LinkSorter.php b/framework/yii/widgets/LinkSorter.php index b555475..c8b30e5 100644 --- a/framework/yii/widgets/LinkSorter.php +++ b/framework/yii/widgets/LinkSorter.php @@ -28,6 +28,11 @@ class LinkSorter extends Widget */ public $sort; /** + * @var array list of the attributes that support sorting. If not set, it will be determined + * using [[Sort::attributes]]. + */ + public $attributes; + /** * @var array HTML attributes for the sorter container tag. */ public $options = array('class' => 'sorter'); @@ -58,8 +63,9 @@ class LinkSorter extends Widget */ protected function renderSortLinks() { + $attributes = empty($this->atttributes) ? array_keys($this->sort->attributes) : $this->attributes; $links = array(); - foreach (array_keys($this->sort->attributes) as $name) { + foreach ($attributes as $name) { $links[] = $this->sort->link($name); } return Html::ul($links, array('encode' => false)); diff --git a/framework/yii/widgets/ListViewBase.php b/framework/yii/widgets/ListViewBase.php index 6be704d..8c2f8f4 100644 --- a/framework/yii/widgets/ListViewBase.php +++ b/framework/yii/widgets/ListViewBase.php @@ -66,7 +66,7 @@ abstract class ListViewBase extends Widget * - `{sorter}`: the sorter. See [[renderSorter()]]. * - `{pager}`: the pager. See [[renderPager()]]. */ - public $layout = "{summary}\n{sorter}\n{items}\n{pager}"; + public $layout = "{summary}\n{items}\n{pager}"; /** diff --git a/framework/yii/widgets/MaskedInput.php b/framework/yii/widgets/MaskedInput.php index 35794b8..8b8cbc6 100644 --- a/framework/yii/widgets/MaskedInput.php +++ b/framework/yii/widgets/MaskedInput.php @@ -18,17 +18,17 @@ use yii\web\JsExpression; * MaskedInput is similar to [[Html::textInput()]] except that * an input mask will be used to force users to enter properly formatted data, * such as phone numbers, social security numbers. - * + * * To use MaskedInput, you must set the [[mask]] property. The following example * shows how to use MaskedInput to collect phone numbers: - * + * * ~~~ * echo MaskedInput::widget(array( * 'name' => 'phone', * 'mask' => '999-999-9999', * )); * ~~~ - * + * * The masked text field is implemented based on the [jQuery masked input plugin](http://digitalbush.com/projects/masked-input-plugin). * * @author Qiang Xue diff --git a/tests/unit/data/ar/Customer.php b/tests/unit/data/ar/Customer.php index 561d1ae..bbc0182 100644 --- a/tests/unit/data/ar/Customer.php +++ b/tests/unit/data/ar/Customer.php @@ -3,6 +3,15 @@ namespace yiiunit\data\ar; use yii\db\ActiveQuery; +/** + * Class Customer + * + * @property integer $id + * @property string $name + * @property string $email + * @property string $address + * @property integer $status + */ class Customer extends ActiveRecord { const STATUS_ACTIVE = 1; diff --git a/tests/unit/data/ar/Item.php b/tests/unit/data/ar/Item.php index 5d23378..e725be9 100644 --- a/tests/unit/data/ar/Item.php +++ b/tests/unit/data/ar/Item.php @@ -2,6 +2,13 @@ namespace yiiunit\data\ar; +/** + * Class Item + * + * @property integer $id + * @property string $name + * @property integer $category_id + */ class Item extends ActiveRecord { public static function tableName() diff --git a/tests/unit/data/ar/Order.php b/tests/unit/data/ar/Order.php index 119f332..063bb67 100644 --- a/tests/unit/data/ar/Order.php +++ b/tests/unit/data/ar/Order.php @@ -2,6 +2,14 @@ namespace yiiunit\data\ar; +/** + * Class Order + * + * @property integer $id + * @property integer $customer_id + * @property integer $create_time + * @property string $total + */ class Order extends ActiveRecord { public static function tableName() diff --git a/tests/unit/data/ar/OrderItem.php b/tests/unit/data/ar/OrderItem.php index 607133e..297432b 100644 --- a/tests/unit/data/ar/OrderItem.php +++ b/tests/unit/data/ar/OrderItem.php @@ -2,6 +2,14 @@ namespace yiiunit\data\ar; +/** + * Class OrderItem + * + * @property integer $order_id + * @property integer $item_id + * @property integer $quantity + * @property string $subtotal + */ class OrderItem extends ActiveRecord { public static function tableName() diff --git a/tests/unit/data/config.php b/tests/unit/data/config.php index 1996e54..beba900 100644 --- a/tests/unit/data/config.php +++ b/tests/unit/data/config.php @@ -1,6 +1,12 @@ array( + 'cubrid' => array( + 'dsn' => 'cubrid:dbname=demodb;host=localhost;port=33000', + 'username' => 'dba', + 'password' => '', + 'fixture' => __DIR__ . '/cubrid.sql', + ), 'mysql' => array( 'dsn' => 'mysql:host=127.0.0.1;dbname=yiitest', 'username' => 'travis', diff --git a/tests/unit/data/cubrid.sql b/tests/unit/data/cubrid.sql new file mode 100644 index 0000000..3dcfa37 --- /dev/null +++ b/tests/unit/data/cubrid.sql @@ -0,0 +1,108 @@ +/** + * This is the database schema for testing CUBRID support of Yii DAO and Active Record. + * The database setup in config.php is required to perform then relevant tests: + */ + +DROP TABLE IF EXISTS tbl_composite_fk; +DROP TABLE IF EXISTS tbl_order_item; +DROP TABLE IF EXISTS tbl_item; +DROP TABLE IF EXISTS tbl_order; +DROP TABLE IF EXISTS tbl_category; +DROP TABLE IF EXISTS tbl_customer; +DROP TABLE IF EXISTS tbl_type; +DROP TABLE IF EXISTS tbl_constraints; + +CREATE TABLE `tbl_constraints` +( + `id` integer not null, + `field1` varchar(255) +); + + +CREATE TABLE `tbl_customer` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `email` varchar(128) NOT NULL, + `name` varchar(128) NOT NULL, + `address` string, + `status` int (11) DEFAULT 0, + PRIMARY KEY (`id`) +); + +CREATE TABLE `tbl_category` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(128) NOT NULL, + PRIMARY KEY (`id`) +); + +CREATE TABLE `tbl_item` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(128) NOT NULL, + `category_id` int(11) NOT NULL, + PRIMARY KEY (`id`), + CONSTRAINT `FK_item_category_id` FOREIGN KEY (`category_id`) REFERENCES `tbl_category` (`id`) ON DELETE CASCADE +); + +CREATE TABLE `tbl_order` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `customer_id` int(11) NOT NULL, + `create_time` int(11) NOT NULL, + `total` decimal(10,0) NOT NULL, + PRIMARY KEY (`id`), + CONSTRAINT `FK_order_customer_id` FOREIGN KEY (`customer_id`) REFERENCES `tbl_customer` (`id`) ON DELETE CASCADE +); + +CREATE TABLE `tbl_order_item` ( + `order_id` int(11) NOT NULL, + `item_id` int(11) NOT NULL, + `quantity` int(11) NOT NULL, + `subtotal` decimal(10,0) NOT NULL, + PRIMARY KEY (`order_id`,`item_id`), + CONSTRAINT `FK_order_item_order_id` FOREIGN KEY (`order_id`) REFERENCES `tbl_order` (`id`) ON DELETE CASCADE, + CONSTRAINT `FK_order_item_item_id` FOREIGN KEY (`item_id`) REFERENCES `tbl_item` (`id`) ON DELETE CASCADE +); + +CREATE TABLE `tbl_type` ( + `int_col` int(11) NOT NULL, + `int_col2` int(11) DEFAULT '1', + `char_col` char(100) NOT NULL, + `char_col2` varchar(100) DEFAULT 'something', + `char_col3` string, + `enum_col` enum('a', 'b'), + `float_col` double NOT NULL, + `float_col2` double DEFAULT '1.23', + `blob_col` blob, + `numeric_col` decimal(5,2) DEFAULT '33.22', + `time` timestamp NOT NULL DEFAULT '2002-01-01 00:00:00' +); + +CREATE TABLE `tbl_composite_fk` ( + `id` int(11) NOT NULL, + `order_id` int(11) NOT NULL, + `item_id` int(11) NOT NULL, + PRIMARY KEY (`id`), + CONSTRAINT `FK_composite_fk_order_item` FOREIGN KEY (`order_id`,`item_id`) REFERENCES `tbl_order_item` (`order_id`,`item_id`) ON DELETE CASCADE +); + +INSERT INTO tbl_customer (email, name, address, status) VALUES ('user1@example.com', 'user1', 'address1', 1); +INSERT INTO tbl_customer (email, name, address, status) VALUES ('user2@example.com', 'user2', 'address2', 1); +INSERT INTO tbl_customer (email, name, address, status) VALUES ('user3@example.com', 'user3', 'address3', 2); + +INSERT INTO tbl_category (name) VALUES ('Books'); +INSERT INTO tbl_category (name) VALUES ('Movies'); + +INSERT INTO tbl_item (name, category_id) VALUES ('Agile Web Application Development with Yii1.1 and PHP5', 1); +INSERT INTO tbl_item (name, category_id) VALUES ('Yii 1.1 Application Development Cookbook', 1); +INSERT INTO tbl_item (name, category_id) VALUES ('Ice Age', 2); +INSERT INTO tbl_item (name, category_id) VALUES ('Toy Story', 2); +INSERT INTO tbl_item (name, category_id) VALUES ('Cars', 2); + +INSERT INTO tbl_order (customer_id, create_time, total) VALUES (1, 1325282384, 110.0); +INSERT INTO tbl_order (customer_id, create_time, total) VALUES (2, 1325334482, 33.0); +INSERT INTO tbl_order (customer_id, create_time, total) VALUES (2, 1325502201, 40.0); + +INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (1, 1, 1, 30.0); +INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (1, 2, 2, 40.0); +INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (2, 4, 1, 10.0); +INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (2, 5, 1, 15.0); +INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (2, 3, 1, 8.0); +INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (3, 2, 1, 40.0); diff --git a/tests/unit/data/mysql.sql b/tests/unit/data/mysql.sql index 2e9458e..133348d 100644 --- a/tests/unit/data/mysql.sql +++ b/tests/unit/data/mysql.sql @@ -3,6 +3,7 @@ * The database setup in config.php is required to perform then relevant tests: */ +DROP TABLE IF EXISTS tbl_composite_fk CASCADE; DROP TABLE IF EXISTS tbl_order_item CASCADE; DROP TABLE IF EXISTS tbl_item CASCADE; DROP TABLE IF EXISTS tbl_order CASCADE; @@ -62,6 +63,14 @@ CREATE TABLE `tbl_order_item` ( CONSTRAINT `FK_order_item_item_id` FOREIGN KEY (`item_id`) REFERENCES `tbl_item` (`id`) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; +CREATE TABLE `tbl_composite_fk` ( + `id` int(11) NOT NULL, + `order_id` int(11) NOT NULL, + `item_id` int(11) NOT NULL, + PRIMARY KEY (`id`), + CONSTRAINT `FK_composite_fk_order_item` FOREIGN KEY (`order_id`,`item_id`) REFERENCES `tbl_order_item` (`order_id`,`item_id`) ON DELETE CASCADE +); + CREATE TABLE `tbl_type` ( `int_col` int(11) NOT NULL, `int_col2` int(11) DEFAULT '1', diff --git a/tests/unit/data/sqlite.sql b/tests/unit/data/sqlite.sql index f75bfa6..f031ac3 100644 --- a/tests/unit/data/sqlite.sql +++ b/tests/unit/data/sqlite.sql @@ -3,6 +3,7 @@ * The database setup in config.php is required to perform then relevant tests: */ +DROP TABLE IF EXISTS tbl_composite_fk; DROP TABLE IF EXISTS tbl_order_item; DROP TABLE IF EXISTS tbl_item; DROP TABLE IF EXISTS tbl_order; @@ -48,6 +49,14 @@ CREATE TABLE tbl_order_item ( PRIMARY KEY (order_id, item_id) ); +CREATE TABLE `tbl_composite_fk` ( + `id` int(11) NOT NULL, + `order_id` int(11) NOT NULL, + `item_id` int(11) NOT NULL, + PRIMARY KEY (`id`), + CONSTRAINT `FK_composite_fk_order_item` FOREIGN KEY (`order_id`,`item_id`) REFERENCES `tbl_order_item` (`order_id`,`item_id`) ON DELETE CASCADE +); + CREATE TABLE tbl_type ( int_col INTEGER NOT NULL, int_col2 INTEGER DEFAULT '1', diff --git a/tests/unit/data/travis/README.md b/tests/unit/data/travis/README.md new file mode 100644 index 0000000..c86497e --- /dev/null +++ b/tests/unit/data/travis/README.md @@ -0,0 +1,12 @@ +This directory contains scripts for automated test runs via the [Travis CI](http://travis-ci.org) build service. They are used for the preparation of worker instances by setting up needed extensions and configuring database access. + +These scripts might be used to configure your own system for test runs. But since their primary purpose remains to support Travis in running the test cases, you would be best advised to stick to the setup notes in the tests themselves. + +The scripts are: + + - [`apc-setup.sh`](apc-setup.sh) + Installs and configures the [apc pecl extension](http://pecl.php.net/package/apc) + - [`memcache-setup.sh`](memcache-setup.sh) + Compiles and installs the [memcache pecl extension](http://pecl.php.net/package/memcache) + - [`cubrid-setup.sh`](cubrid-setup.sh) + Prepares the [CUBRID](http://www.cubrid.org/) server instance by installing the server and PHP PDO driver diff --git a/tests/unit/data/travis/apc-setup.sh b/tests/unit/data/travis/apc-setup.sh new file mode 100755 index 0000000..e5e8734 --- /dev/null +++ b/tests/unit/data/travis/apc-setup.sh @@ -0,0 +1,2 @@ +echo "extension = apc.so" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini +echo "apc.enable_cli = 1" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini \ No newline at end of file diff --git a/tests/unit/data/travis/cubrid-setup.sh b/tests/unit/data/travis/cubrid-setup.sh new file mode 100755 index 0000000..af007ff --- /dev/null +++ b/tests/unit/data/travis/cubrid-setup.sh @@ -0,0 +1,32 @@ +#!/bin/sh +# +# install CUBRID DBMS https://github.com/CUBRID/node-cubrid/blob/056e734ce36bb3fd25f100c983beb3947e899c1c/.travis.yml + +sudo hostname localhost +# Update OS before installing prerequisites. +sudo apt-get update +# Install Chef Solo prerequisites. +sudo apt-get install ruby ruby-dev libopenssl-ruby rdoc ri irb build-essential ssl-cert +# Install Chef Solo. +# Chef Solo 11.4.4 is broken, so install a previous version. +# The bug is planned to be fixed in 11.4.5 which haven't been released yet. +sudo gem install --version '<11.4.4' chef --no-rdoc --no-ri +# Make sure the target directory for cookbooks exists. +mkdir -p /tmp/chef-solo +# Prepare a file with runlist for Chef Solo. +echo '{"cubrid":{"version":"'$CUBRID_VERSION'"},"run_list":["cubrid::demodb"]}' > cubrid_chef.json +# Install CUBRID via Chef Solo. Download all cookbooks from a remote URL. +sudo chef-solo -c tests/unit/data/travis/cubrid-solo.rb -j cubrid_chef.json -r http://sourceforge.net/projects/cubrid/files/CUBRID-Demo-Virtual-Machines/Vagrant/chef-cookbooks.tar.gz/download + + +install_pdo_cubrid() { + wget "http://pecl.php.net/get/PDO_CUBRID-9.1.0.0003.tgz" && + tar -zxf "PDO_CUBRID-9.1.0.0003.tgz" && + sh -c "cd PDO_CUBRID-9.1.0.0003 && phpize && ./configure && make && sudo make install" + + echo "extension=pdo_cubrid.so" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini + + return $? +} + +install_pdo_cubrid > ~/pdo_cubrid.log || ( echo "=== PDO CUBRID BUILD FAILED ==="; cat ~/pdo_cubrid.log ) \ No newline at end of file diff --git a/tests/unit/data/travis/cubrid-solo.rb b/tests/unit/data/travis/cubrid-solo.rb new file mode 100644 index 0000000..f5f0004 --- /dev/null +++ b/tests/unit/data/travis/cubrid-solo.rb @@ -0,0 +1,5 @@ +file_cache_path "/tmp/chef-solo" +data_bag_path "/tmp/chef-solo/data_bags" +encrypted_data_bag_secret "/tmp/chef-solo/data_bag_key" +cookbook_path [ "/tmp/chef-solo/cookbooks" ] +role_path "/tmp/chef-solo/roles" \ No newline at end of file diff --git a/tests/unit/data/travis/memcache-setup.sh b/tests/unit/data/travis/memcache-setup.sh new file mode 100755 index 0000000..6b623d6 --- /dev/null +++ b/tests/unit/data/travis/memcache-setup.sh @@ -0,0 +1,4 @@ +#!/bin/sh + +echo "extension=memcache.so" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini +echo "extension=memcached.so" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini diff --git a/tests/unit/framework/YiiBaseTest.php b/tests/unit/framework/YiiBaseTest.php index e256b2b..72b5f24 100644 --- a/tests/unit/framework/YiiBaseTest.php +++ b/tests/unit/framework/YiiBaseTest.php @@ -6,6 +6,7 @@ use yiiunit\TestCase; /** * YiiBaseTest + * @group base */ class YiiBaseTest extends TestCase { diff --git a/tests/unit/framework/base/BehaviorTest.php b/tests/unit/framework/base/BehaviorTest.php index edb9a1e..b6eda09 100644 --- a/tests/unit/framework/base/BehaviorTest.php +++ b/tests/unit/framework/base/BehaviorTest.php @@ -28,8 +28,27 @@ class BarBehavior extends Behavior { return 'behavior method'; } + + public function __call($name, $params) + { + if ($name == 'magicBehaviorMethod') { + return 'Magic Behavior Method Result!'; + } + return parent::__call($name, $params); + } + + public function hasMethod($name) + { + if ($name == 'magicBehaviorMethod') { + return true; + } + return parent::hasMethod($name); + } } +/** + * @group base + */ class BehaviorTest extends TestCase { protected function setUp() @@ -59,4 +78,29 @@ class BehaviorTest extends TestCase $this->assertEquals('behavior property', $foo->behaviorProperty); $this->assertEquals('behavior method', $foo->behaviorMethod()); } + + public function testMagicMethods() + { + $bar = new BarClass(); + $behavior = new BarBehavior(); + + $this->assertFalse($bar->hasMethod('magicBehaviorMethod')); + $bar->attachBehavior('bar', $behavior); + $this->assertFalse($bar->hasMethod('magicBehaviorMethod', false)); + $this->assertTrue($bar->hasMethod('magicBehaviorMethod')); + + $this->assertEquals('Magic Behavior Method Result!', $bar->magicBehaviorMethod()); + } + + public function testCallUnknownMethod() + { + $bar = new BarClass(); + $behavior = new BarBehavior(); + $this->setExpectedException('yii\base\UnknownMethodException'); + + $this->assertFalse($bar->hasMethod('nomagicBehaviorMethod')); + $bar->attachBehavior('bar', $behavior); + $bar->nomagicBehaviorMethod(); + } + } diff --git a/tests/unit/framework/base/ComponentTest.php b/tests/unit/framework/base/ComponentTest.php index 79fb7db..98786e2 100644 --- a/tests/unit/framework/base/ComponentTest.php +++ b/tests/unit/framework/base/ComponentTest.php @@ -17,6 +17,9 @@ function globalEventHandler2($event) $event->handled = true; } +/** + * @group base + */ class ComponentTest extends TestCase { /** diff --git a/tests/unit/framework/base/FormatterTest.php b/tests/unit/framework/base/FormatterTest.php index 01dd682..ae71a5c 100644 --- a/tests/unit/framework/base/FormatterTest.php +++ b/tests/unit/framework/base/FormatterTest.php @@ -10,9 +10,7 @@ use yii\base\Formatter; use yiiunit\TestCase; /** - * - * @author Qiang Xue - * @since 2.0 + * @group base */ class FormatterTest extends TestCase { diff --git a/tests/unit/framework/base/ModelTest.php b/tests/unit/framework/base/ModelTest.php index e4d8976..b338c17 100644 --- a/tests/unit/framework/base/ModelTest.php +++ b/tests/unit/framework/base/ModelTest.php @@ -9,7 +9,7 @@ use yiiunit\data\base\Singer; use yiiunit\data\base\InvalidRulesModel; /** - * ModelTest + * @group base */ class ModelTest extends TestCase { diff --git a/tests/unit/framework/base/ObjectTest.php b/tests/unit/framework/base/ObjectTest.php index 933b721..0bd9b1d 100644 --- a/tests/unit/framework/base/ObjectTest.php +++ b/tests/unit/framework/base/ObjectTest.php @@ -5,7 +5,7 @@ use yii\base\Object; use yiiunit\TestCase; /** - * ObjectTest + * @group base */ class ObjectTest extends TestCase { @@ -134,11 +134,6 @@ class ObjectTest extends TestCase $this->assertEquals('new text', $this->object->object->text); } - public function testAnonymousFunctionProperty() - { - $this->assertEquals(2, $this->object->execute(1)); - } - public function testConstruct() { $object = new NewObject(array('text' => 'test text')); diff --git a/tests/unit/framework/behaviors/AutoTimestampTest.php b/tests/unit/framework/behaviors/AutoTimestampTest.php index 0e17a39..c26d912 100644 --- a/tests/unit/framework/behaviors/AutoTimestampTest.php +++ b/tests/unit/framework/behaviors/AutoTimestampTest.php @@ -11,6 +11,8 @@ use yii\behaviors\AutoTimestamp; /** * Unit test for [[\yii\behaviors\AutoTimestamp]]. * @see AutoTimestamp + * + * @group behaviors */ class AutoTimestampTest extends TestCase { diff --git a/tests/unit/framework/caching/ApcCacheTest.php b/tests/unit/framework/caching/ApcCacheTest.php index 1d07498..adda151 100644 --- a/tests/unit/framework/caching/ApcCacheTest.php +++ b/tests/unit/framework/caching/ApcCacheTest.php @@ -5,6 +5,8 @@ use yii\caching\ApcCache; /** * Class for testing APC cache backend + * @group apc + * @group caching */ class ApcCacheTest extends CacheTestCase { diff --git a/tests/unit/framework/caching/CacheTestCase.php b/tests/unit/framework/caching/CacheTestCase.php index 491459b..94894a3 100644 --- a/tests/unit/framework/caching/CacheTestCase.php +++ b/tests/unit/framework/caching/CacheTestCase.php @@ -91,6 +91,18 @@ abstract class CacheTestCase extends TestCase $this->assertEquals('array_test', $array['array_test']); } + public function testExists() + { + $cache = $this->prepare(); + + $this->assertTrue($cache->exists('string_test')); + // check whether exists affects the value + $this->assertEquals('string_test', $cache->get('string_test')); + + $this->assertTrue($cache->exists('number_test')); + $this->assertFalse($cache->exists('not_exists')); + } + public function testArrayAccess() { $cache = $this->getCacheInstance(); diff --git a/tests/unit/framework/caching/DbCacheTest.php b/tests/unit/framework/caching/DbCacheTest.php index 969b034..1e94d58 100644 --- a/tests/unit/framework/caching/DbCacheTest.php +++ b/tests/unit/framework/caching/DbCacheTest.php @@ -6,6 +6,8 @@ use yii\caching\DbCache; /** * Class for testing file cache backend + * @group db + * @group caching */ class DbCacheTest extends CacheTestCase { diff --git a/tests/unit/framework/caching/FileCacheTest.php b/tests/unit/framework/caching/FileCacheTest.php index 0bdbc86..263ecb4 100644 --- a/tests/unit/framework/caching/FileCacheTest.php +++ b/tests/unit/framework/caching/FileCacheTest.php @@ -5,6 +5,7 @@ use yii\caching\FileCache; /** * Class for testing file cache backend + * @group caching */ class FileCacheTest extends CacheTestCase { diff --git a/tests/unit/framework/caching/MemCacheTest.php b/tests/unit/framework/caching/MemCacheTest.php index d54d807..32374b5 100644 --- a/tests/unit/framework/caching/MemCacheTest.php +++ b/tests/unit/framework/caching/MemCacheTest.php @@ -5,6 +5,8 @@ use yii\caching\MemCache; /** * Class for testing memcache cache backend + * @group memcache + * @group caching */ class MemCacheTest extends CacheTestCase { diff --git a/tests/unit/framework/caching/MemCachedTest.php b/tests/unit/framework/caching/MemCachedTest.php index faf0d56..f39ed17 100644 --- a/tests/unit/framework/caching/MemCachedTest.php +++ b/tests/unit/framework/caching/MemCachedTest.php @@ -5,6 +5,8 @@ use yii\caching\MemCache; /** * Class for testing memcached cache backend + * @group memcached + * @group caching */ class MemCachedTest extends CacheTestCase { diff --git a/tests/unit/framework/caching/RedisCacheTest.php b/tests/unit/framework/caching/RedisCacheTest.php index 0924d0f..d02773d 100644 --- a/tests/unit/framework/caching/RedisCacheTest.php +++ b/tests/unit/framework/caching/RedisCacheTest.php @@ -6,6 +6,8 @@ use yiiunit\TestCase; /** * Class for testing redis cache backend + * @group redis + * @group caching */ class RedisCacheTest extends CacheTestCase { diff --git a/tests/unit/framework/caching/WinCacheTest.php b/tests/unit/framework/caching/WinCacheTest.php index b6f2425..1bce102 100644 --- a/tests/unit/framework/caching/WinCacheTest.php +++ b/tests/unit/framework/caching/WinCacheTest.php @@ -5,6 +5,8 @@ use yii\caching\WinCache; /** * Class for testing wincache backend + * @group wincache + * @group caching */ class WinCacheTest extends CacheTestCase { diff --git a/tests/unit/framework/caching/XCacheTest.php b/tests/unit/framework/caching/XCacheTest.php index 7ee0a0e..989765d 100644 --- a/tests/unit/framework/caching/XCacheTest.php +++ b/tests/unit/framework/caching/XCacheTest.php @@ -5,6 +5,8 @@ use yii\caching\XCache; /** * Class for testing xcache backend + * @group xcache + * @group caching */ class XCacheTest extends CacheTestCase { diff --git a/tests/unit/framework/caching/ZendDataCacheTest.php b/tests/unit/framework/caching/ZendDataCacheTest.php index 2d68bfd..96354cd 100644 --- a/tests/unit/framework/caching/ZendDataCacheTest.php +++ b/tests/unit/framework/caching/ZendDataCacheTest.php @@ -6,6 +6,8 @@ use yii\caching\ZendDataCache; /** * Class for testing Zend cache backend + * @group zenddata + * @group caching */ class ZendDataCacheTest extends CacheTestCase { diff --git a/tests/unit/framework/console/controllers/AssetControllerTest.php b/tests/unit/framework/console/controllers/AssetControllerTest.php index aaf5ca9..67dbdaa 100644 --- a/tests/unit/framework/console/controllers/AssetControllerTest.php +++ b/tests/unit/framework/console/controllers/AssetControllerTest.php @@ -6,6 +6,8 @@ use yii\console\controllers\AssetController; /** * Unit test for [[\yii\console\controllers\AssetController]]. * @see AssetController + * + * @group console */ class AssetControllerTest extends TestCase { diff --git a/tests/unit/framework/console/controllers/MessageControllerTest.php b/tests/unit/framework/console/controllers/MessageControllerTest.php index cdd38b8..b0c697c 100644 --- a/tests/unit/framework/console/controllers/MessageControllerTest.php +++ b/tests/unit/framework/console/controllers/MessageControllerTest.php @@ -6,6 +6,8 @@ use yii\console\controllers\MessageController; /** * Unit test for [[\yii\console\controllers\MessageController]]. * @see MessageController + * + * @group console */ class MessageControllerTest extends TestCase { diff --git a/tests/unit/framework/data/ActiveDataProviderTest.php b/tests/unit/framework/data/ActiveDataProviderTest.php index 2699a52..3f65ebb 100644 --- a/tests/unit/framework/data/ActiveDataProviderTest.php +++ b/tests/unit/framework/data/ActiveDataProviderTest.php @@ -16,6 +16,8 @@ use yiiunit\data\ar\Order; /** * @author Qiang Xue * @since 2.0 + * + * @group data */ class ActiveDataProviderTest extends DatabaseTestCase { diff --git a/tests/unit/framework/data/SortTest.php b/tests/unit/framework/data/SortTest.php index 9891ad1..c4cc6aa 100644 --- a/tests/unit/framework/data/SortTest.php +++ b/tests/unit/framework/data/SortTest.php @@ -14,6 +14,8 @@ use yii\data\Sort; /** * @author Qiang Xue * @since 2.0 + * + * @group data */ class SortTest extends TestCase { diff --git a/tests/unit/framework/db/ActiveRecordTest.php b/tests/unit/framework/db/ActiveRecordTest.php index 7df4159..2f9b345 100644 --- a/tests/unit/framework/db/ActiveRecordTest.php +++ b/tests/unit/framework/db/ActiveRecordTest.php @@ -9,6 +9,10 @@ use yiiunit\data\ar\OrderItem; use yiiunit\data\ar\Order; use yiiunit\data\ar\Item; +/** + * @group db + * @group mysql + */ class ActiveRecordTest extends DatabaseTestCase { protected function setUp() diff --git a/tests/unit/framework/db/CommandTest.php b/tests/unit/framework/db/CommandTest.php index 52fd046..d9eb0e7 100644 --- a/tests/unit/framework/db/CommandTest.php +++ b/tests/unit/framework/db/CommandTest.php @@ -7,14 +7,12 @@ use yii\db\Command; use yii\db\Query; use yii\db\DataReader; +/** + * @group db + * @group mysql + */ class CommandTest extends DatabaseTestCase { - protected function setUp() - { - parent::setUp(); - $this->mockApplication(); - } - public function testConstruct() { $db = $this->getConnection(false); @@ -221,6 +219,29 @@ class CommandTest extends DatabaseTestCase $this->assertTrue(is_array($result) && isset($result[0])); } + // getPDOType is currently private +// public function testGetPDOType() +// { +// $values = array( +// array(null, \PDO::PARAM_NULL), +// array('', \PDO::PARAM_STR), +// array('hello', \PDO::PARAM_STR), +// array(0, \PDO::PARAM_INT), +// array(1, \PDO::PARAM_INT), +// array(1337, \PDO::PARAM_INT), +// array(true, \PDO::PARAM_BOOL), +// array(false, \PDO::PARAM_BOOL), +// array($fp=fopen(__FILE__, 'rb'), \PDO::PARAM_LOB), +// ); +// +// $command = $this->getConnection()->createCommand(); +// +// foreach($values as $value) { +// $this->assertEquals($value[1], $command->getPdoType($value[0])); +// } +// fclose($fp); +// } + public function testInsert() { } diff --git a/tests/unit/framework/db/ConnectionTest.php b/tests/unit/framework/db/ConnectionTest.php index 42b470b..04c5d53 100644 --- a/tests/unit/framework/db/ConnectionTest.php +++ b/tests/unit/framework/db/ConnectionTest.php @@ -4,14 +4,12 @@ namespace yiiunit\framework\db; use yii\db\Connection; +/** + * @group db + * @group mysql + */ class ConnectionTest extends DatabaseTestCase { - protected function setUp() - { - parent::setUp(); - $this->mockApplication(); - } - public function testConstruct() { $connection = $this->getConnection(false); diff --git a/tests/unit/framework/db/DatabaseTestCase.php b/tests/unit/framework/db/DatabaseTestCase.php index 1fd2d56..d8d2916 100644 --- a/tests/unit/framework/db/DatabaseTestCase.php +++ b/tests/unit/framework/db/DatabaseTestCase.php @@ -1,18 +1,21 @@ mockApplication(); $databases = $this->getParam('databases'); $this->database = $databases[$this->driverName]; $pdo_database = 'pdo_'.$this->driverName; @@ -20,6 +23,15 @@ abstract class DatabaseTestCase extends TestCase if (!extension_loaded('pdo') || !extension_loaded($pdo_database)) { $this->markTestSkipped('pdo and pdo_'.$pdo_database.' extension are required.'); } + $this->mockApplication(); + } + + protected function tearDown() + { + if ($this->db) { + $this->db->close(); + } + $this->destroyApplication(); } /** diff --git a/tests/unit/framework/db/QueryBuilderTest.php b/tests/unit/framework/db/QueryBuilderTest.php index 146cfdb..d43c901 100644 --- a/tests/unit/framework/db/QueryBuilderTest.php +++ b/tests/unit/framework/db/QueryBuilderTest.php @@ -8,15 +8,14 @@ use yii\db\mysql\QueryBuilder as MysqlQueryBuilder; use yii\db\sqlite\QueryBuilder as SqliteQueryBuilder; use yii\db\mssql\QueryBuilder as MssqlQueryBuilder; use yii\db\pgsql\QueryBuilder as PgsqlQueryBuilder; +use yii\db\cubrid\QueryBuilder as CubridQueryBuilder; +/** + * @group db + * @group mysql + */ class QueryBuilderTest extends DatabaseTestCase { - protected function setUp() - { - parent::setUp(); - $this->mockApplication(); - } - /** * @throws \Exception * @return QueryBuilder @@ -32,6 +31,8 @@ class QueryBuilderTest extends DatabaseTestCase return new MssqlQueryBuilder($this->getConnection()); case 'pgsql': return new PgsqlQueryBuilder($this->getConnection()); + case 'cubrid': + return new CubridQueryBuilder($this->getConnection()); } throw new \Exception('Test is not implemented for ' . $this->driverName); } @@ -112,7 +113,7 @@ class QueryBuilderTest extends DatabaseTestCase } } - public function testAddDropPrimayKey() + public function testAddDropPrimaryKey() { $tableName = 'tbl_constraints'; $pkeyName = $tableName . "_pkey"; diff --git a/tests/unit/framework/db/QueryTest.php b/tests/unit/framework/db/QueryTest.php index 5d1f1a9..a275afd 100644 --- a/tests/unit/framework/db/QueryTest.php +++ b/tests/unit/framework/db/QueryTest.php @@ -7,14 +7,12 @@ use yii\db\Command; use yii\db\Query; use yii\db\DataReader; +/** + * @group db + * @group mysql + */ class QueryTest extends DatabaseTestCase { - protected function setUp() - { - parent::setUp(); - $this->mockApplication(); - } - public function testSelect() { // default diff --git a/tests/unit/framework/db/SchemaTest.php b/tests/unit/framework/db/SchemaTest.php new file mode 100644 index 0000000..2a3015d --- /dev/null +++ b/tests/unit/framework/db/SchemaTest.php @@ -0,0 +1,70 @@ +getConnection()->schema; + + $tables = $schema->getTableNames(); + $this->assertTrue(in_array('tbl_customer', $tables)); + $this->assertTrue(in_array('tbl_category', $tables)); + $this->assertTrue(in_array('tbl_item', $tables)); + $this->assertTrue(in_array('tbl_order', $tables)); + $this->assertTrue(in_array('tbl_order_item', $tables)); + $this->assertTrue(in_array('tbl_type', $tables)); + } + + public function testGetTableSchemas() + { + /** @var Schema $schema */ + $schema = $this->getConnection()->schema; + + $tables = $schema->getTableSchemas(); + $this->assertEquals(count($schema->getTableNames()), count($tables)); + foreach($tables as $table) { + $this->assertInstanceOf('yii\db\TableSchema', $table); + } + } + + public function testGetNonExistingTableSchema() + { + $this->assertNull($this->getConnection()->schema->getTableSchema('nonexisting_table')); + } + + public function testSchemaCache() + { + /** @var Schema $schema */ + $schema = $this->getConnection()->schema; + + $schema->db->enableSchemaCache = true; + $schema->db->schemaCache = new FileCache(); + $noCacheTable = $schema->getTableSchema('tbl_type', true); + $cachedTable = $schema->getTableSchema('tbl_type', true); + $this->assertEquals($noCacheTable, $cachedTable); + } + + public function testCompositeFk() + { + /** @var Schema $schema */ + $schema = $this->getConnection()->schema; + + $table = $schema->getTableSchema('tbl_composite_fk'); + + $this->assertCount(1, $table->foreignKeys); + $this->assertTrue(isset($table->foreignKeys[0])); + $this->assertEquals('tbl_order_item', $table->foreignKeys[0][0]); + $this->assertEquals('order_id', $table->foreignKeys[0]['order_id']); + $this->assertEquals('item_id', $table->foreignKeys[0]['item_id']); + } +} diff --git a/tests/unit/framework/db/cubrid/CubridActiveRecordTest.php b/tests/unit/framework/db/cubrid/CubridActiveRecordTest.php new file mode 100644 index 0000000..2d2db15 --- /dev/null +++ b/tests/unit/framework/db/cubrid/CubridActiveRecordTest.php @@ -0,0 +1,36 @@ +name = 'boolean customer'; + $customer->email = 'mail@example.com'; + $customer->status = true; + $customer->save(false); + + $customer->refresh(); + $this->assertEquals(1, $customer->status); + + $customer->status = false; + $customer->save(false); + + $customer->refresh(); + $this->assertEquals(0, $customer->status); + } +} diff --git a/tests/unit/framework/db/cubrid/CubridCommandTest.php b/tests/unit/framework/db/cubrid/CubridCommandTest.php new file mode 100644 index 0000000..45d3c1c --- /dev/null +++ b/tests/unit/framework/db/cubrid/CubridCommandTest.php @@ -0,0 +1,79 @@ +getConnection(); + + // bindParam + $sql = 'INSERT INTO tbl_customer(email, name, address) VALUES (:email, :name, :address)'; + $command = $db->createCommand($sql); + $email = 'user4@example.com'; + $name = 'user4'; + $address = 'address4'; + $command->bindParam(':email', $email); + $command->bindParam(':name', $name); + $command->bindParam(':address', $address); + $command->execute(); + + $sql = 'SELECT name FROM tbl_customer WHERE email=:email'; + $command = $db->createCommand($sql); + $command->bindParam(':email', $email); + $this->assertEquals($name, $command->queryScalar()); + + $sql = "INSERT INTO tbl_type (int_col, char_col, char_col2, enum_col, float_col, blob_col, numeric_col) VALUES (:int_col, '', :char_col, :enum_col, :float_col, CHAR_TO_BLOB(:blob_col), :numeric_col)"; + $command = $db->createCommand($sql); + $intCol = 123; + $charCol = 'abc'; + $enumCol = 'a'; + $floatCol = 1.23; + $blobCol = "\x10\x11\x12"; + $numericCol = '1.23'; + $command->bindParam(':int_col', $intCol); + $command->bindParam(':char_col', $charCol); + $command->bindParam(':enum_col', $enumCol); + $command->bindParam(':float_col', $floatCol); + $command->bindParam(':blob_col', $blobCol); + $command->bindParam(':numeric_col', $numericCol); + $this->assertEquals(1, $command->execute()); + + $sql = 'SELECT * FROM tbl_type'; + $row = $db->createCommand($sql)->queryOne(); + $this->assertEquals($intCol, $row['int_col']); + $this->assertEquals($enumCol, $row['enum_col']); + $this->assertEquals($charCol, $row['char_col2']); + $this->assertEquals($floatCol, $row['float_col']); + $this->assertEquals($blobCol, fread($row['blob_col'], 3)); + $this->assertEquals($numericCol, $row['numeric_col']); + + // bindValue + $sql = 'INSERT INTO tbl_customer(email, name, address) VALUES (:email, \'user5\', \'address5\')'; + $command = $db->createCommand($sql); + $command->bindValue(':email', 'user5@example.com'); + $command->execute(); + + $sql = 'SELECT email FROM tbl_customer WHERE name=:name'; + $command = $db->createCommand($sql); + $command->bindValue(':name', 'user5'); + $this->assertEquals('user5@example.com', $command->queryScalar()); + } + + public function testAutoQuoting() + { + $db = $this->getConnection(false); + + $sql = 'SELECT [[id]], [[t.name]] FROM {{tbl_customer}} t'; + $command = $db->createCommand($sql); + $this->assertEquals('SELECT "id", "t"."name" FROM "tbl_customer" t', $command->sql); + } +} diff --git a/tests/unit/framework/db/cubrid/CubridConnectionTest.php b/tests/unit/framework/db/cubrid/CubridConnectionTest.php new file mode 100644 index 0000000..4cd6e20 --- /dev/null +++ b/tests/unit/framework/db/cubrid/CubridConnectionTest.php @@ -0,0 +1,44 @@ +getConnection(false); + $this->assertEquals(123, $connection->quoteValue(123)); + $this->assertEquals("'string'", $connection->quoteValue('string')); + $this->assertEquals("'It''s interesting'", $connection->quoteValue("It's interesting")); + } + + public function testQuoteTableName() + { + $connection = $this->getConnection(false); + $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"')); + $this->assertEquals('{{table}}', $connection->quoteTableName('{{table}}')); + $this->assertEquals('(table)', $connection->quoteTableName('(table)')); + } + + public function testQuoteColumnName() + { + $connection = $this->getConnection(false); + $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"')); + $this->assertEquals('[[column]]', $connection->quoteColumnName('[[column]]')); + $this->assertEquals('{{column}}', $connection->quoteColumnName('{{column}}')); + $this->assertEquals('(column)', $connection->quoteColumnName('(column)')); + } +} diff --git a/tests/unit/framework/db/cubrid/CubridQueryBuilderTest.php b/tests/unit/framework/db/cubrid/CubridQueryBuilderTest.php new file mode 100644 index 0000000..107b73b --- /dev/null +++ b/tests/unit/framework/db/cubrid/CubridQueryBuilderTest.php @@ -0,0 +1,84 @@ + 5)', 'int NOT NULL AUTO_INCREMENT PRIMARY KEY CHECK (value > 5)'), + array(Schema::TYPE_PK . '(8) CHECK (value > 5)', 'int NOT NULL AUTO_INCREMENT PRIMARY KEY CHECK (value > 5)'), + array(Schema::TYPE_STRING, 'varchar(255)'), + array(Schema::TYPE_STRING . '(32)', 'varchar(32)'), + array(Schema::TYPE_STRING . ' CHECK (value LIKE "test%")', 'varchar(255) CHECK (value LIKE "test%")'), + array(Schema::TYPE_STRING . '(32) CHECK (value LIKE "test%")', 'varchar(32) CHECK (value LIKE "test%")'), + array(Schema::TYPE_STRING . ' NOT NULL', 'varchar(255) NOT NULL'), + array(Schema::TYPE_TEXT, 'varchar'), + array(Schema::TYPE_TEXT . '(255)', 'varchar'), + array(Schema::TYPE_TEXT . ' CHECK (value LIKE "test%")', 'varchar CHECK (value LIKE "test%")'), + array(Schema::TYPE_TEXT . '(255) CHECK (value LIKE "test%")', 'varchar CHECK (value LIKE "test%")'), + array(Schema::TYPE_TEXT . ' NOT NULL', 'varchar NOT NULL'), + array(Schema::TYPE_TEXT . '(255) NOT NULL', 'varchar NOT NULL'), + array(Schema::TYPE_SMALLINT, 'smallint'), + array(Schema::TYPE_SMALLINT . '(8)', 'smallint'), + array(Schema::TYPE_INTEGER, 'int'), + array(Schema::TYPE_INTEGER . '(8)', 'int'), + array(Schema::TYPE_INTEGER . ' CHECK (value > 5)', 'int CHECK (value > 5)'), + array(Schema::TYPE_INTEGER . '(8) CHECK (value > 5)', 'int CHECK (value > 5)'), + array(Schema::TYPE_INTEGER . ' NOT NULL', 'int NOT NULL'), + array(Schema::TYPE_BIGINT, 'bigint'), + array(Schema::TYPE_BIGINT . '(8)', 'bigint'), + array(Schema::TYPE_BIGINT . ' CHECK (value > 5)', 'bigint CHECK (value > 5)'), + array(Schema::TYPE_BIGINT . '(8) CHECK (value > 5)', 'bigint CHECK (value > 5)'), + array(Schema::TYPE_BIGINT . ' NOT NULL', 'bigint NOT NULL'), + array(Schema::TYPE_FLOAT, 'float(7)'), + array(Schema::TYPE_FLOAT . '(16)', 'float(16)'), + array(Schema::TYPE_FLOAT . ' CHECK (value > 5.6)', 'float(7) CHECK (value > 5.6)'), + array(Schema::TYPE_FLOAT . '(16) CHECK (value > 5.6)', 'float(16) CHECK (value > 5.6)'), + array(Schema::TYPE_FLOAT . ' NOT NULL', 'float(7) NOT NULL'), + array(Schema::TYPE_DECIMAL, 'decimal(10,0)'), + array(Schema::TYPE_DECIMAL . '(12,4)', 'decimal(12,4)'), + array(Schema::TYPE_DECIMAL . ' CHECK (value > 5.6)', 'decimal(10,0) CHECK (value > 5.6)'), + array(Schema::TYPE_DECIMAL . '(12,4) CHECK (value > 5.6)', 'decimal(12,4) CHECK (value > 5.6)'), + array(Schema::TYPE_DECIMAL . ' NOT NULL', 'decimal(10,0) NOT NULL'), + array(Schema::TYPE_DATETIME, 'datetime'), + array(Schema::TYPE_DATETIME . " CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')", "datetime CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')"), + array(Schema::TYPE_DATETIME . ' NOT NULL', 'datetime NOT NULL'), + array(Schema::TYPE_TIMESTAMP, 'timestamp'), + array(Schema::TYPE_TIMESTAMP . " CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')", "timestamp CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')"), + array(Schema::TYPE_TIMESTAMP . ' NOT NULL', 'timestamp NOT NULL'), + array(Schema::TYPE_TIME, 'time'), + array(Schema::TYPE_TIME . " CHECK(value BETWEEN '12:00:00' AND '13:01:01')", "time CHECK(value BETWEEN '12:00:00' AND '13:01:01')"), + array(Schema::TYPE_TIME . ' NOT NULL', 'time NOT NULL'), + array(Schema::TYPE_DATE, 'date'), + array(Schema::TYPE_DATE . " CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')", "date CHECK(value BETWEEN '2011-01-01' AND '2013-01-01')"), + array(Schema::TYPE_DATE . ' NOT NULL', 'date NOT NULL'), + array(Schema::TYPE_BINARY, 'blob'), + array(Schema::TYPE_BOOLEAN, 'smallint'), + array(Schema::TYPE_BOOLEAN . ' NOT NULL DEFAULT 1', 'smallint NOT NULL DEFAULT 1'), + array(Schema::TYPE_MONEY, 'decimal(19,4)'), + array(Schema::TYPE_MONEY . '(16,2)', 'decimal(16,2)'), + array(Schema::TYPE_MONEY . ' CHECK (value > 0.0)', 'decimal(19,4) CHECK (value > 0.0)'), + array(Schema::TYPE_MONEY . '(16,2) CHECK (value > 0.0)', 'decimal(16,2) CHECK (value > 0.0)'), + array(Schema::TYPE_MONEY . ' NOT NULL', 'decimal(19,4) NOT NULL'), + ); + } + +} diff --git a/tests/unit/framework/db/cubrid/CubridQueryTest.php b/tests/unit/framework/db/cubrid/CubridQueryTest.php new file mode 100644 index 0000000..b7c9009 --- /dev/null +++ b/tests/unit/framework/db/cubrid/CubridQueryTest.php @@ -0,0 +1,13 @@ +driverName = 'sqlsrv'; - parent::setUp(); - } + protected $driverName = 'sqlsrv'; } diff --git a/tests/unit/framework/db/mssql/MssqlCommandTest.php b/tests/unit/framework/db/mssql/MssqlCommandTest.php index e27fcee..86f7f45 100644 --- a/tests/unit/framework/db/mssql/MssqlCommandTest.php +++ b/tests/unit/framework/db/mssql/MssqlCommandTest.php @@ -4,13 +4,13 @@ namespace yiiunit\framework\db\mssql; use yiiunit\framework\db\CommandTest; +/** + * @group db + * @group mssql + */ class MssqlCommandTest extends CommandTest { - public function setUp() - { - $this->driverName = 'sqlsrv'; - parent::setUp(); - } + protected $driverName = 'sqlsrv'; public function testAutoQuoting() { diff --git a/tests/unit/framework/db/mssql/MssqlConnectionTest.php b/tests/unit/framework/db/mssql/MssqlConnectionTest.php index 7bbaae7..6531f83 100644 --- a/tests/unit/framework/db/mssql/MssqlConnectionTest.php +++ b/tests/unit/framework/db/mssql/MssqlConnectionTest.php @@ -4,13 +4,13 @@ namespace yiiunit\framework\db\mssql; use yiiunit\framework\db\ConnectionTest; +/** + * @group db + * @group mssql + */ class MssqlConnectionTest extends ConnectionTest { - public function setUp() - { - $this->driverName = 'sqlsrv'; - parent::setUp(); - } + protected $driverName = 'sqlsrv'; public function testQuoteValue() { diff --git a/tests/unit/framework/db/mssql/MssqlQueryTest.php b/tests/unit/framework/db/mssql/MssqlQueryTest.php index 4f37c14..a2cb019 100644 --- a/tests/unit/framework/db/mssql/MssqlQueryTest.php +++ b/tests/unit/framework/db/mssql/MssqlQueryTest.php @@ -4,11 +4,11 @@ namespace yiiunit\framework\db\mssql; use yiiunit\framework\db\QueryTest; +/** + * @group db + * @group mssql + */ class MssqlQueryTest extends QueryTest { - public function setUp() - { - $this->driverName = 'sqlsrv'; - parent::setUp(); - } + protected $driverName = 'sqlsrv'; } diff --git a/tests/unit/framework/db/pgsql/PostgreSQLActiveRecordTest.php b/tests/unit/framework/db/pgsql/PostgreSQLActiveRecordTest.php index 2836223..1fffad7 100644 --- a/tests/unit/framework/db/pgsql/PostgreSQLActiveRecordTest.php +++ b/tests/unit/framework/db/pgsql/PostgreSQLActiveRecordTest.php @@ -4,11 +4,11 @@ namespace yiiunit\framework\db\pgsql; use yiiunit\framework\db\ActiveRecordTest; +/** + * @group db + * @group pgsql + */ class PostgreSQLActiveRecordTest extends ActiveRecordTest { - protected function setUp() - { - $this->driverName = 'pgsql'; - parent::setUp(); - } + protected $driverName = 'pgsql'; } diff --git a/tests/unit/framework/db/pgsql/PostgreSQLConnectionTest.php b/tests/unit/framework/db/pgsql/PostgreSQLConnectionTest.php index 7ac65c5..26ac0e0 100644 --- a/tests/unit/framework/db/pgsql/PostgreSQLConnectionTest.php +++ b/tests/unit/framework/db/pgsql/PostgreSQLConnectionTest.php @@ -3,13 +3,13 @@ namespace yiiunit\framework\db\pgsql; use yiiunit\framework\db\ConnectionTest; +/** + * @group db + * @group pgsql + */ class PostgreSQLConnectionTest extends ConnectionTest { - public function setUp() - { - $this->driverName = 'pgsql'; - parent::setUp(); - } + protected $driverName = 'pgsql'; public function testConnection() { diff --git a/tests/unit/framework/db/pgsql/PostgreSQLQueryBuilderTest.php b/tests/unit/framework/db/pgsql/PostgreSQLQueryBuilderTest.php index 7c31190..3ef329e 100644 --- a/tests/unit/framework/db/pgsql/PostgreSQLQueryBuilderTest.php +++ b/tests/unit/framework/db/pgsql/PostgreSQLQueryBuilderTest.php @@ -2,22 +2,24 @@ namespace yiiunit\framework\db\pgsql; -use yii\base\NotSupportedException; use yii\db\pgsql\Schema; use yiiunit\framework\db\QueryBuilderTest; +/** + * @group db + * @group pgsql + */ class PostgreSQLQueryBuilderTest extends QueryBuilderTest { - public $driverName = 'pgsql'; public function columnTypes() { return array( - array(Schema::TYPE_PK, 'serial not null primary key'), - array(Schema::TYPE_PK . '(8)', 'serial not null primary key'), - array(Schema::TYPE_PK . ' CHECK (value > 5)', 'serial not null primary key CHECK (value > 5)'), - array(Schema::TYPE_PK . '(8) CHECK (value > 5)', 'serial not null primary key CHECK (value > 5)'), + array(Schema::TYPE_PK, 'serial NOT NULL PRIMARY KEY'), + array(Schema::TYPE_PK . '(8)', 'serial NOT NULL PRIMARY KEY'), + array(Schema::TYPE_PK . ' CHECK (value > 5)', 'serial NOT NULL PRIMARY KEY CHECK (value > 5)'), + array(Schema::TYPE_PK . '(8) CHECK (value > 5)', 'serial NOT NULL PRIMARY KEY CHECK (value > 5)'), array(Schema::TYPE_STRING, 'varchar(255)'), array(Schema::TYPE_STRING . '(32)', 'varchar(32)'), array(Schema::TYPE_STRING . ' CHECK (value LIKE "test%")', 'varchar(255) CHECK (value LIKE "test%")'), diff --git a/tests/unit/framework/db/sqlite/SqliteActiveRecordTest.php b/tests/unit/framework/db/sqlite/SqliteActiveRecordTest.php index 2e76162..a689e5d 100644 --- a/tests/unit/framework/db/sqlite/SqliteActiveRecordTest.php +++ b/tests/unit/framework/db/sqlite/SqliteActiveRecordTest.php @@ -3,11 +3,11 @@ namespace yiiunit\framework\db\sqlite; use yiiunit\framework\db\ActiveRecordTest; +/** + * @group db + * @group sqlite + */ class SqliteActiveRecordTest extends ActiveRecordTest { - protected function setUp() - { - $this->driverName = 'sqlite'; - parent::setUp(); - } + protected $driverName = 'sqlite'; } diff --git a/tests/unit/framework/db/sqlite/SqliteCommandTest.php b/tests/unit/framework/db/sqlite/SqliteCommandTest.php index e330c7e..1f9ddc2 100644 --- a/tests/unit/framework/db/sqlite/SqliteCommandTest.php +++ b/tests/unit/framework/db/sqlite/SqliteCommandTest.php @@ -3,13 +3,13 @@ namespace yiiunit\framework\db\sqlite; use yiiunit\framework\db\CommandTest; +/** + * @group db + * @group sqlite + */ class SqliteCommandTest extends CommandTest { - protected function setUp() - { - $this->driverName = 'sqlite'; - parent::setUp(); - } + protected $driverName = 'sqlite'; public function testAutoQuoting() { diff --git a/tests/unit/framework/db/sqlite/SqliteConnectionTest.php b/tests/unit/framework/db/sqlite/SqliteConnectionTest.php index 2065200..e1a2961 100644 --- a/tests/unit/framework/db/sqlite/SqliteConnectionTest.php +++ b/tests/unit/framework/db/sqlite/SqliteConnectionTest.php @@ -3,13 +3,13 @@ namespace yiiunit\framework\db\sqlite; use yiiunit\framework\db\ConnectionTest; +/** + * @group db + * @group sqlite + */ class SqliteConnectionTest extends ConnectionTest { - protected function setUp() - { - $this->driverName = 'sqlite'; - parent::setUp(); - } + protected $driverName = 'sqlite'; public function testConstruct() { diff --git a/tests/unit/framework/db/sqlite/SqliteQueryBuilderTest.php b/tests/unit/framework/db/sqlite/SqliteQueryBuilderTest.php index 2f6b164..b20acad 100644 --- a/tests/unit/framework/db/sqlite/SqliteQueryBuilderTest.php +++ b/tests/unit/framework/db/sqlite/SqliteQueryBuilderTest.php @@ -2,13 +2,16 @@ namespace yiiunit\framework\db\sqlite; -use yii\base\NotSupportedException; use yii\db\sqlite\Schema; use yiiunit\framework\db\QueryBuilderTest; +/** + * @group db + * @group sqlite + */ class SqliteQueryBuilderTest extends QueryBuilderTest { - public $driverName = 'sqlite'; + protected $driverName = 'sqlite'; public function columnTypes() { @@ -73,9 +76,9 @@ class SqliteQueryBuilderTest extends QueryBuilderTest ); } - public function testAddDropPrimayKey() + public function testAddDropPrimaryKey() { $this->setExpectedException('yii\base\NotSupportedException'); - parent::testAddDropPrimayKey(); + parent::testAddDropPrimaryKey(); } } diff --git a/tests/unit/framework/db/sqlite/SqliteQueryTest.php b/tests/unit/framework/db/sqlite/SqliteQueryTest.php index ebbb1bb..f1db36b 100644 --- a/tests/unit/framework/db/sqlite/SqliteQueryTest.php +++ b/tests/unit/framework/db/sqlite/SqliteQueryTest.php @@ -3,11 +3,11 @@ namespace yiiunit\framework\db\sqlite; use yiiunit\framework\db\QueryTest; +/** + * @group db + * @group sqlite + */ class SqliteQueryTest extends QueryTest { - protected function setUp() - { - $this->driverName = 'sqlite'; - parent::setUp(); - } + protected $driverName = 'sqlite'; } diff --git a/tests/unit/framework/db/sqlite/SqliteSchemaTest.php b/tests/unit/framework/db/sqlite/SqliteSchemaTest.php new file mode 100644 index 0000000..260bb4c --- /dev/null +++ b/tests/unit/framework/db/sqlite/SqliteSchemaTest.php @@ -0,0 +1,13 @@ +assertEquals(array($dirName . DIRECTORY_SEPARATOR . $fileName), $foundFiles); } - public function testMkdir() + public function testCreateDirectory() { $basePath = $this->testFilePath; $dirName = $basePath . DIRECTORY_SEPARATOR . 'test_dir_level_1' . DIRECTORY_SEPARATOR . 'test_dir_level_2'; - $this->assertTrue(FileHelper::mkdir($dirName), 'FileHelper::mkdir should return true if directory was created!'); + $this->assertTrue(FileHelper::createDirectory($dirName), 'FileHelper::createDirectory should return true if directory was created!'); $this->assertTrue(file_exists($dirName), 'Unable to create directory recursively!'); - $this->assertTrue(FileHelper::mkdir($dirName), 'FileHelper::mkdir should return true for already existing directories!'); + $this->assertTrue(FileHelper::createDirectory($dirName), 'FileHelper::createDirectory should return true for already existing directories!'); } public function testGetMimeTypeByExtension() diff --git a/tests/unit/framework/helpers/HtmlTest.php b/tests/unit/framework/helpers/HtmlTest.php index 6d725de..857f9c2 100644 --- a/tests/unit/framework/helpers/HtmlTest.php +++ b/tests/unit/framework/helpers/HtmlTest.php @@ -6,6 +6,9 @@ use Yii; use yii\helpers\Html; use yiiunit\TestCase; +/** + * @group helpers + */ class HtmlTest extends TestCase { protected function setUp() diff --git a/tests/unit/framework/helpers/InflectorTest.php b/tests/unit/framework/helpers/InflectorTest.php index 732c10d..de7fe01 100644 --- a/tests/unit/framework/helpers/InflectorTest.php +++ b/tests/unit/framework/helpers/InflectorTest.php @@ -6,6 +6,9 @@ use Yii; use yii\helpers\Inflector; use yiiunit\TestCase; +/** + * @group helpers + */ class InflectorTest extends TestCase { public function testPluralize() diff --git a/tests/unit/framework/helpers/JsonTest.php b/tests/unit/framework/helpers/JsonTest.php index 3734744..df2ca5f 100644 --- a/tests/unit/framework/helpers/JsonTest.php +++ b/tests/unit/framework/helpers/JsonTest.php @@ -7,6 +7,9 @@ use yii\helpers\Json; use yii\test\TestCase; use yii\web\JsExpression; +/** + * @group helpers + */ class JsonTest extends TestCase { public function testEncode() diff --git a/tests/unit/framework/helpers/StringHelperTest.php b/tests/unit/framework/helpers/StringHelperTest.php index fe6a96c..8af731d 100644 --- a/tests/unit/framework/helpers/StringHelperTest.php +++ b/tests/unit/framework/helpers/StringHelperTest.php @@ -6,6 +6,7 @@ use yii\test\TestCase; /** * StringHelperTest + * @group helpers */ class StringHelperTest extends TestCase { diff --git a/tests/unit/framework/helpers/VarDumperTest.php b/tests/unit/framework/helpers/VarDumperTest.php index 2b40b63..d41a69d 100644 --- a/tests/unit/framework/helpers/VarDumperTest.php +++ b/tests/unit/framework/helpers/VarDumperTest.php @@ -4,6 +4,9 @@ namespace yiiunit\framework\helpers; use \yii\helpers\VarDumper; use yii\test\TestCase; +/** + * @group helpers + */ class VarDumperTest extends TestCase { public function testDumpObject() diff --git a/tests/unit/framework/i18n/FormatterTest.php b/tests/unit/framework/i18n/FormatterTest.php index c13fff3..6966853 100644 --- a/tests/unit/framework/i18n/FormatterTest.php +++ b/tests/unit/framework/i18n/FormatterTest.php @@ -13,6 +13,7 @@ use yiiunit\TestCase; /** * @author Qiang Xue * @since 2.0 + * @group i18n */ class FormatterTest extends TestCase { diff --git a/tests/unit/framework/i18n/GettextMessageSourceTest.php b/tests/unit/framework/i18n/GettextMessageSourceTest.php index 7b499f4..d039629 100644 --- a/tests/unit/framework/i18n/GettextMessageSourceTest.php +++ b/tests/unit/framework/i18n/GettextMessageSourceTest.php @@ -5,6 +5,9 @@ namespace yiiunit\framework\i18n; use yii\i18n\GettextMessageSource; use yiiunit\TestCase; +/** + * @group i18n + */ class GettextMessageSourceTest extends TestCase { public function testLoadMessages() diff --git a/tests/unit/framework/i18n/GettextMoFileTest.php b/tests/unit/framework/i18n/GettextMoFileTest.php index 0aa22da..9b61145 100644 --- a/tests/unit/framework/i18n/GettextMoFileTest.php +++ b/tests/unit/framework/i18n/GettextMoFileTest.php @@ -5,6 +5,9 @@ namespace yiiunit\framework\i18n; use yii\i18n\GettextMoFile; use yiiunit\TestCase; +/** + * @group i18n + */ class GettextMoFileTest extends TestCase { public function testLoad() diff --git a/tests/unit/framework/i18n/GettextPoFileTest.php b/tests/unit/framework/i18n/GettextPoFileTest.php index 8dddb40..4165b81 100644 --- a/tests/unit/framework/i18n/GettextPoFileTest.php +++ b/tests/unit/framework/i18n/GettextPoFileTest.php @@ -5,6 +5,9 @@ namespace yiiunit\framework\i18n; use yii\i18n\GettextPoFile; use yiiunit\TestCase; +/** + * @group i18n + */ class GettextPoFileTest extends TestCase { public function testLoad() diff --git a/tests/unit/framework/rbac/PhpManagerTest.php b/tests/unit/framework/rbac/PhpManagerTest.php index b3b7c4f..8c5d366 100644 --- a/tests/unit/framework/rbac/PhpManagerTest.php +++ b/tests/unit/framework/rbac/PhpManagerTest.php @@ -5,6 +5,9 @@ namespace yiiunit\framework\rbac; use Yii; use yii\rbac\PhpManager; +/** + * @group rbac + */ class PhpManagerTest extends ManagerTestCase { protected function setUp() diff --git a/tests/unit/framework/requirements/YiiRequirementCheckerTest.php b/tests/unit/framework/requirements/YiiRequirementCheckerTest.php index 7554729..652d003 100644 --- a/tests/unit/framework/requirements/YiiRequirementCheckerTest.php +++ b/tests/unit/framework/requirements/YiiRequirementCheckerTest.php @@ -7,6 +7,7 @@ use yiiunit\TestCase; /** * Test case for [[YiiRequirementChecker]]. * @see YiiRequirementChecker + * @group requirements */ class YiiRequirementCheckerTest extends TestCase { diff --git a/tests/unit/framework/validators/EmailValidatorTest.php b/tests/unit/framework/validators/EmailValidatorTest.php index 5807aed..b33a809 100644 --- a/tests/unit/framework/validators/EmailValidatorTest.php +++ b/tests/unit/framework/validators/EmailValidatorTest.php @@ -6,6 +6,7 @@ use yiiunit\TestCase; /** * EmailValidatorTest + * @group validators */ class EmailValidatorTest extends TestCase { diff --git a/tests/unit/framework/web/ResponseTest.php b/tests/unit/framework/web/ResponseTest.php index 41ed939..2a9b4bf 100644 --- a/tests/unit/framework/web/ResponseTest.php +++ b/tests/unit/framework/web/ResponseTest.php @@ -13,6 +13,9 @@ class MockResponse extends \yii\web\Response } } +/** + * @group web + */ class ResponseTest extends \yiiunit\TestCase { /** diff --git a/tests/unit/framework/web/UrlManagerTest.php b/tests/unit/framework/web/UrlManagerTest.php index efa6695..a77a66d 100644 --- a/tests/unit/framework/web/UrlManagerTest.php +++ b/tests/unit/framework/web/UrlManagerTest.php @@ -5,6 +5,9 @@ use yii\web\Request; use yii\web\UrlManager; use yiiunit\TestCase; +/** + * @group web + */ class UrlManagerTest extends TestCase { protected function setUp() diff --git a/tests/unit/framework/web/UrlRuleTest.php b/tests/unit/framework/web/UrlRuleTest.php index d67dc58..0a0def4 100644 --- a/tests/unit/framework/web/UrlRuleTest.php +++ b/tests/unit/framework/web/UrlRuleTest.php @@ -7,6 +7,9 @@ use yii\web\UrlRule; use yii\web\Request; use yiiunit\TestCase; +/** + * @group web + */ class UrlRuleTest extends TestCase { public function testCreateUrl() diff --git a/tests/unit/framework/web/XmlResponseFormatterTest.php b/tests/unit/framework/web/XmlResponseFormatterTest.php index 590caef..e97962a 100644 --- a/tests/unit/framework/web/XmlResponseFormatterTest.php +++ b/tests/unit/framework/web/XmlResponseFormatterTest.php @@ -26,6 +26,8 @@ class Post extends Object /** * @author Qiang Xue * @since 2.0 + * + * @group web */ class XmlResponseFormatterTest extends \yiiunit\TestCase { diff --git a/tests/unit/framework/widgets/SpacelessTest.php b/tests/unit/framework/widgets/SpacelessTest.php index 6b2cf45..00f5a96 100644 --- a/tests/unit/framework/widgets/SpacelessTest.php +++ b/tests/unit/framework/widgets/SpacelessTest.php @@ -4,6 +4,9 @@ namespace yiiunit\framework\widgets; use yii\widgets\Spaceless; +/** + * @group widgets + */ class SpacelessTest extends \yiiunit\TestCase { public function testWidget()