Commit 0aab6ded authored by Antonio Ramirez's avatar Antonio Ramirez

Merge remote-tracking branch 'upstream/master' into 364-toAscii

* upstream/master: (91 commits)
  fixed init.bat paths
  renamed backstage → backend
  Fixed test break.
  Response WIP
  coding style fix.
  [1] Redone missing code. [2] Added empty line at the end of file [3] Removed exception.
  Updated code style. braces on the same line for control statements.
  Removed unused columsn from find constraint sql. Fixed typo. Added extra schema check for when a foreign table is not in the same schema. Updated indentation to conform to other classes.
  Multilevel Items
  Fixes issue #514.
  Removed the config setting that should not have been commited.
  Removed false exception catching.
  Removed custom pgsql PDO and added defaultSchema as public property.
  CS fixes.
  Minor refactoring of DbMessageSource.
  Response WIP
  Minor refactoring of t().
  Added Jsonable support.
  Fixes #13. Implement DB message source.
  Yii::t() minor fix.
  ...
parents 9ff25805 d5d463f9
...@@ -10,5 +10,6 @@ env: ...@@ -10,5 +10,6 @@ env:
before_script: before_script:
- sh -c "if [ '$DB' = 'mysql' ]; then mysql -e 'create database IF NOT EXISTS yiitest;'; fi" - sh -c "if [ '$DB' = 'mysql' ]; then mysql -e 'create database IF NOT EXISTS yiitest;'; fi"
- psql -U postgres -c 'drop database if exists yiitest;';
- psql -U postgres -c 'create database yiitest;';
script: phpunit script: phpunit
\ No newline at end of file
...@@ -10,7 +10,7 @@ if you have a project to be deployed for production soon. ...@@ -10,7 +10,7 @@ if you have a project to be deployed for production soon.
Thank you for using Yii 2 Advanced Application Template - an application template Thank you for using Yii 2 Advanced Application Template - an application template
that works out-of-box and can be easily customized to fit for your needs. that works out-of-box and can be easily customized to fit for your needs.
Yii 2 Advanced Application Template is best suitable for large projects requiring frontend and backstage separation, Yii 2 Advanced Application Template is best suitable for large projects requiring frontend and backend separation,
deployment in different environments, configuration nesting etc. deployment in different environments, configuration nesting etc.
...@@ -20,18 +20,18 @@ DIRECTORY STRUCTURE ...@@ -20,18 +20,18 @@ DIRECTORY STRUCTURE
``` ```
common common
config/ contains shared configurations config/ contains shared configurations
models/ contains model classes used in both backstage and frontend models/ contains model classes used in both backend and frontend
console console
config/ contains console configurations config/ contains console configurations
controllers/ contains console controllers (commands) controllers/ contains console controllers (commands)
migrations/ contains database migrations migrations/ contains database migrations
models/ contains console-specific model classes models/ contains console-specific model classes
runtime/ contains files generated during runtime runtime/ contains files generated during runtime
backstage backend
assets/ contains application assets such as JavaScript and CSS assets/ contains application assets such as JavaScript and CSS
config/ contains backstage configurations config/ contains backend configurations
controllers/ contains Web controller classes controllers/ contains Web controller classes
models/ contains backstage-specific model classes models/ contains backend-specific model classes
runtime/ contains files generated during runtime runtime/ contains files generated during runtime
views/ contains view files for the Web application views/ contains view files for the Web application
www/ contains the entry script and Web resources www/ contains the entry script and Web resources
...@@ -79,6 +79,21 @@ php composer.phar create-project --stability=dev yiisoft/yii2-app-advanced yii-a ...@@ -79,6 +79,21 @@ php composer.phar create-project --stability=dev yiisoft/yii2-app-advanced yii-a
This is not currently available. We will provide it when Yii 2 is formally released. This is not currently available. We will provide it when Yii 2 is formally released.
### Install from development repository
If you've cloned the [Yii 2 framework main development repository](https://github.com/yiisoft/yii2) you
can bootstrap your application with:
~~~
cd yii2/apps/advanced
php composer.phar create-project
~~~
*Note: If the above command fails with `[RuntimeException] Not enough arguments.` run
`php composer.phar self-update` to obtain an updated version of composer which supports creating projects
from local packages.*
GETTING STARTED GETTING STARTED
--------------- ---------------
...@@ -92,7 +107,7 @@ the installed application. You only need to do these once for all. ...@@ -92,7 +107,7 @@ the installed application. You only need to do these once for all.
Now you should be able to access: Now you should be able to access:
- the frontend using the URL `http://localhost/yii-advanced/frontend/www/` - the frontend using the URL `http://localhost/yii-advanced/frontend/www/`
- the backstage using the URL `http://localhost/yii-advanced/backstage/www/` - the backend using the URL `http://localhost/yii-advanced/backend/www/`
assuming `yii-advanced` is directly under the document root of your Web server. assuming `yii-advanced` is directly under the document root of your Web server.
...@@ -13,7 +13,7 @@ return array( ...@@ -13,7 +13,7 @@ return array(
'basePath' => dirname(__DIR__), 'basePath' => dirname(__DIR__),
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor', 'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'preload' => array('log'), 'preload' => array('log'),
'controllerNamespace' => 'backstage\controllers', 'controllerNamespace' => 'backend\controllers',
'modules' => array( 'modules' => array(
), ),
'components' => array( 'components' => array(
......
<?php <?php
namespace backstage\controllers; namespace backend\controllers;
use Yii; use Yii;
use yii\web\Controller; use yii\web\Controller;
......
...@@ -19,17 +19,14 @@ ...@@ -19,17 +19,14 @@
"yiisoft/yii2-composer": "dev-master" "yiisoft/yii2-composer": "dev-master"
}, },
"scripts": { "scripts": {
"post-install-cmd": [ "post-create-project-cmd": [
"yii\\composer\\InstallHandler::setPermissions"
],
"post-update-cmd": [
"yii\\composer\\InstallHandler::setPermissions" "yii\\composer\\InstallHandler::setPermissions"
] ]
}, },
"extra": { "extra": {
"yii-install-writable": [ "yii-install-writable": [
"backstage/runtime", "backend/runtime",
"backstage/www/assets", "backend/www/assets",
"console/runtime", "console/runtime",
"console/migrations", "console/migrations",
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
"This file locks the dependencies of your project to a known state", "This file locks the dependencies of your project to a known state",
"Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file" "Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file"
], ],
"hash": "05f7bcd0e99931b52415eaeb62d54daf", "hash": "2d1053fbaaf2044054f273a71d0ccde0",
"packages": [ "packages": [
{ {
"name": "yiisoft/yii2", "name": "yiisoft/yii2",
...@@ -11,12 +11,12 @@ ...@@ -11,12 +11,12 @@
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/yiisoft/yii2-framework.git", "url": "https://github.com/yiisoft/yii2-framework.git",
"reference": "2d93f20ba6044ac3f1957300c4ae85fd98ecf47d" "reference": "3ad6334be076a80df3b2ea0b57f38bd0c6901989"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/yiisoft/yii2-framework/zipball/2d93f20ba6044ac3f1957300c4ae85fd98ecf47d", "url": "https://api.github.com/repos/yiisoft/yii2-framework/zipball/3ad6334be076a80df3b2ea0b57f38bd0c6901989",
"reference": "2d93f20ba6044ac3f1957300c4ae85fd98ecf47d", "reference": "3ad6334be076a80df3b2ea0b57f38bd0c6901989",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
...@@ -97,7 +97,7 @@ ...@@ -97,7 +97,7 @@
"framework", "framework",
"yii" "yii"
], ],
"time": "2013-05-29 02:55:14" "time": "2013-06-02 19:19:29"
}, },
{ {
"name": "yiisoft/yii2-composer", "name": "yiisoft/yii2-composer",
......
@echo off @echo off
rem ------------------------------------------------------------- rem -------------------------------------------------------------
rem Yii command line install script for Windows. rem Yii command line init script for Windows.
rem rem
rem @author Qiang Xue <qiang.xue@gmail.com> rem @author Qiang Xue <qiang.xue@gmail.com>
rem @link http://www.yiiframework.com/ rem @link http://www.yiiframework.com/
...@@ -15,6 +15,6 @@ set YII_PATH=%~dp0 ...@@ -15,6 +15,6 @@ set YII_PATH=%~dp0
if "%PHP_COMMAND%" == "" set PHP_COMMAND=php.exe if "%PHP_COMMAND%" == "" set PHP_COMMAND=php.exe
"%PHP_COMMAND%" "%YII_PATH%install" %* "%PHP_COMMAND%" "%YII_PATH%init" %*
@endlocal @endlocal
...@@ -59,3 +59,18 @@ assuming `yii-basic` is directly under the document root of your Web server. ...@@ -59,3 +59,18 @@ assuming `yii-basic` is directly under the document root of your Web server.
### Install from an Archive File ### Install from an Archive File
This is not currently available. We will provide it when Yii 2 is formally released. This is not currently available. We will provide it when Yii 2 is formally released.
### Install from development repository
If you've cloned the [Yii 2 framework main development repository](https://github.com/yiisoft/yii2) you
can bootstrap your application with:
~~~
cd yii2/apps/basic
php composer.phar create-project
~~~
*Note: If the above command fails with `[RuntimeException] Not enough arguments.` run
`php composer.phar self-update` to obtain an updated version of composer which supports creating projects
from local packages.*
...@@ -19,10 +19,7 @@ ...@@ -19,10 +19,7 @@
"yiisoft/yii2-composer": "dev-master" "yiisoft/yii2-composer": "dev-master"
}, },
"scripts": { "scripts": {
"post-install-cmd": [ "post-create-project-cmd": [
"yii\\composer\\InstallHandler::setPermissions"
],
"post-update-cmd": [
"yii\\composer\\InstallHandler::setPermissions" "yii\\composer\\InstallHandler::setPermissions"
] ]
}, },
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
"This file locks the dependencies of your project to a known state", "This file locks the dependencies of your project to a known state",
"Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file" "Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file"
], ],
"hash": "0411dbbd774aa1c89256c77c68023940", "hash": "91ba258de768b93025f86071f3bb4b84",
"packages": [ "packages": [
{ {
"name": "yiisoft/yii2", "name": "yiisoft/yii2",
...@@ -11,12 +11,12 @@ ...@@ -11,12 +11,12 @@
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/yiisoft/yii2-framework.git", "url": "https://github.com/yiisoft/yii2-framework.git",
"reference": "2d93f20ba6044ac3f1957300c4ae85fd98ecf47d" "reference": "3ad6334be076a80df3b2ea0b57f38bd0c6901989"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/yiisoft/yii2-framework/zipball/2d93f20ba6044ac3f1957300c4ae85fd98ecf47d", "url": "https://api.github.com/repos/yiisoft/yii2-framework/zipball/3ad6334be076a80df3b2ea0b57f38bd0c6901989",
"reference": "2d93f20ba6044ac3f1957300c4ae85fd98ecf47d", "reference": "3ad6334be076a80df3b2ea0b57f38bd0c6901989",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
...@@ -97,7 +97,7 @@ ...@@ -97,7 +97,7 @@
"framework", "framework",
"yii" "yii"
], ],
"time": "2013-05-29 02:55:14" "time": "2013-06-02 19:19:29"
}, },
{ {
"name": "yiisoft/yii2-composer", "name": "yiisoft/yii2-composer",
......
...@@ -4,7 +4,6 @@ return array( ...@@ -4,7 +4,6 @@ return array(
'id' => 'bootstrap', 'id' => 'bootstrap',
'basePath' => dirname(__DIR__), 'basePath' => dirname(__DIR__),
'preload' => array('log'), 'preload' => array('log'),
'controllerNamespace' => 'app\controllers',
'modules' => array( 'modules' => array(
// 'debug' => array( // 'debug' => array(
// 'class' => 'yii\debug\Module', // 'class' => 'yii\debug\Module',
......
...@@ -20,6 +20,7 @@ class SiteController extends Controller ...@@ -20,6 +20,7 @@ class SiteController extends Controller
public function actionIndex() public function actionIndex()
{ {
Yii::$app->end(0, false);
echo $this->render('index'); echo $this->render('index');
} }
......
...@@ -82,7 +82,7 @@ class InstallHandler ...@@ -82,7 +82,7 @@ class InstallHandler
throw new Exception("Config file does not exist: $configFile"); throw new Exception("Config file does not exist: $configFile");
} }
require(__DIR__ . '/../../../yii2/yii/Yii.php'); require_once(__DIR__ . '/../../../yii2/yii/Yii.php');
$application = new Application(require($configFile)); $application = new Application(require($configFile));
$request = $application->getRequest(); $request = $application->getRequest();
......
...@@ -26,12 +26,12 @@ class ViewRenderer extends BaseViewRenderer ...@@ -26,12 +26,12 @@ class ViewRenderer extends BaseViewRenderer
/** /**
* @var string the directory or path alias pointing to where Smarty cache will be stored. * @var string the directory or path alias pointing to where Smarty cache will be stored.
*/ */
public $cachePath = '@app/runtime/Smarty/cache'; public $cachePath = '@runtime/Smarty/cache';
/** /**
* @var string the directory or path alias pointing to where Smarty compiled templates will be stored. * @var string the directory or path alias pointing to where Smarty compiled templates will be stored.
*/ */
public $compilePath = '@app/runtime/Smarty/compile'; public $compilePath = '@runtime/Smarty/compile';
/** /**
* @var Smarty * @var Smarty
......
...@@ -25,7 +25,7 @@ class ViewRenderer extends BaseViewRenderer ...@@ -25,7 +25,7 @@ class ViewRenderer extends BaseViewRenderer
/** /**
* @var string the directory or path alias pointing to where Twig cache will be stored. * @var string the directory or path alias pointing to where Twig cache will be stored.
*/ */
public $cachePath = '@app/runtime/Twig/cache'; public $cachePath = '@runtime/Twig/cache';
/** /**
* @var array Twig options * @var array Twig options
......
...@@ -606,11 +606,36 @@ class YiiBase ...@@ -606,11 +606,36 @@ class YiiBase
public static function t($category, $message, $params = array(), $language = null) public static function t($category, $message, $params = array(), $language = null)
{ {
if (self::$app !== null) { if (self::$app !== null) {
return self::$app->getI18N()->translate($category, $message, $params, $language); return self::$app->getI18N()->translate($category, $message, $params, $language ?: self::$app->language);
} else { } else {
return is_array($params) ? strtr($message, $params) : $message; return is_array($params) ? strtr($message, $params) : $message;
} }
} }
/**
* Configures an object with the initial property values.
* @param object $object the object to be configured
* @param array $properties the property initial values given in terms of name-value pairs.
*/
public static function configure($object, $properties)
{
foreach ($properties as $name => $value) {
$object->$name = $value;
}
}
/**
* Returns the public member variables of an object.
* This method is provided such that we can get the public member variables of an object.
* It is different from "get_object_vars()" because the latter will return private
* and protected variables if it is called within the object itself.
* @param object $object the object to be handled
* @return array the public member variables of the object
*/
public static function getObjectVars($object)
{
return get_object_vars($object);
}
} }
YiiBase::$aliases = array( YiiBase::$aliases = array(
......
...@@ -72,30 +72,51 @@ class Application extends Module ...@@ -72,30 +72,51 @@ class Application extends Module
public function __construct($config = array()) public function __construct($config = array())
{ {
Yii::$app = $this; Yii::$app = $this;
if (!isset($config['id'])) { if (!isset($config['id'])) {
throw new InvalidConfigException('The "id" configuration is required.'); throw new InvalidConfigException('The "id" configuration is required.');
} }
if (isset($config['basePath'])) { if (isset($config['basePath'])) {
$this->setBasePath($config['basePath']); $this->setBasePath($config['basePath']);
Yii::setAlias('@app', $this->getBasePath());
unset($config['basePath']); unset($config['basePath']);
} else { } else {
throw new InvalidConfigException('The "basePath" configuration is required.'); throw new InvalidConfigException('The "basePath" configuration is required.');
} }
$this->preInit($config);
$this->registerErrorHandlers();
$this->registerCoreComponents();
Component::__construct($config);
}
/**
* Pre-initializes the application.
* This method is called at the beginning of the application constructor.
* @param array $config the application configuration
*/
public function preInit(&$config)
{
if (isset($config['vendorPath'])) {
$this->setVendorPath($config['vendorPath']);
unset($config['vendorPath']);
} else {
// set "@vendor"
$this->getVendorPath();
}
if (isset($config['runtimePath'])) {
$this->setRuntimePath($config['runtimePath']);
unset($config['runtimePath']);
} else {
// set "@runtime"
$this->getRuntimePath();
}
if (isset($config['timeZone'])) { if (isset($config['timeZone'])) {
$this->setTimeZone($config['timeZone']); $this->setTimeZone($config['timeZone']);
unset($config['timeZone']); unset($config['timeZone']);
} elseif (!ini_get('date.timezone')) { } elseif (!ini_get('date.timezone')) {
$this->setTimeZone('UTC'); $this->setTimeZone('UTC');
} }
$this->registerErrorHandlers();
$this->registerCoreComponents();
Component::__construct($config);
} }
/** /**
...@@ -107,6 +128,11 @@ class Application extends Module ...@@ -107,6 +128,11 @@ class Application extends Module
ini_set('display_errors', 0); ini_set('display_errors', 0);
set_exception_handler(array($this, 'handleException')); set_exception_handler(array($this, 'handleException'));
set_error_handler(array($this, 'handleError'), error_reporting()); set_error_handler(array($this, 'handleError'), error_reporting());
// Allocating twice more than required to display memory exhausted error
// in case of trying to allocate last 1 byte while all memory is taken.
$this->_memoryReserve = str_repeat('x', 1024 * 256);
register_shutdown_function(array($this, 'end'), 0, false);
register_shutdown_function(array($this, 'handleFatalError'));
} }
} }
...@@ -121,11 +147,10 @@ class Application extends Module ...@@ -121,11 +147,10 @@ class Application extends Module
{ {
if (!$this->_ended) { if (!$this->_ended) {
$this->_ended = true; $this->_ended = true;
$this->getResponse()->end();
$this->afterRequest(); $this->afterRequest();
} }
$this->handleFatalError();
if ($exit) { if ($exit) {
exit($status); exit($status);
} }
...@@ -139,11 +164,10 @@ class Application extends Module ...@@ -139,11 +164,10 @@ class Application extends Module
public function run() public function run()
{ {
$this->beforeRequest(); $this->beforeRequest();
// Allocating twice more than required to display memory exhausted error $response = $this->getResponse();
// in case of trying to allocate last 1 byte while all memory is taken. $response->begin();
$this->_memoryReserve = str_repeat('x', 1024 * 256);
register_shutdown_function(array($this, 'end'), 0, false);
$status = $this->processRequest(); $status = $this->processRequest();
$response->end();
$this->afterRequest(); $this->afterRequest();
return $status; return $status;
} }
...@@ -178,7 +202,8 @@ class Application extends Module ...@@ -178,7 +202,8 @@ class Application extends Module
/** /**
* Returns the directory that stores runtime files. * Returns the directory that stores runtime files.
* @return string the directory that stores runtime files. Defaults to 'protected/runtime'. * @return string the directory that stores runtime files.
* Defaults to the "runtime" subdirectory under [[basePath]].
*/ */
public function getRuntimePath() public function getRuntimePath()
{ {
...@@ -191,16 +216,11 @@ class Application extends Module ...@@ -191,16 +216,11 @@ class Application extends Module
/** /**
* Sets the directory that stores runtime files. * Sets the directory that stores runtime files.
* @param string $path the directory that stores runtime files. * @param string $path the directory that stores runtime files.
* @throws InvalidConfigException if the directory does not exist or is not writable
*/ */
public function setRuntimePath($path) public function setRuntimePath($path)
{ {
$path = Yii::getAlias($path); $this->_runtimePath = Yii::getAlias($path);
if (is_dir($path) && is_writable($path)) { Yii::setAlias('@runtime', $this->_runtimePath);
$this->_runtimePath = $path;
} else {
throw new InvalidConfigException("Runtime path must be a directory writable by the Web server process: $path");
}
} }
private $_vendorPath; private $_vendorPath;
...@@ -208,7 +228,7 @@ class Application extends Module ...@@ -208,7 +228,7 @@ class Application extends Module
/** /**
* Returns the directory that stores vendor files. * Returns the directory that stores vendor files.
* @return string the directory that stores vendor files. * @return string the directory that stores vendor files.
* Defaults to 'vendor' directory under applications [[basePath]]. * Defaults to "vendor" directory under [[basePath]].
*/ */
public function getVendorPath() public function getVendorPath()
{ {
...@@ -225,6 +245,7 @@ class Application extends Module ...@@ -225,6 +245,7 @@ class Application extends Module
public function setVendorPath($path) public function setVendorPath($path)
{ {
$this->_vendorPath = Yii::getAlias($path); $this->_vendorPath = Yii::getAlias($path);
Yii::setAlias('@vendor', $this->_vendorPath);
} }
/** /**
...@@ -296,6 +317,15 @@ class Application extends Module ...@@ -296,6 +317,15 @@ class Application extends Module
return $this->getComponent('request'); return $this->getComponent('request');
} }
/**
* Returns the response component.
* @return \yii\web\Response|\yii\console\Response the response component
*/
public function getResponse()
{
return $this->getComponent('response');
}
/** /**
* Returns the view object. * Returns the view object.
* @return View the view object that is used to render various view files. * @return View the view object that is used to render various view files.
......
...@@ -82,11 +82,12 @@ class ErrorHandler extends Component ...@@ -82,11 +82,12 @@ class ErrorHandler extends Component
} elseif (!(Yii::$app instanceof \yii\web\Application)) { } elseif (!(Yii::$app instanceof \yii\web\Application)) {
Yii::$app->renderException($exception); Yii::$app->renderException($exception);
} else { } else {
$response = Yii::$app->getResponse();
if (!headers_sent()) { if (!headers_sent()) {
if ($exception instanceof HttpException) { if ($exception instanceof HttpException) {
header('HTTP/1.0 ' . $exception->statusCode . ' ' . $exception->getName()); $response->setStatusCode($exception->statusCode);
} else { } else {
header('HTTP/1.0 500 ' . get_class($exception)); $response->setStatusCode(500);
} }
} }
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') { if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
...@@ -100,13 +101,13 @@ class ErrorHandler extends Component ...@@ -100,13 +101,13 @@ class ErrorHandler extends Component
$view = new View(); $view = new View();
$request = ''; $request = '';
foreach (array('GET', 'POST', 'SERVER', 'FILES', 'COOKIE', 'SESSION', 'ENV') as $name) { foreach (array('_GET', '_POST', '_SERVER', '_FILES', '_COOKIE', '_SESSION', '_ENV') as $name) {
if (!empty($GLOBALS['_' . $name])) { if (!empty($GLOBALS[$name])) {
$request .= '$_' . $name . ' = ' . var_export($GLOBALS['_' . $name], true) . ";\n\n"; $request .= '$' . $name . ' = ' . var_export($GLOBALS[$name], true) . ";\n\n";
} }
} }
$request = rtrim($request, "\n\n"); $request = rtrim($request, "\n\n");
echo $view->renderFile($this->mainView, array( $response->content = $view->renderFile($this->mainView, array(
'exception' => $exception, 'exception' => $exception,
'request' => $request, 'request' => $request,
), $this); ), $this);
...@@ -255,7 +256,7 @@ class ErrorHandler extends Component ...@@ -255,7 +256,7 @@ class ErrorHandler extends Component
if (isset($_SERVER['SERVER_SOFTWARE'])) { if (isset($_SERVER['SERVER_SOFTWARE'])) {
foreach ($serverUrls as $url => $keywords) { foreach ($serverUrls as $url => $keywords) {
foreach ($keywords as $keyword) { foreach ($keywords as $keyword) {
if (stripos($_SERVER['SERVER_SOFTWARE'], $keyword) !== false ) { if (stripos($_SERVER['SERVER_SOFTWARE'], $keyword) !== false) {
return '<a href="' . $url . '" target="_blank">' . $this->htmlEncode($_SERVER['SERVER_SOFTWARE']) . '</a>'; return '<a href="' . $url . '" target="_blank">' . $this->htmlEncode($_SERVER['SERVER_SOFTWARE']) . '</a>';
} }
} }
......
...@@ -12,7 +12,6 @@ use DateTime; ...@@ -12,7 +12,6 @@ use DateTime;
use yii\helpers\HtmlPurifier; use yii\helpers\HtmlPurifier;
use yii\helpers\Html; use yii\helpers\Html;
/** /**
* Formatter provides a set of commonly used data formatting methods. * Formatter provides a set of commonly used data formatting methods.
* *
...@@ -39,17 +38,19 @@ class Formatter extends Component ...@@ -39,17 +38,19 @@ class Formatter extends Component
public $datetimeFormat = 'Y/m/d h:i:s A'; public $datetimeFormat = 'Y/m/d h:i:s A';
/** /**
* @var array the text to be displayed when formatting a boolean value. The first element corresponds * @var array the text to be displayed when formatting a boolean value. The first element corresponds
* to the text display for false, the second element for true. Defaults to <code>array('No', 'Yes')</code>. * to the text display for false, the second element for true. Defaults to `array('No', 'Yes')`.
*/ */
public $booleanFormat; public $booleanFormat;
/** /**
* @var string the character displayed as the decimal point when formatting a number. * @var string the character displayed as the decimal point when formatting a number.
* If not set, "." will be used.
*/ */
public $decimalSeparator = '.'; public $decimalSeparator;
/** /**
* @var string the character displayed as the thousands separator character when formatting a number. * @var string the character displayed as the thousands separator character when formatting a number.
* If not set, "," will be used.
*/ */
public $thousandSeparator = ','; public $thousandSeparator;
/** /**
...@@ -273,8 +274,12 @@ class Formatter extends Component ...@@ -273,8 +274,12 @@ class Formatter extends Component
*/ */
public function asDouble($value, $decimals = 2) public function asDouble($value, $decimals = 2)
{ {
if ($this->decimalSeparator === null) {
return sprintf("%.{$decimals}f", $value);
} else {
return str_replace('.', $this->decimalSeparator, sprintf("%.{$decimals}f", $value)); return str_replace('.', $this->decimalSeparator, sprintf("%.{$decimals}f", $value));
} }
}
/** /**
* Formats the value as a number with decimal and thousand separators. * Formats the value as a number with decimal and thousand separators.
...@@ -287,6 +292,8 @@ class Formatter extends Component ...@@ -287,6 +292,8 @@ class Formatter extends Component
*/ */
public function asNumber($value, $decimals = 0) public function asNumber($value, $decimals = 0)
{ {
return number_format($value, $decimals, $this->decimalSeparator, $this->thousandSeparator); $ds = isset($this->decimalSeparator) ? $this->decimalSeparator: '.';
$ts = isset($this->thousandSeparator) ? $this->thousandSeparator: ',';
return number_format($value, $decimals, $ds, $ts);
} }
} }
...@@ -7,6 +7,7 @@ ...@@ -7,6 +7,7 @@
namespace yii\base; namespace yii\base;
/** /**
* HttpException represents an exception caused by an improper request of the end-user. * HttpException represents an exception caused by an improper request of the end-user.
* *
...@@ -42,66 +43,8 @@ class HttpException extends UserException ...@@ -42,66 +43,8 @@ class HttpException extends UserException
*/ */
public function getName() public function getName()
{ {
static $httpCodes = array( if (isset(\yii\web\Response::$statusTexts[$this->statusCode])) {
100 => 'Continue', return \yii\web\Response::$statusTexts[$this->statusCode];
101 => 'Switching Protocols',
102 => 'Processing',
118 => 'Connection timed out',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
207 => 'Multi-Status',
210 => 'Content Different',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
307 => 'Temporary Redirect',
310 => 'Too many Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Time-out',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested range unsatisfiable',
417 => 'Expectation failed',
418 => 'I’m a teapot',
422 => 'Unprocessable entity',
423 => 'Locked',
424 => 'Method failure',
425 => 'Unordered Collection',
426 => 'Upgrade Required',
449 => 'Retry With',
450 => 'Blocked by Windows Parental Controls',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway ou Proxy Error',
503 => 'Service Unavailable',
504 => 'Gateway Time-out',
505 => 'HTTP Version not supported',
507 => 'Insufficient storage',
509 => 'Bandwidth Limit Exceeded',
);
if (isset($httpCodes[$this->statusCode])) {
return $httpCodes[$this->statusCode];
} else { } else {
return 'Error'; return 'Error';
} }
......
...@@ -23,4 +23,3 @@ class InvalidCallException extends Exception ...@@ -23,4 +23,3 @@ class InvalidCallException extends Exception
return \Yii::t('yii', 'Invalid Call'); return \Yii::t('yii', 'Invalid Call');
} }
} }
...@@ -23,4 +23,3 @@ class InvalidConfigException extends Exception ...@@ -23,4 +23,3 @@ class InvalidConfigException extends Exception
return \Yii::t('yii', 'Invalid Configuration'); return \Yii::t('yii', 'Invalid Configuration');
} }
} }
...@@ -23,4 +23,3 @@ class InvalidParamException extends Exception ...@@ -23,4 +23,3 @@ class InvalidParamException extends Exception
return \Yii::t('yii', 'Invalid Parameter'); return \Yii::t('yii', 'Invalid Parameter');
} }
} }
...@@ -23,4 +23,3 @@ class InvalidRouteException extends UserException ...@@ -23,4 +23,3 @@ class InvalidRouteException extends UserException
return \Yii::t('yii', 'Invalid Route'); return \Yii::t('yii', 'Invalid Route');
} }
} }
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\base;
/**
* Jsonable should be implemented by classes that need to be represented in JSON format.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
interface Jsonable
{
/**
* @return string the JSON representation of this object
*/
public function toJson();
}
...@@ -10,6 +10,7 @@ namespace yii\base; ...@@ -10,6 +10,7 @@ namespace yii\base;
use ArrayObject; use ArrayObject;
use ArrayIterator; use ArrayIterator;
use yii\helpers\Inflector; use yii\helpers\Inflector;
use yii\helpers\Json;
use yii\validators\RequiredValidator; use yii\validators\RequiredValidator;
use yii\validators\Validator; use yii\validators\Validator;
...@@ -41,7 +42,7 @@ use yii\validators\Validator; ...@@ -41,7 +42,7 @@ use yii\validators\Validator;
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
class Model extends Component implements \IteratorAggregate, \ArrayAccess class Model extends Component implements \IteratorAggregate, \ArrayAccess, Jsonable
{ {
/** /**
* @event ModelEvent an event raised at the beginning of [[validate()]]. You may set * @event ModelEvent an event raised at the beginning of [[validate()]]. You may set
...@@ -637,6 +638,16 @@ class Model extends Component implements \IteratorAggregate, \ArrayAccess ...@@ -637,6 +638,16 @@ class Model extends Component implements \IteratorAggregate, \ArrayAccess
return $attributes; return $attributes;
} }
/**
* Returns the JSON representation of this object.
* The default implementation will return [[attributes]].
* @return string the JSON representation of this object.
*/
public function toJson()
{
return Json::encode($this->getAttributes());
}
/** /**
* Returns an iterator for traversing the attributes in the model. * Returns an iterator for traversing the attributes in the model.
* This method is required by the interface IteratorAggregate. * This method is required by the interface IteratorAggregate.
......
...@@ -88,7 +88,11 @@ abstract class Module extends Component ...@@ -88,7 +88,11 @@ abstract class Module extends Component
*/ */
public $controllerMap = array(); public $controllerMap = array();
/** /**
* @var string the namespace that controller classes are in. Default is to use global namespace. * @var string the namespace that controller classes are in. If not set,
* it will use the "controllers" sub-namespace under the namespace of this module.
* For example, if the namespace of this module is "foo\bar", then the default
* controller namespace would be "foo\bar\controllers".
* If the module is an application, it will default to "app\controllers".
*/ */
public $controllerNamespace; public $controllerNamespace;
/** /**
...@@ -178,6 +182,16 @@ abstract class Module extends Component ...@@ -178,6 +182,16 @@ abstract class Module extends Component
public function init() public function init()
{ {
$this->preloadComponents(); $this->preloadComponents();
if ($this->controllerNamespace === null) {
if ($this instanceof Application) {
$this->controllerNamespace = 'app\\controllers';
} else {
$class = get_class($this);
if (($pos = strrpos($class, '\\')) !== false) {
$this->controllerNamespace = substr($class, 0, $pos) . '\\controllers';
}
}
}
} }
/** /**
...@@ -222,6 +236,9 @@ abstract class Module extends Component ...@@ -222,6 +236,9 @@ abstract class Module extends Component
$p = realpath($path); $p = realpath($path);
if ($p !== false && is_dir($p)) { if ($p !== false && is_dir($p)) {
$this->_basePath = $p; $this->_basePath = $p;
if ($this instanceof Application) {
Yii::setAlias('@app', $p);
}
} else { } else {
throw new InvalidParamException("The directory does not exist: $path"); throw new InvalidParamException("The directory does not exist: $path");
} }
...@@ -409,11 +426,11 @@ abstract class Module extends Component ...@@ -409,11 +426,11 @@ abstract class Module extends Component
* ~~~ * ~~~
* array( * array(
* 'comment' => array( * 'comment' => array(
* 'class' => 'app\modules\CommentModule', * 'class' => 'app\modules\comment\CommentModule',
* 'db' => 'db', * 'db' => 'db',
* ), * ),
* 'booking' => array( * 'booking' => array(
* 'class' => 'app\modules\BookingModule', * 'class' => 'app\modules\booking\BookingModule',
* ), * ),
* ) * )
* ~~~ * ~~~
......
...@@ -23,4 +23,3 @@ class NotSupportedException extends Exception ...@@ -23,4 +23,3 @@ class NotSupportedException extends Exception
return \Yii::t('yii', 'Not Supported'); return \Yii::t('yii', 'Not Supported');
} }
} }
...@@ -7,12 +7,15 @@ ...@@ -7,12 +7,15 @@
namespace yii\base; namespace yii\base;
use Yii;
use yii\helpers\Json;
/** /**
* @include @yii/base/Object.md * @include @yii/base/Object.md
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
class Object class Object implements Jsonable
{ {
/** /**
* @return string the fully qualified name of this class. * @return string the fully qualified name of this class.
...@@ -38,8 +41,8 @@ class Object ...@@ -38,8 +41,8 @@ class Object
*/ */
public function __construct($config = array()) public function __construct($config = array())
{ {
foreach ($config as $name => $value) { if (!empty($config)) {
$this->$name = $value; Yii::configure($this, $config);
} }
$this->init(); $this->init();
} }
...@@ -216,4 +219,14 @@ class Object ...@@ -216,4 +219,14 @@ class Object
{ {
return method_exists($this, 'set' . $name) || $checkVar && property_exists($this, $name); return method_exists($this, 'set' . $name) || $checkVar && property_exists($this, $name);
} }
/**
* Returns the JSON representation of this object.
* The default implementation will return all public member variables.
* @return string the JSON representation of this object.
*/
public function toJson()
{
return Json::encode(Yii::getObjectVars($this));
}
} }
...@@ -13,6 +13,9 @@ namespace yii\base; ...@@ -13,6 +13,9 @@ namespace yii\base;
*/ */
class Response extends Component class Response extends Component
{ {
const EVENT_BEGIN_RESPONSE = 'beginResponse';
const EVENT_END_RESPONSE = 'endResponse';
/** /**
* Starts output buffering * Starts output buffering
*/ */
...@@ -56,4 +59,14 @@ class Response extends Component ...@@ -56,4 +59,14 @@ class Response extends Component
ob_end_clean(); ob_end_clean();
} }
} }
public function begin()
{
$this->trigger(self::EVENT_BEGIN_RESPONSE);
}
public function end()
{
$this->trigger(self::EVENT_END_RESPONSE);
}
} }
...@@ -23,4 +23,3 @@ class UnknownClassException extends Exception ...@@ -23,4 +23,3 @@ class UnknownClassException extends Exception
return \Yii::t('yii', 'Unknown Class'); return \Yii::t('yii', 'Unknown Class');
} }
} }
...@@ -23,4 +23,3 @@ class UnknownMethodException extends Exception ...@@ -23,4 +23,3 @@ class UnknownMethodException extends Exception
return \Yii::t('yii', 'Unknown Method'); return \Yii::t('yii', 'Unknown Method');
} }
} }
...@@ -23,4 +23,3 @@ class UnknownPropertyException extends Exception ...@@ -23,4 +23,3 @@ class UnknownPropertyException extends Exception
return \Yii::t('yii', 'Unknown Property'); return \Yii::t('yii', 'Unknown Property');
} }
} }
...@@ -6,9 +6,8 @@ ...@@ -6,9 +6,8 @@
*/ */
namespace yii\bootstrap; namespace yii\bootstrap;
use yii\base\InvalidConfigException;
use yii\helpers\Html;
use yii\helpers\Html;
/** /**
* Button renders a bootstrap button. * Button renders a bootstrap button.
......
...@@ -6,8 +6,8 @@ ...@@ -6,8 +6,8 @@
*/ */
namespace yii\bootstrap; namespace yii\bootstrap;
use yii\helpers\Html;
use yii\helpers\Html;
/** /**
* ButtonDropdown renders a group or split button dropdown bootstrap component. * ButtonDropdown renders a group or split button dropdown bootstrap component.
......
...@@ -10,7 +10,6 @@ namespace yii\bootstrap; ...@@ -10,7 +10,6 @@ namespace yii\bootstrap;
use yii\helpers\base\ArrayHelper; use yii\helpers\base\ArrayHelper;
use yii\helpers\Html; use yii\helpers\Html;
/** /**
* ButtonGroup renders a button group bootstrap component. * ButtonGroup renders a button group bootstrap component.
* *
......
...@@ -11,7 +11,6 @@ use yii\base\InvalidConfigException; ...@@ -11,7 +11,6 @@ use yii\base\InvalidConfigException;
use yii\helpers\ArrayHelper; use yii\helpers\ArrayHelper;
use yii\helpers\Html; use yii\helpers\Html;
/** /**
* Dropdown renders a Bootstrap dropdown menu component. * Dropdown renders a Bootstrap dropdown menu component.
* *
......
...@@ -29,11 +29,17 @@ use yii\helpers\Html; ...@@ -29,11 +29,17 @@ use yii\helpers\Html;
* 'label' => 'Dropdown', * 'label' => 'Dropdown',
* 'items' => array( * 'items' => array(
* array( * array(
* 'label' => 'DropdownA', * 'label' => 'Level 1 -DropdownA',
* 'url' => '#', * 'url' => '#',
* 'items' => array(
* array(
* 'label' => 'Level 2 -DropdownA',
* 'url' => '#',
* ),
* ),
* ), * ),
* array( * array(
* 'label' => 'DropdownB', * 'label' => 'Level 1 -DropdownB',
* 'url' => '#', * 'url' => '#',
* ), * ),
* ), * ),
...@@ -114,25 +120,27 @@ class Nav extends Widget ...@@ -114,25 +120,27 @@ class Nav extends Widget
} }
$label = $this->encodeLabels ? Html::encode($item['label']) : $item['label']; $label = $this->encodeLabels ? Html::encode($item['label']) : $item['label'];
$options = ArrayHelper::getValue($item, 'options', array()); $options = ArrayHelper::getValue($item, 'options', array());
$dropdown = ArrayHelper::getValue($item, 'dropdown'); $items = ArrayHelper::getValue($item, 'items');
$url = Html::url(ArrayHelper::getValue($item, 'url', '#')); $url = Html::url(ArrayHelper::getValue($item, 'url', '#'));
$linkOptions = ArrayHelper::getValue($item, 'linkOptions', array()); $linkOptions = ArrayHelper::getValue($item, 'linkOptions', array());
if(ArrayHelper::getValue($item, 'active')) { if (ArrayHelper::getValue($item, 'active')) {
$this->addCssClass($options, 'active'); $this->addCssClass($options, 'active');
} }
if ($dropdown !== null) { if ($items !== null) {
$linkOptions['data-toggle'] = 'dropdown'; $linkOptions['data-toggle'] = 'dropdown';
$this->addCssClass($options, 'dropdown'); $this->addCssClass($options, 'dropdown');
$this->addCssClass($urlOptions, 'dropdown-toggle'); $this->addCssClass($urlOptions, 'dropdown-toggle');
$label .= ' ' . Html::tag('b', '', array('class' => 'caret')); $label .= ' ' . Html::tag('b', '', array('class' => 'caret'));
if (is_array($dropdown)) { if (is_array($items)) {
$dropdown['clientOptions'] = false; $items = Dropdown::widget(array(
$dropdown = Dropdown::widget($dropdown); 'items' => $items,
'clientOptions' => false,
));
} }
} }
return Html::tag('li', Html::a($label, $url, $linkOptions) . $dropdown, $options); return Html::tag('li', Html::a($label, $url, $linkOptions) . $items, $options);
} }
} }
...@@ -11,7 +11,6 @@ use yii\base\InvalidConfigException; ...@@ -11,7 +11,6 @@ use yii\base\InvalidConfigException;
use yii\helpers\ArrayHelper; use yii\helpers\ArrayHelper;
use yii\helpers\Html; use yii\helpers\Html;
/** /**
* Progress renders a bootstrap progress bar component. * Progress renders a bootstrap progress bar component.
* *
......
...@@ -11,7 +11,6 @@ use Yii; ...@@ -11,7 +11,6 @@ use Yii;
use yii\base\View; use yii\base\View;
use yii\helpers\Json; use yii\helpers\Json;
/** /**
* \yii\bootstrap\Widget is the base class for all bootstrap widgets. * \yii\bootstrap\Widget is the base class for all bootstrap widgets.
* *
......
...@@ -25,8 +25,9 @@ class FileCache extends Cache ...@@ -25,8 +25,9 @@ class FileCache extends Cache
{ {
/** /**
* @var string the directory to store cache files. You may use path alias here. * @var string the directory to store cache files. You may use path alias here.
* If not set, it will use the "cache" subdirectory under the application runtime path.
*/ */
public $cachePath = '@app/runtime/cache'; public $cachePath = '@runtime/cache';
/** /**
* @var string cache file suffix. Defaults to '.bin'. * @var string cache file suffix. Defaults to '.bin'.
*/ */
......
...@@ -86,4 +86,3 @@ class XCache extends Cache ...@@ -86,4 +86,3 @@ class XCache extends Cache
return true; return true;
} }
} }
...@@ -25,4 +25,3 @@ class Exception extends UserException ...@@ -25,4 +25,3 @@ class Exception extends UserException
return \Yii::t('yii', 'Error'); return \Yii::t('yii', 'Error');
} }
} }
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\console;
/**
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class Response extends \yii\base\Response
{
}
...@@ -14,6 +14,20 @@ use yii\console\Controller; ...@@ -14,6 +14,20 @@ use yii\console\Controller;
/** /**
* This command allows you to combine and compress your JavaScript and CSS files. * This command allows you to combine and compress your JavaScript and CSS files.
* *
* Usage:
* 1. Create a configuration file using 'template' action:
* yii asset/template /path/to/myapp/config.php
* 2. Edit the created config file, adjusting it for your web application needs.
* 3. Run the 'compress' action, using created config:
* yii asset /path/to/myapp/config.php /path/to/myapp/config/assets_compressed.php
* 4. Adjust your web application config to use compressed assets.
*
* Note: in the console environment some path aliases like '@wwwroot' and '@www' may not exist,
* so corresponding paths inside the configuration should be specified directly.
*
* 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 array|\yii\web\AssetManager $assetManager asset manager, which will be used for assets processing.
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
...@@ -43,7 +57,7 @@ class AssetController extends Controller ...@@ -43,7 +57,7 @@ class AssetController extends Controller
* ~~~ * ~~~
* 'all' => array( * 'all' => array(
* 'css' => 'all.css', * 'css' => 'all.css',
* 'js' => 'js.css', * 'js' => 'all.js',
* 'depends' => array( ... ), * 'depends' => array( ... ),
* ) * )
* ~~~ * ~~~
...@@ -57,7 +71,7 @@ class AssetController extends Controller ...@@ -57,7 +71,7 @@ class AssetController extends Controller
*/ */
private $_assetManager = array(); private $_assetManager = array();
/** /**
* @var string|callback Java Script file compressor. * @var string|callback JavaScript file compressor.
* If a string, it is treated as shell command template, which should contain * If a string, it is treated as shell command template, which should contain
* placeholders {from} - source file name - and {to} - output file name. * placeholders {from} - source file name - and {to} - output file name.
* Otherwise, it is treated as PHP callback, which should perform the compression. * Otherwise, it is treated as PHP callback, which should perform the compression.
...@@ -150,7 +164,6 @@ class AssetController extends Controller ...@@ -150,7 +164,6 @@ class AssetController extends Controller
protected function loadConfiguration($configFile) protected function loadConfiguration($configFile)
{ {
echo "Loading configuration from '{$configFile}'...\n"; echo "Loading configuration from '{$configFile}'...\n";
foreach (require($configFile) as $name => $value) { foreach (require($configFile) as $name => $value) {
if (property_exists($this, $name) || $this->canSetProperty($name)) { if (property_exists($this, $name) || $this->canSetProperty($name)) {
$this->$name = $value; $this->$name = $value;
...@@ -159,7 +172,7 @@ class AssetController extends Controller ...@@ -159,7 +172,7 @@ class AssetController extends Controller
} }
} }
$this->getAssetManager(); // check asset manager configuration $this->getAssetManager(); // check if asset manager configuration is correct
} }
/** /**
...@@ -207,7 +220,8 @@ class AssetController extends Controller ...@@ -207,7 +220,8 @@ class AssetController extends Controller
* @param array $result already loaded bundles list. * @param array $result already loaded bundles list.
* @throws \yii\console\Exception on failure. * @throws \yii\console\Exception on failure.
*/ */
protected function loadBundleDependency($name, $bundle, &$result) { protected function loadBundleDependency($name, $bundle, &$result)
{
if (!empty($bundle->depends)) { if (!empty($bundle->depends)) {
$assetManager = $this->getAssetManager(); $assetManager = $this->getAssetManager();
foreach ($bundle->depends as $dependencyName) { foreach ($bundle->depends as $dependencyName) {
...@@ -308,7 +322,7 @@ class AssetController extends Controller ...@@ -308,7 +322,7 @@ class AssetController extends Controller
/** /**
* Builds output asset bundle. * Builds output asset bundle.
* @param \yii\web\AssetBundle $target output asset bundle * @param \yii\web\AssetBundle $target output asset bundle
* @param string $type either "js" or "css". * @param string $type either 'js' or 'css'.
* @param \yii\web\AssetBundle[] $bundles source asset bundles. * @param \yii\web\AssetBundle[] $bundles source asset bundles.
* @param integer $timestamp current timestamp. * @param integer $timestamp current timestamp.
* @throws Exception on failure. * @throws Exception on failure.
...@@ -420,24 +434,23 @@ class AssetController extends Controller ...@@ -420,24 +434,23 @@ class AssetController extends Controller
} }
$array = var_export($array, true); $array = var_export($array, true);
$version = date('Y-m-d H:i:s', time()); $version = date('Y-m-d H:i:s', time());
$bytesWritten = file_put_contents($bundleFile, <<<EOD $bundleFileContent = <<<EOD
<?php <?php
/** /**
* This file is generated by the "yii script" command. * This file is generated by the "yii {$this->id}" command.
* DO NOT MODIFY THIS FILE DIRECTLY. * DO NOT MODIFY THIS FILE DIRECTLY.
* @version $version * @version {$version}
*/ */
return $array; return {$array};
EOD EOD;
); if (!file_put_contents($bundleFile, $bundleFileContent)) {
if ($bytesWritten <= 0) {
throw new Exception("Unable to write output bundle configuration at '{$bundleFile}'."); throw new Exception("Unable to write output bundle configuration at '{$bundleFile}'.");
} }
echo "Output bundle configuration created at '{$bundleFile}'.\n"; echo "Output bundle configuration created at '{$bundleFile}'.\n";
} }
/** /**
* Compresses given Java Script files and combines them into the single one. * Compresses given JavaScript files and combines them into the single one.
* @param array $inputFiles list of source file names. * @param array $inputFiles list of source file names.
* @param string $outputFile output file name. * @param string $outputFile output file name.
* @throws \yii\console\Exception on failure * @throws \yii\console\Exception on failure
...@@ -495,9 +508,10 @@ EOD ...@@ -495,9 +508,10 @@ EOD
} }
/** /**
* Combines Java Script files into a single one. * Combines JavaScript files into a single one.
* @param array $inputFiles source file names. * @param array $inputFiles source file names.
* @param string $outputFile output file name. * @param string $outputFile output file name.
* @throws \yii\console\Exception on failure.
*/ */
public function combineJsFiles($inputFiles, $outputFile) public function combineJsFiles($inputFiles, $outputFile)
{ {
...@@ -507,13 +521,16 @@ EOD ...@@ -507,13 +521,16 @@ EOD
. file_get_contents($file) . file_get_contents($file)
. "/*** END FILE: $file ***/\n"; . "/*** END FILE: $file ***/\n";
} }
file_put_contents($outputFile, $content); if (!file_put_contents($outputFile, $content)) {
throw new Exception("Unable to write output JavaScript file '{$outputFile}'.");
}
} }
/** /**
* Combines CSS files into a single one. * Combines CSS files into a single one.
* @param array $inputFiles source file names. * @param array $inputFiles source file names.
* @param string $outputFile output file name. * @param string $outputFile output file name.
* @throws \yii\console\Exception on failure.
*/ */
public function combineCssFiles($inputFiles, $outputFile) public function combineCssFiles($inputFiles, $outputFile)
{ {
...@@ -523,7 +540,9 @@ EOD ...@@ -523,7 +540,9 @@ EOD
. $this->adjustCssUrl(file_get_contents($file), dirname($file), dirname($outputFile)) . $this->adjustCssUrl(file_get_contents($file), dirname($file), dirname($outputFile))
. "/*** END FILE: $file ***/\n"; . "/*** END FILE: $file ***/\n";
} }
file_put_contents($outputFile, $content); if (!file_put_contents($outputFile, $content)) {
throw new Exception("Unable to write output CSS file '{$outputFile}'.");
}
} }
/** /**
...@@ -554,7 +573,7 @@ EOD ...@@ -554,7 +573,7 @@ EOD
$inputFileRelativePathParts = explode('/', $inputFileRelativePath); $inputFileRelativePathParts = explode('/', $inputFileRelativePath);
$outputFileRelativePathParts = explode('/', $outputFileRelativePath); $outputFileRelativePathParts = explode('/', $outputFileRelativePath);
$callback = function($matches) use ($inputFileRelativePathParts, $outputFileRelativePathParts) { $callback = function ($matches) use ($inputFileRelativePathParts, $outputFileRelativePathParts) {
$fullMatch = $matches[0]; $fullMatch = $matches[0];
$inputUrl = $matches[1]; $inputUrl = $matches[1];
...@@ -590,18 +609,23 @@ EOD ...@@ -590,18 +609,23 @@ EOD
/** /**
* Creates template of configuration file for [[actionCompress]]. * Creates template of configuration file for [[actionCompress]].
* @param string $configFile output file name. * @param string $configFile output file name.
* @throws \yii\console\Exception on failure.
*/ */
public function actionTemplate($configFile) public function actionTemplate($configFile)
{ {
$template = <<<EOD $template = <<<EOD
<?php <?php
/**
* Configuration file for the "yii asset" console command.
* Note: in the console environment some path aliases like '@wwwroot' and '@www' may not exist,
* so corresponding paths should be specified directly.
*/
return array( return array(
// // The list of asset bundles to compress:
'bundles' => require('path/to/bundles.php'), 'bundles' => require('path/to/bundles.php'),
// // The list of extensions to compress:
'extensions' => require('path/to/namespaces.php'), 'extensions' => require('path/to/namespaces.php'),
// // Asset bundle for compression output:
'targets' => array( 'targets' => array(
'all' => array( 'all' => array(
'basePath' => __DIR__, 'basePath' => __DIR__,
...@@ -610,7 +634,7 @@ return array( ...@@ -610,7 +634,7 @@ return array(
'css' => 'all-{ts}.css', 'css' => 'all-{ts}.css',
), ),
), ),
// Asset manager configuration:
'assetManager' => array( 'assetManager' => array(
'basePath' => __DIR__, 'basePath' => __DIR__,
'baseUrl' => '/test', 'baseUrl' => '/test',
...@@ -622,9 +646,8 @@ EOD; ...@@ -622,9 +646,8 @@ EOD;
return; return;
} }
} }
$bytesWritten = file_put_contents($configFile, $template); if (!file_put_contents($configFile, $template)) {
if ($bytesWritten<=0) { throw new Exception("Unable to write template file '{$configFile}'.");
echo "Error: unable to write file '{$configFile}'!\n\n";
} else { } else {
echo "Configuration file template created at '{$configFile}'.\n\n"; echo "Configuration file template created at '{$configFile}'.\n\n";
} }
......
...@@ -179,8 +179,7 @@ class MessageController extends Controller ...@@ -179,8 +179,7 @@ class MessageController extends Controller
} }
ksort($translated); ksort($translated);
foreach ($translated as $message => $translation) { foreach ($translated as $message => $translation) {
if (!isset($merged[$message]) && !isset($todo[$message]) && !$removeOld) if (!isset($merged[$message]) && !isset($todo[$message]) && !$removeOld) {
{
if (substr($translation, 0, 2) === '@@' && substr($translation, -2) === '@@') { if (substr($translation, 0, 2) === '@@' && substr($translation, -2) === '@@') {
$todo[$message]=$translation; $todo[$message]=$translation;
} else { } else {
......
...@@ -115,7 +115,7 @@ class MigrateController extends Controller ...@@ -115,7 +115,7 @@ class MigrateController extends Controller
} }
$this->migrationPath = $path; $this->migrationPath = $path;
if($action->id!=='create') { if ($action->id !== 'create') {
if (is_string($this->db)) { if (is_string($this->db)) {
$this->db = Yii::$app->getComponent($this->db); $this->db = Yii::$app->getComponent($this->db);
} }
......
...@@ -5,9 +5,10 @@ ...@@ -5,9 +5,10 @@
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
namespace yii\web; namespace yii\data;
use Yii; use Yii;
use yii\base\Object;
/** /**
* Pagination represents information relevant to pagination of data items. * Pagination represents information relevant to pagination of data items.
...@@ -62,7 +63,7 @@ use Yii; ...@@ -62,7 +63,7 @@ use Yii;
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
class Pagination extends \yii\base\Object class Pagination extends Object
{ {
/** /**
* @var string name of the parameter storing the current page index. Defaults to 'page'. * @var string name of the parameter storing the current page index. Defaults to 'page'.
......
...@@ -5,9 +5,10 @@ ...@@ -5,9 +5,10 @@
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
namespace yii\web; namespace yii\data;
use Yii; use Yii;
use yii\base\Object;
use yii\helpers\Html; use yii\helpers\Html;
/** /**
...@@ -68,7 +69,7 @@ use yii\helpers\Html; ...@@ -68,7 +69,7 @@ use yii\helpers\Html;
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
class Sort extends \yii\base\Object class Sort extends Object
{ {
/** /**
* Sort ascending * Sort ascending
......
...@@ -275,10 +275,16 @@ class ActiveRecord extends Model ...@@ -275,10 +275,16 @@ class ActiveRecord extends Model
/** /**
* Returns the schema information of the DB table associated with this AR class. * Returns the schema information of the DB table associated with this AR class.
* @return TableSchema the schema information of the DB table associated with this AR class. * @return TableSchema the schema information of the DB table associated with this AR class.
* @throws InvalidConfigException if the table for the AR class does not exist.
*/ */
public static function getTableSchema() public static function getTableSchema()
{ {
return static::getDb()->getTableSchema(static::tableName()); $schema = static::getDb()->getTableSchema(static::tableName());
if ($schema !== null) {
return $schema;
} else {
throw new InvalidConfigException("The table does not exist: " . static::tableName());
}
} }
/** /**
......
...@@ -305,8 +305,7 @@ class Connection extends Component ...@@ -305,8 +305,7 @@ class Connection extends Component
$this->pdo = $this->createPdoInstance(); $this->pdo = $this->createPdoInstance();
$this->initConnection(); $this->initConnection();
Yii::endProfile($token, __METHOD__); Yii::endProfile($token, __METHOD__);
} } catch (\PDOException $e) {
catch (\PDOException $e) {
Yii::endProfile($token, __METHOD__); Yii::endProfile($token, __METHOD__);
Yii::error("Failed to open DB connection ({$this->dsn}): " . $e->getMessage(), __METHOD__); Yii::error("Failed to open DB connection ({$this->dsn}): " . $e->getMessage(), __METHOD__);
$message = YII_DEBUG ? 'Failed to open DB connection: ' . $e->getMessage() : 'Failed to open DB connection.'; $message = YII_DEBUG ? 'Failed to open DB connection: ' . $e->getMessage() : 'Failed to open DB connection.';
...@@ -508,7 +507,7 @@ class Connection extends Component ...@@ -508,7 +507,7 @@ class Connection extends Component
{ {
$db = $this; $db = $this;
return preg_replace_callback('/(\\{\\{([%\w\-\. ]+)\\}\\}|\\[\\[([\w\-\. ]+)\\]\\])/', return preg_replace_callback('/(\\{\\{([%\w\-\. ]+)\\}\\}|\\[\\[([\w\-\. ]+)\\]\\])/',
function($matches) use($db) { function ($matches) use ($db) {
if (isset($matches[3])) { if (isset($matches[3])) {
return $db->quoteColumnName($matches[3]); return $db->quoteColumnName($matches[3]);
} else { } else {
......
...@@ -464,6 +464,12 @@ class QueryBuilder extends \yii\base\Object ...@@ -464,6 +464,12 @@ class QueryBuilder extends \yii\base\Object
* the first part will be converted, and the rest of the parts will be appended to the converted result. * the first part will be converted, and the rest of the parts will be appended to the converted result.
* For example, 'string NOT NULL' is converted to 'varchar(255) NOT NULL'. * For example, 'string NOT NULL' is converted to 'varchar(255) NOT NULL'.
* *
* For some of the abstract types you can also specify a length or precision constraint
* by prepending it in round brackets directly to the type.
* For example `string(32)` will be converted into "varchar(32)" on a MySQL database.
* If the underlying DBMS does not support these kind of constraints for a type it will
* be ignored.
*
* If a type cannot be found in [[typeMap]], it will be returned without any change. * If a type cannot be found in [[typeMap]], it will be returned without any change.
* @param string $type abstract column type * @param string $type abstract column type
* @return string physical column type. * @return string physical column type.
...@@ -472,6 +478,10 @@ class QueryBuilder extends \yii\base\Object ...@@ -472,6 +478,10 @@ class QueryBuilder extends \yii\base\Object
{ {
if (isset($this->typeMap[$type])) { if (isset($this->typeMap[$type])) {
return $this->typeMap[$type]; return $this->typeMap[$type];
} elseif (preg_match('/^(\w+)\((.+?)\)(.*)$/', $type, $matches)) {
if (isset($this->typeMap[$matches[1]])) {
return preg_replace('/\(.+\)/', '(' . $matches[2] . ')', $this->typeMap[$matches[1]]) . $matches[3];
}
} elseif (preg_match('/^(\w+)\s+/', $type, $matches)) { } elseif (preg_match('/^(\w+)\s+/', $type, $matches)) {
if (isset($this->typeMap[$matches[1]])) { if (isset($this->typeMap[$matches[1]])) {
return preg_replace('/^\w+/', $this->typeMap[$matches[1]], $type); return preg_replace('/^\w+/', $this->typeMap[$matches[1]], $type);
......
...@@ -28,7 +28,7 @@ class QueryBuilder extends \yii\db\QueryBuilder ...@@ -28,7 +28,7 @@ class QueryBuilder extends \yii\db\QueryBuilder
Schema::TYPE_INTEGER => 'int(11)', Schema::TYPE_INTEGER => 'int(11)',
Schema::TYPE_BIGINT => 'bigint(20)', Schema::TYPE_BIGINT => 'bigint(20)',
Schema::TYPE_FLOAT => 'float', Schema::TYPE_FLOAT => 'float',
Schema::TYPE_DECIMAL => 'decimal', Schema::TYPE_DECIMAL => 'decimal(10,0)',
Schema::TYPE_DATETIME => 'datetime', Schema::TYPE_DATETIME => 'datetime',
Schema::TYPE_TIMESTAMP => 'timestamp', Schema::TYPE_TIMESTAMP => 'timestamp',
Schema::TYPE_TIME => 'time', Schema::TYPE_TIME => 'time',
......
...@@ -29,7 +29,7 @@ class QueryBuilder extends \yii\db\QueryBuilder ...@@ -29,7 +29,7 @@ class QueryBuilder extends \yii\db\QueryBuilder
Schema::TYPE_INTEGER => 'int(11)', Schema::TYPE_INTEGER => 'int(11)',
Schema::TYPE_BIGINT => 'bigint(20)', Schema::TYPE_BIGINT => 'bigint(20)',
Schema::TYPE_FLOAT => 'float', Schema::TYPE_FLOAT => 'float',
Schema::TYPE_DECIMAL => 'decimal', Schema::TYPE_DECIMAL => 'decimal(10,0)',
Schema::TYPE_DATETIME => 'datetime', Schema::TYPE_DATETIME => 'datetime',
Schema::TYPE_TIMESTAMP => 'timestamp', Schema::TYPE_TIMESTAMP => 'timestamp',
Schema::TYPE_TIME => 'time', Schema::TYPE_TIME => 'time',
......
...@@ -178,6 +178,7 @@ class Schema extends \yii\db\Schema ...@@ -178,6 +178,7 @@ class Schema extends \yii\db\Schema
* Collects the metadata of table columns. * Collects the metadata of table columns.
* @param TableSchema $table the table metadata * @param TableSchema $table the table metadata
* @return boolean whether the table exists in the database * @return boolean whether the table exists in the database
* @throws \Exception if DB query fails
*/ */
protected function findColumns($table) protected function findColumns($table)
{ {
...@@ -185,8 +186,13 @@ class Schema extends \yii\db\Schema ...@@ -185,8 +186,13 @@ class Schema extends \yii\db\Schema
try { try {
$columns = $this->db->createCommand($sql)->queryAll(); $columns = $this->db->createCommand($sql)->queryAll();
} catch (\Exception $e) { } catch (\Exception $e) {
$previous = $e->getPrevious();
if ($previous instanceof \PDOException && $previous->getCode() == '42S02') {
// table does not exist
return false; return false;
} }
throw $e;
}
foreach ($columns as $info) { foreach ($columns as $info) {
$column = $this->loadColumnSchema($info); $column = $this->loadColumnSchema($info);
$table->columns[$column->name] = $column; $table->columns[$column->name] = $column;
......
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\db\pgsql;
/**
* QueryBuilder is the query builder for PostgreSQL databases.
*
* @author Gevik Babakhani <gevikb@gmail.com>
* @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 => 'serial not null primary key',
Schema::TYPE_STRING => 'varchar',
Schema::TYPE_TEXT => 'text',
Schema::TYPE_SMALLINT => 'smallint',
Schema::TYPE_INTEGER => 'integer',
Schema::TYPE_BIGINT => 'bigint',
Schema::TYPE_FLOAT => 'double precision',
Schema::TYPE_DECIMAL => 'numeric',
Schema::TYPE_DATETIME => 'timestamp',
Schema::TYPE_TIMESTAMP => 'timestamp',
Schema::TYPE_TIME => 'time',
Schema::TYPE_DATE => 'date',
Schema::TYPE_BINARY => 'bytea',
Schema::TYPE_BOOLEAN => 'boolean',
Schema::TYPE_MONEY => 'numeric(19,4)',
);
}
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\db\pgsql;
use yii\db\TableSchema;
use yii\db\ColumnSchema;
/**
* Schema is the class for retrieving metadata from a PostgreSQL database
* (version 9.x and above).
*
* @author Gevik Babakhani <gevikb@gmail.com>
* @since 2.0
*/
class Schema extends \yii\db\Schema
{
/**
* The default schema used for the current session.
* @var string
*/
public $defaultSchema = 'public';
/**
* @var array mapping from physical column types (keys) to abstract
* column types (values)
*/
public $typeMap = array(
'abstime' => self::TYPE_TIMESTAMP,
'bit' => self::TYPE_STRING,
'boolean' => self::TYPE_BOOLEAN,
'box' => self::TYPE_STRING,
'character' => self::TYPE_STRING,
'bytea' => self::TYPE_BINARY,
'char' => self::TYPE_STRING,
'cidr' => self::TYPE_STRING,
'circle' => self::TYPE_STRING,
'date' => self::TYPE_DATE,
'real' => self::TYPE_FLOAT,
'double precision' => self::TYPE_DECIMAL,
'inet' => self::TYPE_STRING,
'smallint' => self::TYPE_SMALLINT,
'integer' => self::TYPE_INTEGER,
'bigint' => self::TYPE_BIGINT,
'interval' => self::TYPE_STRING,
'json' => self::TYPE_STRING,
'line' => self::TYPE_STRING,
'macaddr' => self::TYPE_STRING,
'money' => self::TYPE_MONEY,
'name' => self::TYPE_STRING,
'numeric' => self::TYPE_STRING,
'numrange' => self::TYPE_DECIMAL,
'oid' => self::TYPE_BIGINT, // should not be used. it's pg internal!
'path' => self::TYPE_STRING,
'point' => self::TYPE_STRING,
'polygon' => self::TYPE_STRING,
'text' => self::TYPE_TEXT,
'time without time zone' => self::TYPE_TIME,
'timestamp without time zone' => self::TYPE_TIMESTAMP,
'timestamp with time zone' => self::TYPE_TIMESTAMP,
'time with time zone' => self::TYPE_TIMESTAMP,
'unknown' => self::TYPE_STRING,
'uuid' => self::TYPE_STRING,
'bit varying' => self::TYPE_STRING,
'character varying' => self::TYPE_STRING,
'xml' => self::TYPE_STRING
);
/**
* Creates a query builder for the PostgreSQL database.
* @return QueryBuilder query builder instance
*/
public function createQueryBuilder()
{
return new QueryBuilder($this->db);
}
/**
* Resolves the table name and schema name (if any).
* @param TableSchema $table the table metadata object
* @param string $name the table name
*/
protected function resolveTableNames($table, $name)
{
$parts = explode('.', str_replace('"', '', $name));
if (isset($parts[1])) {
$table->schemaName = $parts[0];
$table->name = $parts[1];
} else {
$table->name = $parts[0];
}
if ($table->schemaName === null) {
$table->schemaName = $this->defaultSchema;
}
}
/**
* 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 . '"';
}
/**
* Loads the metadata for the specified table.
* @param string $name table name
* @return TableSchema|null driver dependent table metadata. Null if the table does not exist.
*/
public function loadTableSchema($name)
{
$table = new TableSchema();
$this->resolveTableNames($table, $name);
if ($this->findColumns($table)) {
$this->findConstraints($table);
return $table;
} else {
return null;
}
}
/**
* Collects the foreign key column details for the given table.
* @param TableSchema $table the table metadata
*/
protected function findConstraints($table)
{
$tableName = $this->quoteValue($table->name);
$tableSchema = $this->quoteValue($table->schemaName);
//We need to extract the constraints de hard way since:
//http://www.postgresql.org/message-id/26677.1086673982@sss.pgh.pa.us
$sql = <<<SQL
select
(select string_agg(attname,',') attname from pg_attribute where attrelid=ct.conrelid and attnum = any(ct.conkey)) as columns,
fc.relname as foreign_table_name,
fns.nspname as foreign_table_schema,
(select string_agg(attname,',') attname from pg_attribute where attrelid=ct.confrelid and attnum = any(ct.confkey)) as foreign_columns
from
pg_constraint ct
inner join pg_class c on c.oid=ct.conrelid
inner join pg_namespace ns on c.relnamespace=ns.oid
left join pg_class fc on fc.oid=ct.confrelid
left join pg_namespace fns on fc.relnamespace=fns.oid
where
ct.contype='f'
and c.relname={$tableName}
and ns.nspname={$tableSchema}
SQL;
$constraints = $this->db->createCommand($sql)->queryAll();
foreach ($constraints as $constraint) {
$columns = explode(',', $constraint['columns']);
$fcolumns = explode(',', $constraint['foreign_columns']);
if ($constraint['foreign_table_schema'] !== $this->defaultSchema) {
$foreignTable = $constraint['foreign_table_schema'] . '.' . $constraint['foreign_table_name'];
} else {
$foreignTable = $constraint['foreign_table_name'];
}
$citem = array($foreignTable);
foreach ($columns as $idx => $column) {
$citem[] = array($fcolumns[$idx] => $column);
}
$table->foreignKeys[] = $citem;
}
}
/**
* Collects the metadata of table columns.
* @param TableSchema $table the table metadata
* @return boolean whether the table exists in the database
*/
protected function findColumns($table)
{
$tableName = $this->db->quoteValue($table->name);
$schemaName = $this->db->quoteValue($table->schemaName);
$sql = <<<SQL
SELECT
current_database() as table_catalog,
d.nspname AS table_schema,
c.relname AS table_name,
a.attname AS column_name,
t.typname AS data_type,
a.attlen AS character_maximum_length,
pg_catalog.col_description(c.oid, a.attnum) AS column_comment,
a.atttypmod AS modifier,
a.attnotnull = false AS is_nullable,
CAST(pg_get_expr(ad.adbin, ad.adrelid) AS varchar) AS column_default,
coalesce(pg_get_expr(ad.adbin, ad.adrelid) ~ 'nextval',false) AS is_autoinc,
array_to_string((select array_agg(enumlabel) from pg_enum where enumtypid=a.atttypid)::varchar[],',') as enum_values,
CASE atttypid
WHEN 21 /*int2*/ THEN 16
WHEN 23 /*int4*/ THEN 32
WHEN 20 /*int8*/ THEN 64
WHEN 1700 /*numeric*/ THEN
CASE WHEN atttypmod = -1
THEN null
ELSE ((atttypmod - 4) >> 16) & 65535
END
WHEN 700 /*float4*/ THEN 24 /*FLT_MANT_DIG*/
WHEN 701 /*float8*/ THEN 53 /*DBL_MANT_DIG*/
ELSE null
END AS numeric_precision,
CASE
WHEN atttypid IN (21, 23, 20) THEN 0
WHEN atttypid IN (1700) THEN
CASE
WHEN atttypmod = -1 THEN null
ELSE (atttypmod - 4) & 65535
END
ELSE null
END AS numeric_scale,
CAST(
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
FROM
pg_class c
LEFT JOIN pg_attribute a ON a.attrelid = c.oid
LEFT JOIN pg_attrdef ad ON a.attrelid = ad.adrelid AND a.attnum = ad.adnum
LEFT JOIN pg_type t ON a.atttypid = t.oid
LEFT JOIN pg_namespace d ON d.oid = c.relnamespace
LEFT join pg_constraint ct on ct.conrelid=c.oid and ct.contype='p'
WHERE
a.attnum > 0
and c.relname = {$tableName}
and d.nspname = {$schemaName}
ORDER BY
a.attnum;
SQL;
$columns = $this->db->createCommand($sql)->queryAll();
foreach ($columns as $column) {
$column = $this->loadColumnSchema($column);
$table->columns[$column->name] = $column;
if ($column->isPrimaryKey === true) {
$table->primaryKey[] = $column->name;
if ($table->sequenceName === null && preg_match("/nextval\('\w+'(::regclass)?\)/", $column->defaultValue) === 1) {
$table->sequenceName = preg_replace(array('/nextval/', '/::/', '/regclass/', '/\'\)/', '/\(\'/'), '', $column->defaultValue);
}
}
}
return true;
}
/**
* 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->allowNull = $info['is_nullable'];
$column->autoIncrement = $info['is_autoinc'];
$column->comment = $info['column_comment'];
$column->dbType = $info['data_type'];
$column->defaultValue = $info['column_default'];
$column->enumValues = explode(',', str_replace(array("''"), array("'"), $info['enum_values']));
$column->unsigned = false; // has no meanining in PG
$column->isPrimaryKey = $info['is_pkey'];
$column->name = $info['column_name'];
$column->precision = $info['numeric_precision'];
$column->scale = $info['numeric_scale'];
$column->size = $info['size'];
if (isset($this->typeMap[$column->dbType])) {
$column->type = $this->typeMap[$column->dbType];
} else {
$column->type = self::TYPE_STRING;
}
$column->phpType = $this->getColumnPhpType($column);
return $column;
}
}
...@@ -30,13 +30,13 @@ class QueryBuilder extends \yii\db\QueryBuilder ...@@ -30,13 +30,13 @@ class QueryBuilder extends \yii\db\QueryBuilder
Schema::TYPE_INTEGER => 'integer', Schema::TYPE_INTEGER => 'integer',
Schema::TYPE_BIGINT => 'bigint', Schema::TYPE_BIGINT => 'bigint',
Schema::TYPE_FLOAT => 'float', Schema::TYPE_FLOAT => 'float',
Schema::TYPE_DECIMAL => 'decimal', Schema::TYPE_DECIMAL => 'decimal(10,0)',
Schema::TYPE_DATETIME => 'datetime', Schema::TYPE_DATETIME => 'datetime',
Schema::TYPE_TIMESTAMP => 'timestamp', Schema::TYPE_TIMESTAMP => 'timestamp',
Schema::TYPE_TIME => 'time', Schema::TYPE_TIME => 'time',
Schema::TYPE_DATE => 'date', Schema::TYPE_DATE => 'date',
Schema::TYPE_BINARY => 'blob', Schema::TYPE_BINARY => 'blob',
Schema::TYPE_BOOLEAN => 'tinyint(1)', Schema::TYPE_BOOLEAN => 'boolean',
Schema::TYPE_MONEY => 'decimal(19,4)', Schema::TYPE_MONEY => 'decimal(19,4)',
); );
......
...@@ -14,5 +14,4 @@ namespace yii\helpers; ...@@ -14,5 +14,4 @@ namespace yii\helpers;
*/ */
class Json extends base\Json class Json extends base\Json
{ {
} }
...@@ -286,7 +286,7 @@ class Console ...@@ -286,7 +286,7 @@ class Console
* You can pass any of the FG_*, BG_* and TEXT_* constants and also [[xtermFgColor]] and [[xtermBgColor]]. * You can pass any of the FG_*, BG_* and TEXT_* constants and also [[xtermFgColor]] and [[xtermBgColor]].
* @return string * @return string
*/ */
public static function ansiFormat($string, $format=array()) public static function ansiFormat($string, $format = array())
{ {
$code = implode(';', $format); $code = implode(';', $format);
return "\033[0m" . ($code !== '' ? "\033[" . $code . "m" : '') . $string . "\033[0m"; return "\033[0m" . ($code !== '' ? "\033[" . $code . "m" : '') . $string . "\033[0m";
...@@ -589,11 +589,10 @@ class Console ...@@ -589,11 +589,10 @@ class Console
if (static::isRunningOnWindows()) { if (static::isRunningOnWindows()) {
$output = array(); $output = array();
exec('mode con', $output); exec('mode con', $output);
if(isset($output) && strpos($output[1], 'CON')!==false) { if (isset($output) && strpos($output[1], 'CON') !== false) {
return $size = array((int)preg_replace('~[^0-9]~', '', $output[3]), (int)preg_replace('~[^0-9]~', '', $output[4])); return $size = array((int)preg_replace('~[^0-9]~', '', $output[3]), (int)preg_replace('~[^0-9]~', '', $output[4]));
} }
} else { } else {
// try stty if available // try stty if available
$stty = array(); $stty = array();
if (exec('stty -a 2>&1', $stty) && preg_match('/rows\s+(\d+);\s*columns\s+(\d+);/mi', implode(' ', $stty), $matches)) { if (exec('stty -a 2>&1', $stty) && preg_match('/rows\s+(\d+);\s*columns\s+(\d+);/mi', implode(' ', $stty), $matches)) {
......
...@@ -1479,5 +1479,4 @@ class Html ...@@ -1479,5 +1479,4 @@ class Html
$name = strtolower(static::getInputName($model, $attribute)); $name = strtolower(static::getInputName($model, $attribute));
return str_replace(array('[]', '][', '[', ']', ' '), array('', '-', '-', '', '-'), $name); return str_replace(array('[]', '][', '[', ']', ' '), array('', '-', '-', '', '-'), $name);
} }
} }
...@@ -498,7 +498,7 @@ class Inflector ...@@ -498,7 +498,7 @@ class Inflector
if (in_array(($number % 100), range(11, 13))) { if (in_array(($number % 100), range(11, 13))) {
return $number . 'th'; return $number . 'th';
} }
switch (($number % 10)) { switch ($number % 10) {
case 1: return $number . 'st'; case 1: return $number . 'st';
case 2: return $number . 'nd'; case 2: return $number . 'nd';
case 3: return $number . 'rd'; case 3: return $number . 'rd';
......
...@@ -8,6 +8,7 @@ ...@@ -8,6 +8,7 @@
namespace yii\helpers\base; namespace yii\helpers\base;
use yii\base\InvalidParamException; use yii\base\InvalidParamException;
use yii\base\Jsonable;
use yii\web\JsExpression; use yii\web\JsExpression;
/** /**
...@@ -90,7 +91,9 @@ class Json ...@@ -90,7 +91,9 @@ class Json
$token = '!{[' . count($expressions) . ']}!'; $token = '!{[' . count($expressions) . ']}!';
$expressions['"' . $token . '"'] = $data->expression; $expressions['"' . $token . '"'] = $data->expression;
return $token; return $token;
} } elseif ($data instanceof Jsonable) {
return $data->toJson();
} else {
$result = array(); $result = array();
foreach ($data as $key => $value) { foreach ($data as $key => $value) {
if (is_array($value) || is_object($value)) { if (is_array($value) || is_object($value)) {
...@@ -100,6 +103,7 @@ class Json ...@@ -100,6 +103,7 @@ class Json
} }
} }
return $result; return $result;
}
} else { } else {
return $data; return $data;
} }
......
...@@ -131,14 +131,29 @@ class SecurityHelper ...@@ -131,14 +131,29 @@ class SecurityHelper
$keys = is_file($keyFile) ? require($keyFile) : array(); $keys = is_file($keyFile) ? require($keyFile) : array();
} }
if (!isset($keys[$name])) { if (!isset($keys[$name])) {
// generate a 32-char random key $keys[$name] = static::generateRandomKey($length);
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$keys[$name] = substr(str_shuffle(str_repeat($chars, 5)), 0, $length);
file_put_contents($keyFile, "<?php\nreturn " . var_export($keys, true) . ";\n"); file_put_contents($keyFile, "<?php\nreturn " . var_export($keys, true) . ";\n");
} }
return $keys[$name]; return $keys[$name];
} }
/**
* Generates a random key.
* @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));
if ($strong) {
return substr($key, 0, $length);
}
}
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
return substr(str_shuffle(str_repeat($chars, 5)), 0, $length);
}
/** /**
* Opens the mcrypt module. * Opens the mcrypt module.
* @return resource the mcrypt module handle. * @return resource the mcrypt module handle.
......
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\i18n;
use Yii;
use yii\base\InvalidConfigException;
use yii\helpers\ArrayHelper;
use yii\caching\Cache;
use yii\db\Connection;
use yii\db\Query;
/**
* DbMessageSource extends [[MessageSource]] and represents a message source that stores translated
* messages in database.
*
* The database must contain the following two tables:
*
* ~~~
* CREATE TABLE tbl_source_message (
* id INTEGER PRIMARY KEY,
* category VARCHAR(32),
* message TEXT
* );
*
* CREATE TABLE tbl_message (
* id INTEGER,
* language VARCHAR(16),
* translation TEXT,
* PRIMARY KEY (id, language),
* CONSTRAINT fk_message_source_message FOREIGN KEY (id)
* REFERENCES tbl_source_message (id) ON DELETE CASCADE ON UPDATE RESTRICT
* );
* ~~~
*
* The `tbl_source_message` table stores the messages to be translated, and the `tbl_message` table stores
* the translated messages. The name of these two tables can be customized by setting [[sourceMessageTable]]
* and [[messageTable]], respectively.
*
* @author resurtm <resurtm@gmail.com>
* @since 2.0
*/
class DbMessageSource extends MessageSource
{
/**
* Prefix which would be used when generating cache key.
*/
const CACHE_KEY_PREFIX = 'DbMessageSource';
/**
* @var Connection|string the DB connection object or the application component ID of the DB connection.
* After the DbMessageSource object is created, if you want to change this property, you should only assign
* it with a DB connection object.
*/
public $db = 'db';
/**
* @var Cache|string the cache object or the application component ID of the cache object.
* The messages data will be cached using this cache object. Note, this property has meaning only
* in case [[cachingDuration]] set to non-zero value.
* After the DbMessageSource object is created, if you want to change this property, you should only assign
* it with a cache object.
*/
public $cache = 'cache';
/**
* @var string the name of the source message table.
*/
public $sourceMessageTable = 'tbl_source_message';
/**
* @var string the name of the translated message table.
*/
public $messageTable = 'tbl_message';
/**
* @var integer the time in seconds that the messages can remain valid in cache.
* Use 0 to indicate that the cached data will never expire.
* @see enableCaching
*/
public $cachingDuration = 0;
/**
* @var boolean whether to enable caching translated messages
*/
public $enableCaching = false;
/**
* Initializes the DbMessageSource component.
* This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
* Configured [[cache]] component would also be initialized.
* @throws InvalidConfigException if [[db]] is invalid or [[cache]] is invalid.
*/
public function init()
{
parent::init();
if (is_string($this->db)) {
$this->db = Yii::$app->getComponent($this->db);
}
if (!$this->db instanceof Connection) {
throw new InvalidConfigException("DbMessageSource::db must be either a DB connection instance or the application component ID of a DB connection.");
}
if ($this->enableCaching) {
if (is_string($this->cache)) {
$this->cache = Yii::$app->getComponent($this->cache);
}
if (!$this->cache instanceof Cache) {
throw new InvalidConfigException("DbMessageSource::cache must be either a cache object or the application component ID of the cache object.");
}
}
}
/**
* Loads the message translation for the specified language and category.
* Child classes should override this method to return the message translations of
* the specified language and category.
* @param string $category the message category
* @param string $language the target language
* @return array the loaded messages. The keys are original messages, and the values
* are translated messages.
*/
protected function loadMessages($category, $language)
{
if ($this->enableCaching) {
$key = array(
__CLASS__,
$category,
$language,
);
$messages = $this->cache->get($key);
if ($messages === false) {
$messages = $this->loadMessagesFromDb($category, $language);
$this->cache->set($key, $messages, $this->cachingDuration);
}
return $messages;
} else {
return $this->loadMessagesFromDb($category, $language);
}
}
/**
* Loads the messages from database.
* You may override this method to customize the message storage in the database.
* @param string $category the message category.
* @param string $language the target language.
* @return array the messages loaded from database.
*/
protected function loadMessagesFromDb($category, $language)
{
$query = new Query();
$messages = $query->select(array('t1.message message', 't2.translation translation'))
->from(array($this->sourceMessageTable . ' t1', $this->messageTable . ' t2'))
->where('t1.id = t2.id AND t1.category = :category AND t2.language = :language')
->params(array(':category' => $category, ':language' => $language))
->createCommand($this->db)
->queryAll();
return ArrayHelper::map($messages, 'message', 'translation');
}
}
...@@ -30,21 +30,40 @@ class Formatter extends \yii\base\Formatter ...@@ -30,21 +30,40 @@ class Formatter extends \yii\base\Formatter
*/ */
public $locale; public $locale;
/** /**
* @var string the default format string to be used to format a date using PHP date() function. * @var string the default format string to be used to format a date.
* This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
* It can also be a custom format as specified in the [ICU manual](http://userguide.icu-project.org/formatparse/datetime).
*/ */
public $dateFormat = 'short'; public $dateFormat = 'short';
/** /**
* @var string the default format string to be used to format a time using PHP date() function. * @var string the default format string to be used to format a time.
* This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
* It can also be a custom format as specified in the [ICU manual](http://userguide.icu-project.org/formatparse/datetime).
*/ */
public $timeFormat = 'short'; public $timeFormat = 'short';
/** /**
* @var string the default format string to be used to format a date and time using PHP date() function. * @var string the default format string to be used to format a date and time.
* This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
* It can also be a custom format as specified in the [ICU manual](http://userguide.icu-project.org/formatparse/datetime).
*/ */
public $datetimeFormat = 'short'; public $datetimeFormat = 'short';
/** /**
* @var array the options to be set for the NumberFormatter objects. Please refer to * @var array the options to be set for the NumberFormatter objects. Please refer to
* [PHP manual](http://php.net/manual/en/class.numberformatter.php#intl.numberformatter-constants.unumberformatattribute)
* for the possible options. This property is used by [[createNumberFormatter]] when
* creating a new number formatter to format decimals, currencies, etc.
*/ */
public $numberFormatOptions = array(); public $numberFormatOptions = array();
/**
* @var string the character displayed as the decimal point when formatting a number.
* If not set, the decimal separator corresponding to [[locale]] will be used.
*/
public $decimalSeparator;
/**
* @var string the character displayed as the thousands separator character when formatting a number.
* If not set, the thousand separator corresponding to [[locale]] will be used.
*/
public $thousandSeparator;
/** /**
...@@ -61,6 +80,16 @@ class Formatter extends \yii\base\Formatter ...@@ -61,6 +80,16 @@ class Formatter extends \yii\base\Formatter
if ($this->locale === null) { if ($this->locale === null) {
$this->locale = Yii::$app->language; $this->locale = Yii::$app->language;
} }
if ($this->decimalSeparator === null || $this->thousandSeparator === null) {
$formatter = new NumberFormatter($this->locale, NumberFormatter::DECIMAL);
if ($this->decimalSeparator === null) {
$this->decimalSeparator = $formatter->getSymbol(NumberFormatter::DECIMAL_SEPARATOR_SYMBOL);
}
if ($this->thousandSeparator === null) {
$this->thousandSeparator = $formatter->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL);
}
}
parent::init(); parent::init();
} }
...@@ -81,8 +110,11 @@ class Formatter extends \yii\base\Formatter ...@@ -81,8 +110,11 @@ class Formatter extends \yii\base\Formatter
* - a PHP DateTime object * - a PHP DateTime object
* *
* @param string $format the format used to convert the value into a date string. * @param string $format the format used to convert the value into a date string.
* If null, [[dateFormat]] will be used. The format string should be the one * If null, [[dateFormat]] will be used.
* that can be recognized by the PHP `date()` function. *
* This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
* It can also be a custom format as specified in the [ICU manual](http://userguide.icu-project.org/formatparse/datetime).
*
* @return string the formatted result * @return string the formatted result
* @see dateFormat * @see dateFormat
*/ */
...@@ -111,8 +143,11 @@ class Formatter extends \yii\base\Formatter ...@@ -111,8 +143,11 @@ class Formatter extends \yii\base\Formatter
* - a PHP DateTime object * - a PHP DateTime object
* *
* @param string $format the format used to convert the value into a date string. * @param string $format the format used to convert the value into a date string.
* If null, [[dateFormat]] will be used. The format string should be the one * If null, [[dateFormat]] will be used.
* that can be recognized by the PHP `date()` function. *
* This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
* It can also be a custom format as specified in the [ICU manual](http://userguide.icu-project.org/formatparse/datetime).
*
* @return string the formatted result * @return string the formatted result
* @see timeFormat * @see timeFormat
*/ */
...@@ -141,8 +176,11 @@ class Formatter extends \yii\base\Formatter ...@@ -141,8 +176,11 @@ class Formatter extends \yii\base\Formatter
* - a PHP DateTime object * - a PHP DateTime object
* *
* @param string $format the format used to convert the value into a date string. * @param string $format the format used to convert the value into a date string.
* If null, [[dateFormat]] will be used. The format string should be the one * If null, [[dateFormat]] will be used.
* that can be recognized by the PHP `date()` function. *
* This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.
* It can also be a custom format as specified in the [ICU manual](http://userguide.icu-project.org/formatparse/datetime).
*
* @return string the formatted result * @return string the formatted result
* @see datetimeFormat * @see datetimeFormat
*/ */
...@@ -213,7 +251,7 @@ class Formatter extends \yii\base\Formatter ...@@ -213,7 +251,7 @@ class Formatter extends \yii\base\Formatter
/** /**
* Creates a number formatter based on the given type and format. * Creates a number formatter based on the given type and format.
* @param integer $type the type of the number formatter * @param integer $type the type of the number formatter
* @param string $format the format to be used * @param string $format the format to be used. Please refer to [ICU manual](http://www.icu-project.org/apiref/icu4c/classDecimalFormat.html#_details)
* @return NumberFormatter the created formatter instance * @return NumberFormatter the created formatter instance
*/ */
protected function createNumberFormatter($type, $format) protected function createNumberFormatter($type, $format)
......
...@@ -78,16 +78,11 @@ class I18N extends Component ...@@ -78,16 +78,11 @@ class I18N extends Component
* @param string $category the message category. * @param string $category the message category.
* @param string $message the message to be translated. * @param string $message the message to be translated.
* @param array $params the parameters that will be used to replace the corresponding placeholders in the message. * @param array $params the parameters that will be used to replace the corresponding placeholders in the message.
* @param string $language the language code (e.g. `en_US`, `en`). If this is null, the current * @param string $language the language code (e.g. `en_US`, `en`).
* [[\yii\base\Application::language|application language]] will be used.
* @return string the translated message. * @return string the translated message.
*/ */
public function translate($category, $message, $params = array(), $language = null) public function translate($category, $message, $params, $language)
{ {
if ($language === null) {
$language = Yii::$app->language;
}
$message = $this->getMessageSource($category)->translate($category, $message, $language); $message = $this->getMessageSource($category)->translate($category, $message, $language);
if (!is_array($params)) { if (!is_array($params)) {
......
...@@ -118,4 +118,3 @@ class MessageSource extends Component ...@@ -118,4 +118,3 @@ class MessageSource extends Component
} }
} }
} }
...@@ -125,7 +125,7 @@ class Accordion extends Widget ...@@ -125,7 +125,7 @@ class Accordion extends Widget
$items[] = Html::tag($headerTag, $item['header'], $headerOptions); $items[] = Html::tag($headerTag, $item['header'], $headerOptions);
$options = array_merge($this->itemOptions, ArrayHelper::getValue($item, 'options', array())); $options = array_merge($this->itemOptions, ArrayHelper::getValue($item, 'options', array()));
$tag = ArrayHelper::remove($options, 'tag', 'div'); $tag = ArrayHelper::remove($options, 'tag', 'div');
$items[] = Html::tag($tag, $item['content'], $options);; $items[] = Html::tag($tag, $item['content'], $options);
} }
return implode("\n", $items); return implode("\n", $items);
......
...@@ -10,7 +10,6 @@ namespace yii\jui; ...@@ -10,7 +10,6 @@ namespace yii\jui;
use Yii; use Yii;
use yii\helpers\Json; use yii\helpers\Json;
/** /**
* Menu renders a menu jQuery UI widget. * Menu renders a menu jQuery UI widget.
* *
......
...@@ -10,7 +10,6 @@ namespace yii\jui; ...@@ -10,7 +10,6 @@ namespace yii\jui;
use Yii; use Yii;
use yii\helpers\Json; use yii\helpers\Json;
/** /**
* \yii\jui\Widget is the base class for all jQuery UI widgets. * \yii\jui\Widget is the base class for all jQuery UI widgets.
* *
......
...@@ -70,7 +70,7 @@ class CProfileLogRoute extends CWebLogRoute ...@@ -70,7 +70,7 @@ class CProfileLogRoute extends CWebLogRoute
public function processLogs($logs) public function processLogs($logs)
{ {
$app = \Yii::$app; $app = \Yii::$app;
if (!($app instanceof CWebApplication) || $app->getRequest()->getIsAjaxRequest()) if (!($app instanceof \yii\web\Application) || $app->getRequest()->getIsAjax())
return; return;
if ($this->getReport() === 'summary') if ($this->getReport() === 'summary')
......
...@@ -204,14 +204,12 @@ abstract class Target extends Component ...@@ -204,14 +204,12 @@ abstract class Target extends Component
if ($matched) { if ($matched) {
foreach ($this->except as $category) { foreach ($this->except as $category) {
$prefix = rtrim($category, '*'); $prefix = rtrim($category, '*');
foreach ($messages as $i => $message) {
if (strpos($message[2], $prefix) === 0 && ($message[2] === $category || $prefix !== $category)) { if (strpos($message[2], $prefix) === 0 && ($message[2] === $category || $prefix !== $category)) {
$matched = false; $matched = false;
break; break;
} }
} }
} }
}
if (!$matched) { if (!$matched) {
unset($messages[$i]); unset($messages[$i]);
......
...@@ -493,9 +493,10 @@ class DbManager extends Manager ...@@ -493,9 +493,10 @@ class DbManager extends Manager
'bizRule' => $row['biz_rule'], 'bizRule' => $row['biz_rule'],
'data' => $data, 'data' => $data,
)); ));
} else } else {
return null; return null;
} }
}
/** /**
* Saves an authorization item to persistent storage. * Saves an authorization item to persistent storage.
......
...@@ -117,4 +117,3 @@ class CaptchaValidator extends Validator ...@@ -117,4 +117,3 @@ class CaptchaValidator extends Validator
return 'yii.validation.captcha(value, messages, ' . json_encode($options) . ');'; return 'yii.validation.captcha(value, messages, ' . json_encode($options) . ');';
} }
} }
...@@ -58,7 +58,7 @@ class CompareValidator extends Validator ...@@ -58,7 +58,7 @@ class CompareValidator extends Validator
* - `<`: validates to see if the value being validated is less than the value being compared with. * - `<`: validates to see if the value being validated is less than the value being compared with.
* - `<=`: validates to see if the value being validated is less than or equal to the value being compared with. * - `<=`: validates to see if the value being validated is less than or equal to the value being compared with.
*/ */
public $operator = '='; public $operator = '==';
/** /**
* @var string the user-defined error message. It may contain the following placeholders which * @var string the user-defined error message. It may contain the following placeholders which
* will be replaced accordingly by the validator: * will be replaced accordingly by the validator:
......
...@@ -58,7 +58,7 @@ class DateValidator extends Validator ...@@ -58,7 +58,7 @@ class DateValidator extends Validator
$date = DateTime::createFromFormat($this->format, $value); $date = DateTime::createFromFormat($this->format, $value);
if ($date === false) { if ($date === false) {
$this->addError($object, $attribute, $this->message); $this->addError($object, $attribute, $this->message);
} elseif ($this->timestampAttribute !== false) { } elseif ($this->timestampAttribute !== null) {
$object->{$this->timestampAttribute} = $date->getTimestamp(); $object->{$this->timestampAttribute} = $date->getTimestamp();
} }
} }
...@@ -73,4 +73,3 @@ class DateValidator extends Validator ...@@ -73,4 +73,3 @@ class DateValidator extends Validator
return DateTime::createFromFormat($this->format, $value) !== false; return DateTime::createFromFormat($this->format, $value) !== false;
} }
} }
...@@ -40,4 +40,3 @@ class DefaultValueValidator extends Validator ...@@ -40,4 +40,3 @@ class DefaultValueValidator extends Validator
} }
} }
} }
...@@ -99,4 +99,3 @@ class ExistValidator extends Validator ...@@ -99,4 +99,3 @@ class ExistValidator extends Validator
return $query->exists(); return $query->exists();
} }
} }
...@@ -6,6 +6,7 @@ ...@@ -6,6 +6,7 @@
*/ */
namespace yii\validators; namespace yii\validators;
use yii\base\InvalidConfigException; use yii\base\InvalidConfigException;
/** /**
......
...@@ -174,4 +174,3 @@ class StringValidator extends Validator ...@@ -174,4 +174,3 @@ class StringValidator extends Validator
return 'yii.validation.string(value, messages, ' . json_encode($options) . ');'; return 'yii.validation.string(value, messages, ' . json_encode($options) . ');';
} }
} }
...@@ -99,7 +99,7 @@ class UrlValidator extends Validator ...@@ -99,7 +99,7 @@ class UrlValidator extends Validator
} }
if ($this->enableIDN) { if ($this->enableIDN) {
$value = preg_replace_callback('/:\/\/([^\/]+)/', function($matches) { $value = preg_replace_callback('/:\/\/([^\/]+)/', function ($matches) {
return '://' . idn_to_ascii($matches[1]); return '://' . idn_to_ascii($matches[1]);
}, $value); }, $value);
} }
......
...@@ -99,7 +99,7 @@ class AccessRule extends Component ...@@ -99,7 +99,7 @@ class AccessRule extends Component
if ($this->matchAction($action) if ($this->matchAction($action)
&& $this->matchRole($user) && $this->matchRole($user)
&& $this->matchIP($request->getUserIP()) && $this->matchIP($request->getUserIP())
&& $this->matchVerb($request->getRequestMethod()) && $this->matchVerb($request->getMethod())
&& $this->matchController($action->controller) && $this->matchController($action->controller)
&& $this->matchCustom($action) && $this->matchCustom($action)
) { ) {
......
...@@ -277,11 +277,8 @@ class CaptchaAction extends Action ...@@ -277,11 +277,8 @@ class CaptchaAction extends Action
imagecolordeallocate($image, $foreColor); imagecolordeallocate($image, $foreColor);
header('Pragma: public'); $this->sendHttpHeaders();
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Transfer-Encoding: binary');
header("Content-type: image/png");
imagepng($image); imagepng($image);
imagedestroy($image); imagedestroy($image);
} }
...@@ -319,12 +316,21 @@ class CaptchaAction extends Action ...@@ -319,12 +316,21 @@ class CaptchaAction extends Action
$x += (int)($fontMetrics['textWidth']) + $this->offset; $x += (int)($fontMetrics['textWidth']) + $this->offset;
} }
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Transfer-Encoding: binary');
header("Content-type: image/png");
$image->setImageFormat('png'); $image->setImageFormat('png');
echo $image; Yii::$app->getResponse()->content = (string)$image;
$this->sendHttpHeaders();
}
/**
* Sends the HTTP headers needed by image response.
*/
protected function sendHttpHeaders()
{
Yii::$app->getResponse()->getHeaders()
->set('Pragma', 'public')
->set('Expires', '0')
->set('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')
->set('Content-Transfer-Encoding', 'binary')
->set('Content-type', 'image/png');
} }
} }
...@@ -45,7 +45,7 @@ class Cookie extends \yii\base\Object ...@@ -45,7 +45,7 @@ class Cookie extends \yii\base\Object
* By setting this property to true, the cookie will not be accessible by scripting languages, * By setting this property to true, the cookie will not be accessible by scripting languages,
* such as JavaScript, which can effectively help to reduce identity theft through XSS attacks. * such as JavaScript, which can effectively help to reduce identity theft through XSS attacks.
*/ */
public $httponly = false; public $httpOnly = false;
/** /**
* Magic method to turn a cookie object into a string without having to explicitly access [[value]]. * Magic method to turn a cookie object into a string without having to explicitly access [[value]].
......
...@@ -9,7 +9,8 @@ namespace yii\web; ...@@ -9,7 +9,8 @@ namespace yii\web;
use Yii; use Yii;
use ArrayIterator; use ArrayIterator;
use yii\helpers\SecurityHelper; use yii\base\InvalidCallException;
use yii\base\Object;
/** /**
* CookieCollection maintains the cookies available in the current request. * CookieCollection maintains the cookies available in the current request.
...@@ -19,17 +20,12 @@ use yii\helpers\SecurityHelper; ...@@ -19,17 +20,12 @@ use yii\helpers\SecurityHelper;
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
class CookieCollection extends \yii\base\Object implements \IteratorAggregate, \ArrayAccess, \Countable class CookieCollection extends Object implements \IteratorAggregate, \ArrayAccess, \Countable
{ {
/** /**
* @var boolean whether to enable cookie validation. By setting this property to true, * @var boolean whether this collection is read only.
* if a cookie is tampered on the client side, it will be ignored when received on the server side.
*/ */
public $enableValidation = true; public $readOnly = false;
/**
* @var string the secret key used for cookie validation. If not set, a random key will be generated and used.
*/
public $validationKey;
/** /**
* @var Cookie[] the cookies in this collection (indexed by the cookie names) * @var Cookie[] the cookies in this collection (indexed by the cookie names)
...@@ -38,12 +34,14 @@ class CookieCollection extends \yii\base\Object implements \IteratorAggregate, \ ...@@ -38,12 +34,14 @@ class CookieCollection extends \yii\base\Object implements \IteratorAggregate, \
/** /**
* Constructor. * Constructor.
* @param array $cookies the cookies that this collection initially contains. This should be
* an array of name-value pairs.s
* @param array $config name-value pairs that will be used to initialize the object properties * @param array $config name-value pairs that will be used to initialize the object properties
*/ */
public function __construct($config = array()) public function __construct($cookies = array(), $config = array())
{ {
$this->_cookies = $cookies;
parent::__construct($config); parent::__construct($config);
$this->_cookies = $this->loadCookies();
} }
/** /**
...@@ -100,54 +98,67 @@ class CookieCollection extends \yii\base\Object implements \IteratorAggregate, \ ...@@ -100,54 +98,67 @@ class CookieCollection extends \yii\base\Object implements \IteratorAggregate, \
return isset($this->_cookies[$name]) ? $this->_cookies[$name]->value : $defaultValue; return isset($this->_cookies[$name]) ? $this->_cookies[$name]->value : $defaultValue;
} }
/**
* Returns whether there is a cookie with the specified name.
* @param string $name the cookie name
* @return boolean whether the named cookie exists
*/
public function has($name)
{
return isset($this->_cookies[$name]);
}
/** /**
* Adds a cookie to the collection. * Adds a cookie to the collection.
* If there is already a cookie with the same name in the collection, it will be removed first. * If there is already a cookie with the same name in the collection, it will be removed first.
* @param Cookie $cookie the cookie to be added * @param Cookie $cookie the cookie to be added
* @throws InvalidCallException if the cookie collection is read only
*/ */
public function add($cookie) public function add($cookie)
{ {
if (isset($this->_cookies[$cookie->name])) { if ($this->readOnly) {
$c = $this->_cookies[$cookie->name]; throw new InvalidCallException('The cookie collection is read only.');
setcookie($c->name, '', 0, $c->path, $c->domain, $c->secure, $c->httponly);
}
$value = $cookie->value;
if ($this->enableValidation) {
if ($this->validationKey === null) {
$key = SecurityHelper::getSecretKey(__CLASS__ . '/' . Yii::$app->id);
} else {
$key = $this->validationKey;
} }
$value = SecurityHelper::hashData(serialize($value), $key);
}
setcookie($cookie->name, $value, $cookie->expire, $cookie->path, $cookie->domain, $cookie->secure, $cookie->httponly);
$this->_cookies[$cookie->name] = $cookie; $this->_cookies[$cookie->name] = $cookie;
} }
/** /**
* Removes a cookie from the collection. * Removes a cookie.
* If `$removeFromBrowser` is true, the cookie will be removed from the browser.
* In this case, a cookie with outdated expiry will be added to the collection.
* @param Cookie|string $cookie the cookie object or the name of the cookie to be removed. * @param Cookie|string $cookie the cookie object or the name of the cookie to be removed.
* @param boolean $removeFromBrowser whether to remove the cookie from browser
* @throws InvalidCallException if the cookie collection is read only
*/ */
public function remove($cookie) public function remove($cookie, $removeFromBrowser = true)
{ {
if (is_string($cookie) && isset($this->_cookies[$cookie])) { if ($this->readOnly) {
$cookie = $this->_cookies[$cookie]; throw new InvalidCallException('The cookie collection is read only.');
} }
if ($cookie instanceof Cookie) { if ($cookie instanceof Cookie) {
setcookie($cookie->name, '', 0, $cookie->path, $cookie->domain, $cookie->secure, $cookie->httponly); $cookie->expire = 1;
$cookie->value = '';
} else {
$cookie = new Cookie(array(
'name' => $cookie,
'expire' => 1,
));
}
if ($removeFromBrowser) {
$this->_cookies[$cookie->name] = $cookie;
} else {
unset($this->_cookies[$cookie->name]); unset($this->_cookies[$cookie->name]);
} }
} }
/** /**
* Removes all cookies. * Removes all cookies.
* @throws InvalidCallException if the cookie collection is read only
*/ */
public function removeAll() public function removeAll()
{ {
foreach ($this->_cookies as $cookie) { if ($this->readOnly) {
setcookie($cookie->name, '', 0, $cookie->path, $cookie->domain, $cookie->secure, $cookie->httponly); throw new InvalidCallException('The cookie collection is read only.');
} }
$this->_cookies = array(); $this->_cookies = array();
} }
...@@ -172,7 +183,7 @@ class CookieCollection extends \yii\base\Object implements \IteratorAggregate, \ ...@@ -172,7 +183,7 @@ class CookieCollection extends \yii\base\Object implements \IteratorAggregate, \
*/ */
public function offsetExists($name) public function offsetExists($name)
{ {
return isset($this->_cookies[$name]); return $this->has($name);
} }
/** /**
...@@ -212,36 +223,4 @@ class CookieCollection extends \yii\base\Object implements \IteratorAggregate, \ ...@@ -212,36 +223,4 @@ class CookieCollection extends \yii\base\Object implements \IteratorAggregate, \
{ {
$this->remove($name); $this->remove($name);
} }
/**
* Returns the current cookies in terms of [[Cookie]] objects.
* @return Cookie[] list of current cookies
*/
protected function loadCookies()
{
$cookies = array();
if ($this->enableValidation) {
if ($this->validationKey === null) {
$key = SecurityHelper::getSecretKey(__CLASS__ . '/' . Yii::$app->id);
} else {
$key = $this->validationKey;
}
foreach ($_COOKIE as $name => $value) {
if (is_string($value) && ($value = SecurityHelper::validateData($value, $key)) !== false) {
$cookies[$name] = new Cookie(array(
'name' => $name,
'value' => @unserialize($value),
));
}
}
} else {
foreach ($_COOKIE as $name => $value) {
$cookies[$name] = new Cookie(array(
'name' => $name,
'value' => $value,
));
}
}
return $cookies;
}
} }
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\web;
use Yii;
use yii\base\Object;
use ArrayIterator;
/**
* HeaderCollection is used by [[Response]] to maintain the currently registered HTTP headers.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class HeaderCollection extends Object implements \IteratorAggregate, \ArrayAccess, \Countable
{
/**
* @var array the headers in this collection (indexed by the header names)
*/
private $_headers = array();
/**
* Returns an iterator for traversing the headers in the collection.
* This method is required by the SPL interface `IteratorAggregate`.
* It will be implicitly called when you use `foreach` to traverse the collection.
* @return ArrayIterator an iterator for traversing the headers in the collection.
*/
public function getIterator()
{
return new ArrayIterator($this->_headers);
}
/**
* Returns the number of headers in the collection.
* This method is required by the SPL `Countable` interface.
* It will be implicitly called when you use `count($collection)`.
* @return integer the number of headers in the collection.
*/
public function count()
{
return $this->getCount();
}
/**
* Returns the number of headers in the collection.
* @return integer the number of headers in the collection.
*/
public function getCount()
{
return count($this->_headers);
}
/**
* Returns the named header(s).
* @param string $name the name of the header to return
* @param mixed $default the value to return in case the named header does not exist
* @param boolean $first whether to only return the first header of the specified name.
* If false, all headers of the specified name will be returned.
* @return string|array the named header(s). If `$first` is true, a string will be returned;
* If `$first` is false, an array will be returned.
*/
public function get($name, $default = null, $first = true)
{
$name = strtolower($name);
if (isset($this->_headers[$name])) {
return $first ? reset($this->_headers[$name]) : $this->_headers[$name];
} else {
return $default;
}
}
/**
* Adds a new header.
* If there is already a header with the same name, it will be replaced.
* @param string $name the name of the header
* @param string $value the value of the header
* @return HeaderCollection the collection object itself
*/
public function set($name, $value = '')
{
$name = strtolower($name);
$this->_headers[$name] = (array)$value;
return $this;
}
/**
* Adds a new header.
* If there is already a header with the same name, the new one will
* be appended to it instead of replacing it.
* @param string $name the name of the header
* @param string $value the value of the header
* @return HeaderCollection the collection object itself
*/
public function add($name, $value)
{
$name = strtolower($name);
$this->_headers[$name][] = $value;
return $this;
}
/**
* Returns a value indicating whether the named header exists.
* @param string $name the name of the header
* @return boolean whether the named header exists
*/
public function has($name)
{
$name = strtolower($name);
return isset($this->_headers[$name]);
}
/**
* Removes a header.
* @param string $name the name of the header to be removed.
* @return string the value of the removed header. Null is returned if the header does not exist.
*/
public function remove($name)
{
$name = strtolower($name);
if (isset($this->_headers[$name])) {
$value = $this->_headers[$name];
unset($this->_headers[$name]);
return $value;
} else {
return null;
}
}
/**
* Removes all headers.
*/
public function removeAll()
{
$this->_headers = array();
}
/**
* Returns the collection as a PHP array.
* @return array the array representation of the collection.
* The array keys are header names, and the array values are the corresponding header values.
*/
public function toArray()
{
return $this->_headers;
}
/**
* Returns whether there is a header with the specified name.
* This method is required by the SPL interface `ArrayAccess`.
* It is implicitly called when you use something like `isset($collection[$name])`.
* @param string $name the header name
* @return boolean whether the named header exists
*/
public function offsetExists($name)
{
return $this->has($name);
}
/**
* Returns the header with the specified name.
* This method is required by the SPL interface `ArrayAccess`.
* It is implicitly called when you use something like `$header = $collection[$name];`.
* This is equivalent to [[get()]].
* @param string $name the header name
* @return string the header value with the specified name, null if the named header does not exist.
*/
public function offsetGet($name)
{
return $this->get($name);
}
/**
* Adds the header to the collection.
* This method is required by the SPL interface `ArrayAccess`.
* It is implicitly called when you use something like `$collection[$name] = $header;`.
* This is equivalent to [[add()]].
* @param string $name the header name
* @param string $value the header value to be added
*/
public function offsetSet($name, $value)
{
$this->set($name, $value);
}
/**
* Removes the named header.
* This method is required by the SPL interface `ArrayAccess`.
* It is implicitly called when you use something like `unset($collection[$name])`.
* This is equivalent to [[remove()]].
* @param string $name the header name
*/
public function offsetUnset($name)
{
$this->remove($name);
}
}
...@@ -50,7 +50,7 @@ class HttpCache extends ActionFilter ...@@ -50,7 +50,7 @@ class HttpCache extends ActionFilter
/** /**
* @var string HTTP cache control header. If null, the header will not be sent. * @var string HTTP cache control header. If null, the header will not be sent.
*/ */
public $cacheControlHeader = 'Cache-Control: max-age=3600, public'; public $cacheControlHeader = 'max-age=3600, public';
/** /**
* This method is invoked right before an action is to be executed (after all possible filters.) * This method is invoked right before an action is to be executed (after all possible filters.)
...@@ -60,7 +60,7 @@ class HttpCache extends ActionFilter ...@@ -60,7 +60,7 @@ class HttpCache extends ActionFilter
*/ */
public function beforeAction($action) public function beforeAction($action)
{ {
$verb = Yii::$app->request->getRequestMethod(); $verb = Yii::$app->getRequest()->getMethod();
if ($verb !== 'GET' && $verb !== 'HEAD' || $this->lastModified === null && $this->etagSeed === null) { if ($verb !== 'GET' && $verb !== 'HEAD' || $this->lastModified === null && $this->etagSeed === null) {
return true; return true;
} }
...@@ -75,17 +75,18 @@ class HttpCache extends ActionFilter ...@@ -75,17 +75,18 @@ class HttpCache extends ActionFilter
} }
$this->sendCacheControlHeader(); $this->sendCacheControlHeader();
$response = Yii::$app->getResponse();
if ($etag !== null) { if ($etag !== null) {
header("ETag: $etag"); $response->getHeaders()->set('Etag', $etag);
} }
if ($this->validateCache($lastModified, $etag)) { if ($this->validateCache($lastModified, $etag)) {
header('HTTP/1.1 304 Not Modified'); $response->setStatusCode(304);
return false; return false;
} }
if ($lastModified !== null) { if ($lastModified !== null) {
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $lastModified) . ' GMT'); $response->getHeaders()->set('Last-Modified', gmdate('D, d M Y H:i:s', $lastModified) . ' GMT');
} }
return true; return true;
} }
...@@ -113,9 +114,10 @@ class HttpCache extends ActionFilter ...@@ -113,9 +114,10 @@ class HttpCache extends ActionFilter
protected function sendCacheControlHeader() protected function sendCacheControlHeader()
{ {
session_cache_limiter('public'); session_cache_limiter('public');
header('Pragma:', true); $headers = Yii::$app->getResponse()->getHeaders();
$headers->set('Pragma');
if ($this->cacheControlHeader !== null) { if ($this->cacheControlHeader !== null) {
header($this->cacheControlHeader, true); $headers->set('Cache-Control', $this->cacheControlHeader);
} }
} }
......
...@@ -10,6 +10,7 @@ namespace yii\web; ...@@ -10,6 +10,7 @@ namespace yii\web;
use Yii; use Yii;
use yii\base\HttpException; use yii\base\HttpException;
use yii\base\InvalidConfigException; use yii\base\InvalidConfigException;
use yii\helpers\SecurityHelper;
/** /**
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
...@@ -37,19 +38,15 @@ class Request extends \yii\base\Request ...@@ -37,19 +38,15 @@ class Request extends \yii\base\Request
* @var array the configuration of the CSRF cookie. This property is used only when [[enableCsrfValidation]] is true. * @var array the configuration of the CSRF cookie. This property is used only when [[enableCsrfValidation]] is true.
* @see Cookie * @see Cookie
*/ */
public $csrfCookie = array('httponly' => true); public $csrfCookie = array('httpOnly' => true);
/** /**
* @var boolean whether cookies should be validated to ensure they are not tampered. Defaults to true. * @var boolean whether cookies should be validated to ensure they are not tampered. Defaults to true.
*/ */
public $enableCookieValidation = true; public $enableCookieValidation = true;
/**
* @var string the secret key used for cookie validation. If not set, a random key will be generated and used.
*/
public $cookieValidationKey;
/** /**
* @var string|boolean the name of the POST parameter that is used to indicate if a request is a PUT or DELETE * @var string|boolean the name of the POST parameter that is used to indicate if a request is a PUT or DELETE
* request tunneled through POST. Default to '_method'. * request tunneled through POST. Default to '_method'.
* @see getRequestMethod * @see getMethod
* @see getRestParams * @see getRestParams
*/ */
public $restVar = '_method'; public $restVar = '_method';
...@@ -81,7 +78,7 @@ class Request extends \yii\base\Request ...@@ -81,7 +78,7 @@ class Request extends \yii\base\Request
* @return string request method, such as GET, POST, HEAD, PUT, DELETE. * @return string request method, such as GET, POST, HEAD, PUT, DELETE.
* The value returned is turned into upper case. * The value returned is turned into upper case.
*/ */
public function getRequestMethod() public function getMethod()
{ {
if (isset($_POST[$this->restVar])) { if (isset($_POST[$this->restVar])) {
return strtoupper($_POST[$this->restVar]); return strtoupper($_POST[$this->restVar]);
...@@ -94,34 +91,34 @@ class Request extends \yii\base\Request ...@@ -94,34 +91,34 @@ class Request extends \yii\base\Request
* Returns whether this is a POST request. * Returns whether this is a POST request.
* @return boolean whether this is a POST request. * @return boolean whether this is a POST request.
*/ */
public function getIsPostRequest() public function getIsPost()
{ {
return $this->getRequestMethod() === 'POST'; return $this->getMethod() === 'POST';
} }
/** /**
* Returns whether this is a DELETE request. * Returns whether this is a DELETE request.
* @return boolean whether this is a DELETE request. * @return boolean whether this is a DELETE request.
*/ */
public function getIsDeleteRequest() public function getIsDelete()
{ {
return $this->getRequestMethod() === 'DELETE'; return $this->getMethod() === 'DELETE';
} }
/** /**
* Returns whether this is a PUT request. * Returns whether this is a PUT request.
* @return boolean whether this is a PUT request. * @return boolean whether this is a PUT request.
*/ */
public function getIsPutRequest() public function getIsPut()
{ {
return $this->getRequestMethod() === 'PUT'; return $this->getMethod() === 'PUT';
} }
/** /**
* Returns whether this is an AJAX (XMLHttpRequest) request. * Returns whether this is an AJAX (XMLHttpRequest) request.
* @return boolean whether this is an AJAX (XMLHttpRequest) request. * @return boolean whether this is an AJAX (XMLHttpRequest) request.
*/ */
public function getIsAjaxRequest() public function getIsAjax()
{ {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest'; return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';
} }
...@@ -130,7 +127,7 @@ class Request extends \yii\base\Request ...@@ -130,7 +127,7 @@ class Request extends \yii\base\Request
* Returns whether this is an Adobe Flash or Flex request. * Returns whether this is an Adobe Flash or Flex request.
* @return boolean whether this is an Adobe Flash or Adobe Flex request. * @return boolean whether this is an Adobe Flash or Adobe Flex request.
*/ */
public function getIsFlashRequest() public function getIsFlash()
{ {
return isset($_SERVER['HTTP_USER_AGENT']) && return isset($_SERVER['HTTP_USER_AGENT']) &&
(stripos($_SERVER['HTTP_USER_AGENT'], 'Shockwave') !== false || stripos($_SERVER['HTTP_USER_AGENT'], 'Flash') !== false); (stripos($_SERVER['HTTP_USER_AGENT'], 'Shockwave') !== false || stripos($_SERVER['HTTP_USER_AGENT'], 'Flash') !== false);
...@@ -141,7 +138,7 @@ class Request extends \yii\base\Request ...@@ -141,7 +138,7 @@ class Request extends \yii\base\Request
/** /**
* Returns the request parameters for the RESTful request. * Returns the request parameters for the RESTful request.
* @return array the RESTful request parameters * @return array the RESTful request parameters
* @see getRequestMethod * @see getMethod
*/ */
public function getRestParams() public function getRestParams()
{ {
...@@ -203,7 +200,7 @@ class Request extends \yii\base\Request ...@@ -203,7 +200,7 @@ class Request extends \yii\base\Request
* @return mixed the GET parameter value * @return mixed the GET parameter value
* @see getPost * @see getPost
*/ */
public function getParam($name, $defaultValue = null) public function get($name, $defaultValue = null)
{ {
return isset($_GET[$name]) ? $_GET[$name] : $defaultValue; return isset($_GET[$name]) ? $_GET[$name] : $defaultValue;
} }
...@@ -229,7 +226,7 @@ class Request extends \yii\base\Request ...@@ -229,7 +226,7 @@ class Request extends \yii\base\Request
*/ */
public function getDelete($name, $defaultValue = null) public function getDelete($name, $defaultValue = null)
{ {
return $this->getIsDeleteRequest() ? $this->getRestParam($name, $defaultValue) : null; return $this->getIsDelete() ? $this->getRestParam($name, $defaultValue) : null;
} }
/** /**
...@@ -240,7 +237,7 @@ class Request extends \yii\base\Request ...@@ -240,7 +237,7 @@ class Request extends \yii\base\Request
*/ */
public function getPut($name, $defaultValue = null) public function getPut($name, $defaultValue = null)
{ {
return $this->getIsPutRequest() ? $this->getRestParam($name, $defaultValue) : null; return $this->getIsPut() ? $this->getRestParam($name, $defaultValue) : null;
} }
private $_hostInfo; private $_hostInfo;
...@@ -717,14 +714,64 @@ class Request extends \yii\base\Request ...@@ -717,14 +714,64 @@ class Request extends \yii\base\Request
public function getCookies() public function getCookies()
{ {
if ($this->_cookies === null) { if ($this->_cookies === null) {
$this->_cookies = new CookieCollection(array( $this->_cookies = new CookieCollection($this->loadCookies(), array(
'enableValidation' => $this->enableCookieValidation, 'readOnly' => true,
'validationKey' => $this->cookieValidationKey,
)); ));
} }
return $this->_cookies; return $this->_cookies;
} }
/**
* Converts `$_COOKIE` into an array of [[Cookie]].
* @return array the cookies obtained from request
*/
protected function loadCookies()
{
$cookies = array();
if ($this->enableCookieValidation) {
$key = $this->getCookieValidationKey();
foreach ($_COOKIE as $name => $value) {
if (is_string($value) && ($value = SecurityHelper::validateData($value, $key)) !== false) {
$cookies[$name] = new Cookie(array(
'name' => $name,
'value' => @unserialize($value),
));
}
}
} else {
foreach ($_COOKIE as $name => $value) {
$cookies[$name] = new Cookie(array(
'name' => $name,
'value' => $value,
));
}
}
return $cookies;
}
private $_cookieValidationKey;
/**
* @return string the secret key used for cookie validation. If it was set previously,
* a random key will be generated and used.
*/
public function getCookieValidationKey()
{
if ($this->_cookieValidationKey === null) {
$this->_cookieValidationKey = SecurityHelper::getSecretKey(__CLASS__ . '/' . Yii::$app->id);
}
return $this->_cookieValidationKey;
}
/**
* Sets the secret key used for cookie validation.
* @param string $value the secret key used for cookie validation.
*/
public function setCookieValidationKey($value)
{
$this->_cookieValidationKey = $value;
}
private $_csrfToken; private $_csrfToken;
/** /**
...@@ -772,7 +819,7 @@ class Request extends \yii\base\Request ...@@ -772,7 +819,7 @@ class Request extends \yii\base\Request
if (!$this->enableCsrfValidation) { if (!$this->enableCsrfValidation) {
return; return;
} }
$method = $this->getRequestMethod(); $method = $this->getMethod();
if ($method === 'POST' || $method === 'PUT' || $method === 'DELETE') { if ($method === 'POST' || $method === 'PUT' || $method === 'DELETE') {
$cookies = $this->getCookies(); $cookies = $this->getCookies();
switch ($method) { switch ($method) {
...@@ -792,4 +839,3 @@ class Request extends \yii\base\Request ...@@ -792,4 +839,3 @@ class Request extends \yii\base\Request
} }
} }
} }
...@@ -9,8 +9,11 @@ namespace yii\web; ...@@ -9,8 +9,11 @@ namespace yii\web;
use Yii; use Yii;
use yii\base\HttpException; use yii\base\HttpException;
use yii\base\InvalidParamException;
use yii\helpers\FileHelper; use yii\helpers\FileHelper;
use yii\helpers\Html; use yii\helpers\Html;
use yii\helpers\Json;
use yii\helpers\SecurityHelper;
use yii\helpers\StringHelper; use yii\helpers\StringHelper;
/** /**
...@@ -27,6 +30,237 @@ class Response extends \yii\base\Response ...@@ -27,6 +30,237 @@ class Response extends \yii\base\Response
* @see redirect * @see redirect
*/ */
public $ajaxRedirectCode = 278; public $ajaxRedirectCode = 278;
/**
* @var string
*/
public $content;
/**
* @var string
*/
public $statusText;
/**
* @var string the charset to use. If not set, [[\yii\base\Application::charset]] will be used.
*/
public $charset;
/**
* @var string the version of the HTTP protocol to use
*/
public $version = '1.0';
/**
* @var array list of HTTP status codes and the corresponding texts
*/
public static $statusTexts = array(
100 => 'Continue',
101 => 'Switching Protocols',
102 => 'Processing',
118 => 'Connection timed out',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
207 => 'Multi-Status',
208 => 'Already Reported',
210 => 'Content Different',
226 => 'IM Used',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
306 => 'Reserved',
307 => 'Temporary Redirect',
308 => 'Permanent Redirect',
310 => 'Too many Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Time-out',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested range unsatisfiable',
417 => 'Expectation failed',
418 => 'I’m a teapot',
422 => 'Unprocessable entity',
423 => 'Locked',
424 => 'Method failure',
425 => 'Unordered Collection',
426 => 'Upgrade Required',
428 => 'Precondition Required',
429 => 'Too Many Requests',
431 => 'Request Header Fields Too Large',
449 => 'Retry With',
450 => 'Blocked by Windows Parental Controls',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway ou Proxy Error',
503 => 'Service Unavailable',
504 => 'Gateway Time-out',
505 => 'HTTP Version not supported',
507 => 'Insufficient storage',
508 => 'Loop Detected',
509 => 'Bandwidth Limit Exceeded',
510 => 'Not Extended',
511 => 'Network Authentication Required',
);
private $_statusCode;
/**
* @var HeaderCollection
*/
private $_headers;
public function init()
{
if ($this->charset === null) {
$this->charset = Yii::$app->charset;
}
}
public function begin()
{
parent::begin();
$this->beginOutput();
}
public function end()
{
$this->content .= $this->endOutput();
$this->send();
parent::end();
}
public function getStatusCode()
{
return $this->_statusCode;
}
public function setStatusCode($value, $text = null)
{
$this->_statusCode = (int)$value;
if ($this->isInvalid()) {
throw new InvalidParamException("The HTTP status code is invalid: $value");
}
if ($text === null) {
$this->statusText = isset(self::$statusTexts[$this->_statusCode]) ? self::$statusTexts[$this->_statusCode] : '';
} else {
$this->statusText = $text;
}
}
/**
* Returns the header collection.
* The header collection contains the currently registered HTTP headers.
* @return HeaderCollection the header collection
*/
public function getHeaders()
{
if ($this->_headers === null) {
$this->_headers = new HeaderCollection;
}
return $this->_headers;
}
public function renderJson($data)
{
$this->getHeaders()->set('content-type', 'application/json');
$this->content = Json::encode($data);
}
public function renderJsonp($data, $callbackName)
{
$this->getHeaders()->set('content-type', 'text/javascript');
$data = Json::encode($data);
$this->content = "$callbackName($data);";
}
/**
* Sends the response to the client.
* @return boolean true if the response was sent
*/
public function send()
{
$this->sendHeaders();
$this->sendContent();
}
public function reset()
{
$this->_headers = null;
$this->_statusCode = null;
$this->statusText = null;
$this->content = null;
}
/**
* Sends the response headers to the client
*/
protected function sendHeaders()
{
if (headers_sent()) {
return;
}
$statusCode = $this->getStatusCode();
if ($statusCode !== null) {
header("HTTP/{$this->version} $statusCode {$this->statusText}");
}
if ($this->_headers) {
$headers = $this->getHeaders();
foreach ($headers as $name => $values) {
foreach ($values as $value) {
header("$name: $value", false);
}
}
$headers->removeAll();
}
$this->sendCookies();
}
/**
* Sends the cookies to the client.
*/
protected function sendCookies()
{
if ($this->_cookies === null) {
return;
}
$request = Yii::$app->getRequest();
if ($request->enableCookieValidation) {
$validationKey = $request->getCookieValidationKey();
}
foreach ($this->getCookies() as $cookie) {
$value = $cookie->value;
if ($cookie->expire != 1 && isset($validationKey)) {
$value = SecurityHelper::hashData(serialize($value), $validationKey);
}
setcookie($cookie->name, $value, $cookie->expire, $cookie->path, $cookie->domain, $cookie->secure, $cookie->httpOnly);
}
$this->getCookies()->removeAll();
}
/**
* Sends the response content to the client
*/
protected function sendContent()
{
echo $this->content;
$this->content = null;
}
/** /**
* Sends a file to user. * Sends a file to user.
...@@ -46,13 +280,15 @@ class Response extends \yii\base\Response ...@@ -46,13 +280,15 @@ class Response extends \yii\base\Response
$contentStart = 0; $contentStart = 0;
$contentEnd = $fileSize - 1; $contentEnd = $fileSize - 1;
$headers = $this->getHeaders();
// tell the client that we accept range requests // tell the client that we accept range requests
header('Accept-Ranges: bytes'); $headers->set('Accept-Ranges', 'bytes');
if (isset($_SERVER['HTTP_RANGE'])) { if (isset($_SERVER['HTTP_RANGE'])) {
// client sent us a multibyte range, can not hold this one for now // client sent us a multibyte range, can not hold this one for now
if (strpos($_SERVER['HTTP_RANGE'],',') !== false) { if (strpos($_SERVER['HTTP_RANGE'], ',') !== false) {
header("Content-Range: bytes $contentStart-$contentEnd/$fileSize"); $headers->set('Content-Range', "bytes $contentStart-$contentEnd/$fileSize");
throw new HttpException(416, 'Requested Range Not Satisfiable'); throw new HttpException(416, 'Requested Range Not Satisfiable');
} }
...@@ -75,31 +311,32 @@ class Response extends \yii\base\Response ...@@ -75,31 +311,32 @@ class Response extends \yii\base\Response
* http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
*/ */
// End bytes can not be larger than $end. // End bytes can not be larger than $end.
$contentEnd = ($contentEnd > $fileSize) ? $fileSize -1 : $contentEnd; $contentEnd = ($contentEnd > $fileSize) ? $fileSize - 1 : $contentEnd;
// Validate the requested range and return an error if it's not correct. // Validate the requested range and return an error if it's not correct.
$wrongContentStart = ($contentStart > $contentEnd || $contentStart > $fileSize - 1 || $contentStart < 0); $wrongContentStart = ($contentStart > $contentEnd || $contentStart > $fileSize - 1 || $contentStart < 0);
if ($wrongContentStart) { if ($wrongContentStart) {
header("Content-Range: bytes $contentStart-$contentEnd/$fileSize"); $headers->set('Content-Range', "bytes $contentStart-$contentEnd/$fileSize");
throw new HttpException(416, 'Requested Range Not Satisfiable'); throw new HttpException(416, 'Requested Range Not Satisfiable');
} }
header('HTTP/1.1 206 Partial Content'); $this->setStatusCode(206);
header("Content-Range: bytes $contentStart-$contentEnd/$fileSize"); $headers->set('Content-Range', "bytes $contentStart-$contentEnd/$fileSize");
} else { } else {
header('HTTP/1.1 200 OK'); $this->setStatusCode(200);
} }
$length = $contentEnd - $contentStart + 1; // Calculate new content length $length = $contentEnd - $contentStart + 1; // Calculate new content length
header('Pragma: public'); $headers->set('Pragma', 'public')
header('Expires: 0'); ->set('Expires', '0')
header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); ->set('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')
header('Content-Type: ' . $mimeType); ->set('Content-Type', $mimeType)
header('Content-Length: ' . $length); ->set('Content-Length', $length)
header('Content-Disposition: attachment; filename="' . $fileName . '"'); ->set('Content-Disposition', "attachment; filename=\"$fileName\"")
header('Content-Transfer-Encoding: binary'); ->set('Content-Transfer-Encoding', 'binary');
$content = StringHelper::substr($content, $contentStart, $length); $content = StringHelper::substr($content, $contentStart, $length);
if ($terminate) { if ($terminate) {
...@@ -108,10 +345,10 @@ class Response extends \yii\base\Response ...@@ -108,10 +345,10 @@ class Response extends \yii\base\Response
ob_start(); ob_start();
Yii::$app->end(0, false); Yii::$app->end(0, false);
ob_end_clean(); ob_end_clean();
echo $content; $this->content = $content;
exit(0); exit(0);
} else { } else {
echo $content; $this->content = $content;
} }
} }
...@@ -186,7 +423,7 @@ class Response extends \yii\base\Response ...@@ -186,7 +423,7 @@ class Response extends \yii\base\Response
} }
if (!isset($options['mimeType'])) { if (!isset($options['mimeType'])) {
if (($options['mimeType'] = CFileHelper::getMimeTypeByExtension($filePath)) === null) { if (($options['mimeType'] = FileHelper::getMimeTypeByExtension($filePath)) === null) {
$options['mimeType'] = 'text/plain'; $options['mimeType'] = 'text/plain';
} }
} }
...@@ -195,16 +432,18 @@ class Response extends \yii\base\Response ...@@ -195,16 +432,18 @@ class Response extends \yii\base\Response
$options['xHeader'] = 'X-Sendfile'; $options['xHeader'] = 'X-Sendfile';
} }
$headers = $this->getHeaders();
if ($options['mimeType'] !== null) { if ($options['mimeType'] !== null) {
header('Content-type: ' . $options['mimeType']); $headers->set('Content-Type', $options['mimeType']);
} }
header('Content-Disposition: ' . $disposition . '; filename="' . $options['saveName'] . '"'); $headers->set('Content-Disposition', "$disposition; filename=\"{$options['saveName']}\"");
if (isset($options['addHeaders'])) { if (isset($options['addHeaders'])) {
foreach ($options['addHeaders'] as $header => $value) { foreach ($options['addHeaders'] as $header => $value) {
header($header . ': ' . $value); $headers->set($header, $value);
} }
} }
header(trim($options['xHeader']) . ': ' . $filePath); $headers->set(trim($options['xHeader']), $filePath);
if (!isset($options['terminate']) || $options['terminate']) { if (!isset($options['terminate']) || $options['terminate']) {
Yii::$app->end(); Yii::$app->end();
...@@ -243,10 +482,11 @@ class Response extends \yii\base\Response ...@@ -243,10 +482,11 @@ class Response extends \yii\base\Response
if (strpos($url, '/') === 0 && strpos($url, '//') !== 0) { if (strpos($url, '/') === 0 && strpos($url, '//') !== 0) {
$url = Yii::$app->getRequest()->getHostInfo() . $url; $url = Yii::$app->getRequest()->getHostInfo() . $url;
} }
if (Yii::$app->getRequest()->getIsAjaxRequest()) { if (Yii::$app->getRequest()->getIsAjax()) {
$statusCode = $this->ajaxRedirectCode; $statusCode = $this->ajaxRedirectCode;
} }
header('Location: ' . $url, true, $statusCode); $this->getHeaders()->set('Location', $url);
$this->setStatusCode($statusCode);
if ($terminate) { if ($terminate) {
Yii::$app->end(); Yii::$app->end();
} }
...@@ -265,6 +505,8 @@ class Response extends \yii\base\Response ...@@ -265,6 +505,8 @@ class Response extends \yii\base\Response
$this->redirect(Yii::$app->getRequest()->getUrl() . $anchor, $terminate); $this->redirect(Yii::$app->getRequest()->getUrl() . $anchor, $terminate);
} }
private $_cookies;
/** /**
* Returns the cookie collection. * Returns the cookie collection.
* Through the returned cookie collection, you add or remove cookies as follows, * Through the returned cookie collection, you add or remove cookies as follows,
...@@ -286,6 +528,89 @@ class Response extends \yii\base\Response ...@@ -286,6 +528,89 @@ class Response extends \yii\base\Response
*/ */
public function getCookies() public function getCookies()
{ {
return Yii::$app->getRequest()->getCookies(); if ($this->_cookies === null) {
$this->_cookies = new CookieCollection;
}
return $this->_cookies;
}
/**
* @return boolean whether this response has a valid [[statusCode]].
*/
public function isInvalid()
{
return $this->getStatusCode() < 100 || $this->getStatusCode() >= 600;
}
/**
* @return boolean whether this response is informational
*/
public function isInformational()
{
return $this->getStatusCode() >= 100 && $this->getStatusCode() < 200;
}
/**
* @return boolean whether this response is successfully
*/
public function isSuccessful()
{
return $this->getStatusCode() >= 200 && $this->getStatusCode() < 300;
}
/**
* @return boolean whether this response is a redirection
*/
public function isRedirection()
{
return $this->getStatusCode() >= 300 && $this->getStatusCode() < 400;
}
/**
* @return boolean whether this response indicates a client error
*/
public function isClientError()
{
return $this->getStatusCode() >= 400 && $this->getStatusCode() < 500;
}
/**
* @return boolean whether this response indicates a server error
*/
public function isServerError()
{
return $this->getStatusCode() >= 500 && $this->getStatusCode() < 600;
}
/**
* @return boolean whether this response is OK
*/
public function isOk()
{
return 200 === $this->getStatusCode();
}
/**
* @return boolean whether this response indicates the current request is forbidden
*/
public function isForbidden()
{
return 403 === $this->getStatusCode();
}
/**
* @return boolean whether this response indicates the currently requested resource is not found
*/
public function isNotFound()
{
return 404 === $this->getStatusCode();
}
/**
* @return boolean whether this response is empty
*/
public function isEmpty()
{
return in_array($this->getStatusCode(), array(201, 204, 304));
} }
} }
...@@ -63,7 +63,7 @@ class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Co ...@@ -63,7 +63,7 @@ class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Co
* @var array parameter-value pairs to override default session cookie parameters * @var array parameter-value pairs to override default session cookie parameters
*/ */
public $cookieParams = array( public $cookieParams = array(
'httponly' => true 'httpOnly' => true
); );
/** /**
...@@ -241,26 +241,31 @@ class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Co ...@@ -241,26 +241,31 @@ class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Co
*/ */
public function getCookieParams() public function getCookieParams()
{ {
return session_get_cookie_params(); $params = session_get_cookie_params();
if (isset($params['httponly'])) {
$params['httpOnly'] = $params['httponly'];
unset($params['httponly']);
}
return $params;
} }
/** /**
* Sets the session cookie parameters. * Sets the session cookie parameters.
* The effect of this method only lasts for the duration of the script. * The effect of this method only lasts for the duration of the script.
* Call this method before the session starts. * Call this method before the session starts.
* @param array $value cookie parameters, valid keys include: lifetime, path, domain, secure and httponly. * @param array $value cookie parameters, valid keys include: `lifetime`, `path`, `domain`, `secure` and `httpOnly`.
* @throws InvalidParamException if the parameters are incomplete. * @throws InvalidParamException if the parameters are incomplete.
* @see http://us2.php.net/manual/en/function.session-set-cookie-params.php * @see http://us2.php.net/manual/en/function.session-set-cookie-params.php
*/ */
public function setCookieParams($value) public function setCookieParams($value)
{ {
$data = session_get_cookie_params(); $data = $this->getCookieParams();
extract($data); extract($data);
extract($value); extract($value);
if (isset($lifetime, $path, $domain, $secure, $httponly)) { if (isset($lifetime, $path, $domain, $secure, $httpOnly)) {
session_set_cookie_params($lifetime, $path, $domain, $secure, $httponly); session_set_cookie_params($lifetime, $path, $domain, $secure, $httpOnly);
} else { } else {
throw new InvalidParamException('Please make sure these parameters are provided: lifetime, path, domain, secure and httponly.'); throw new InvalidParamException('Please make sure these parameters are provided: lifetime, path, domain, secure and httpOnly.');
} }
} }
......
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
namespace yii\web; namespace yii\web;
use yii\widgets\Html; use yii\helpers\Html;
/** /**
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
......
...@@ -43,6 +43,31 @@ class UrlManager extends Component ...@@ -43,6 +43,31 @@ class UrlManager extends Component
* array, one can use the key to represent the pattern and the value the corresponding route. * array, one can use the key to represent the pattern and the value the corresponding route.
* For example, `'post/<id:\d+>' => 'post/view'`. * For example, `'post/<id:\d+>' => 'post/view'`.
* *
* For RESTful routing the mentioned shortcut format also allows you to specify the
* [[UrlRule::verb|HTTP verb]] that the rule should apply for.
* You can do that by prepending it to the pattern, separated by space.
* For example, `'PUT post/<id:\d+>' => 'post/update'`.
* You may specify multiple verbs by separating them with comma
* like this: `'POST,PUT post/index' => 'post/create'`.
* The supported verbs in the shortcut format are: GET, HEAD, POST, PUT and DELETE.
* Note that [[UrlRule::mode|mode]] will be set to PARSING_ONLY when specifying verb in this way
* so you normally would not specify a verb for normal GET request.
*
* Here is an example configuration for RESTful CRUD controller:
*
* ~~~php
* array(
* 'dashboard' => 'site/index',
*
* 'POST <controller:\w+>s' => '<controller>/create',
* '<controller:\w+>s' => '<controller>/index',
*
* 'PUT <controller:\w+>/<id:\d+>' => '<controller>/update',
* 'DELETE <controller:\w+>/<id:\d+>' => '<controller>/delete',
* '<controller:\w+>/<id:\d+>' => '<controller>/view',
* );
* ~~~
*
* Note that if you modify this property after the UrlManager object is created, make sure * Note that if you modify this property after the UrlManager object is created, make sure
* you populate the array with rule objects instead of rule configurations. * you populate the array with rule objects instead of rule configurations.
*/ */
...@@ -115,9 +140,14 @@ class UrlManager extends Component ...@@ -115,9 +140,14 @@ class UrlManager extends Component
foreach ($this->rules as $key => $rule) { foreach ($this->rules as $key => $rule) {
if (!is_array($rule)) { if (!is_array($rule)) {
$rule = array( $rule = array(
'pattern' => $key,
'route' => $rule, 'route' => $rule,
); );
if (preg_match('/^((?:(GET|HEAD|POST|PUT|DELETE),)*(GET|HEAD|POST|PUT|DELETE))\s+(.*)$/', $key, $matches)) {
$rule['verb'] = explode(',', $matches[1]);
$rule['mode'] = UrlRule::PARSING_ONLY;
$key = $matches[4];
}
$rule['pattern'] = $key;
} }
$rules[] = Yii::createObject(array_merge($this->ruleConfig, $rule)); $rules[] = Yii::createObject(array_merge($this->ruleConfig, $rule));
} }
...@@ -166,7 +196,7 @@ class UrlManager extends Component ...@@ -166,7 +196,7 @@ class UrlManager extends Component
return array($pathInfo, array()); return array($pathInfo, array());
} else { } else {
$route = $request->getParam($this->routeVar); $route = $request->get($this->routeVar);
if (is_array($route)) { if (is_array($route)) {
$route = ''; $route = '';
} }
......
...@@ -171,7 +171,7 @@ class UrlRule extends Object ...@@ -171,7 +171,7 @@ class UrlRule extends Object
return false; return false;
} }
if ($this->verb !== null && !in_array($request->getRequestMethod(), $this->verb, true)) { if ($this->verb !== null && !in_array($request->getMethod(), $this->verb, true)) {
return false; return false;
} }
......
...@@ -56,7 +56,7 @@ class User extends Component ...@@ -56,7 +56,7 @@ class User extends Component
* @var array the configuration of the identity cookie. This property is used only when [[enableAutoLogin]] is true. * @var array the configuration of the identity cookie. This property is used only when [[enableAutoLogin]] is true.
* @see Cookie * @see Cookie
*/ */
public $identityCookie = array('name' => '_identity', 'httponly' => true); public $identityCookie = array('name' => '_identity', 'httpOnly' => true);
/** /**
* @var integer the number of seconds in which the user will be logged out automatically if he * @var integer the number of seconds in which the user will be logged out automatically if he
* remains inactive. If this property is not set, the user will be logged out after * remains inactive. If this property is not set, the user will be logged out after
...@@ -280,7 +280,7 @@ class User extends Component ...@@ -280,7 +280,7 @@ class User extends Component
public function loginRequired() public function loginRequired()
{ {
$request = Yii::$app->getRequest(); $request = Yii::$app->getRequest();
if (!$request->getIsAjaxRequest()) { if (!$request->getIsAjax()) {
$this->setReturnUrl($request->getUrl()); $this->setReturnUrl($request->getUrl());
} }
if ($this->loginUrl !== null) { if ($this->loginUrl !== null) {
......
...@@ -76,12 +76,12 @@ class VerbFilter extends Behavior ...@@ -76,12 +76,12 @@ class VerbFilter extends Behavior
{ {
$action = $event->action->id; $action = $event->action->id;
if (isset($this->actions[$action])) { if (isset($this->actions[$action])) {
$verb = Yii::$app->getRequest()->getRequestMethod(); $verb = Yii::$app->getRequest()->getMethod();
$allowed = array_map('strtoupper', $this->actions[$action]); $allowed = array_map('strtoupper', $this->actions[$action]);
if (!in_array($verb, $allowed)) { if (!in_array($verb, $allowed)) {
$event->isValid = false; $event->isValid = false;
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.7 // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.7
header('Allow: ' . implode(', ', $allowed)); Yii::$app->getResponse()->getHeaders()->set('Allow', implode(', ', $allowed));
throw new HttpException(405, 'Method Not Allowed. This url can only handle the following request methods: ' . implode(', ', $allowed)); throw new HttpException(405, 'Method Not Allowed. This url can only handle the following request methods: ' . implode(', ', $allowed));
} }
} }
......
...@@ -11,7 +11,7 @@ use Yii; ...@@ -11,7 +11,7 @@ use Yii;
use yii\base\InvalidConfigException; use yii\base\InvalidConfigException;
use yii\helpers\Html; use yii\helpers\Html;
use yii\base\Widget; use yii\base\Widget;
use yii\web\Pagination; use yii\data\Pagination;
/** /**
* LinkPager displays a list of hyperlinks that lead to different pages of target. * LinkPager displays a list of hyperlinks that lead to different pages of target.
......
...@@ -10,7 +10,7 @@ namespace yii\widgets; ...@@ -10,7 +10,7 @@ namespace yii\widgets;
use yii\base\InvalidConfigException; use yii\base\InvalidConfigException;
use yii\helpers\Html; use yii\helpers\Html;
use yii\base\Widget; use yii\base\Widget;
use yii\web\Pagination; use yii\data\Pagination;
/** /**
* ListPager displays a drop-down list that contains options leading to different pages. * ListPager displays a drop-down list that contains options leading to different pages.
...@@ -91,5 +91,4 @@ class ListPager extends Widget ...@@ -91,5 +91,4 @@ class ListPager extends Widget
'{page}' => $page + 1, '{page}' => $page + 1,
)); ));
} }
} }
...@@ -38,14 +38,13 @@ abstract class TestCase extends \yii\test\TestCase ...@@ -38,14 +38,13 @@ abstract class TestCase extends \yii\test\TestCase
* The application will be destroyed on tearDown() automatically. * The application will be destroyed on tearDown() automatically.
* @param array $config The application configuration, if needed * @param array $config The application configuration, if needed
*/ */
protected function mockApplication($config=array()) protected function mockApplication($config = array(), $appClass = '\yii\console\Application')
{ {
static $defaultConfig = array( static $defaultConfig = array(
'id' => 'testapp', 'id' => 'testapp',
'basePath' => __DIR__, 'basePath' => __DIR__,
); );
$appClass = $this->getParam( 'appClass', '\yii\web\Application' );
new $appClass(array_merge($defaultConfig,$config)); new $appClass(array_merge($defaultConfig,$config));
} }
......
<?php <?php
return array( return array(
//'appClass' => '\yii\web\Application',
'appClass' => '\yii\console\Application',
'databases' => array( 'databases' => array(
'mysql' => array( 'mysql' => array(
'dsn' => 'mysql:host=127.0.0.1;dbname=yiitest', 'dsn' => 'mysql:host=127.0.0.1;dbname=yiitest',
...@@ -20,5 +18,11 @@ return array( ...@@ -20,5 +18,11 @@ return array(
'password' => '', 'password' => '',
'fixture' => __DIR__ . '/mssql.sql', 'fixture' => __DIR__ . '/mssql.sql',
), ),
'pgsql' => array(
'dsn' => 'pgsql:host=localhost;dbname=yiitest;port=5432;',
'username' => 'postgres',
'password' => 'postgres',
'fixture' => __DIR__ . '/postgres.sql',
)
) )
); );
/** /**
* This is the database schema for testing PostgreSQL support of yii Active Record. * This is the database schema for testing PostgreSQL support of yii Active Record.
* To test this feature, you need to create a database named 'yii' on 'localhost' * To test this feature, you need to create a database named 'yiitest' on 'localhost'
* and create an account 'test/test' which owns this test database. * and create an account 'postgres/postgres' which owns this test database.
*/ */
CREATE SCHEMA test;
CREATE TABLE test.users DROP TABLE IF EXISTS tbl_order_item CASCADE;
( DROP TABLE IF EXISTS tbl_item CASCADE;
id SERIAL NOT NULL PRIMARY KEY, DROP TABLE IF EXISTS tbl_order CASCADE;
username VARCHAR(128) NOT NULL, DROP TABLE IF EXISTS tbl_category CASCADE;
password VARCHAR(128) NOT NULL, DROP TABLE IF EXISTS tbl_customer CASCADE;
email VARCHAR(128) NOT NULL DROP TABLE IF EXISTS tbl_type CASCADE;
CREATE TABLE tbl_customer (
id serial not null primary key,
email varchar(128) NOT NULL,
name varchar(128) NOT NULL,
address text,
status integer DEFAULT 0
); );
INSERT INTO test.users (username, password, email) VALUES ('user1','pass1','email1'); comment on column public.tbl_customer.email is 'someone@example.com';
INSERT INTO test.users (username, password, email) VALUES ('user2','pass2','email2');
INSERT INTO test.users (username, password, email) VALUES ('user3','pass3','email3');
CREATE TABLE test.user_friends CREATE TABLE tbl_category (
( id serial not null primary key,
id INTEGER NOT NULL, name varchar(128) NOT NULL
friend INTEGER NOT NULL,
PRIMARY KEY (id, friend),
CONSTRAINT FK_user_id FOREIGN KEY (id)
REFERENCES test.users (id) ON DELETE CASCADE ON UPDATE RESTRICT,
CONSTRAINT FK_friend_id FOREIGN KEY (friend)
REFERENCES test.users (id) ON DELETE CASCADE ON UPDATE RESTRICT
); );
INSERT INTO test.user_friends VALUES (1,2); CREATE TABLE tbl_item (
INSERT INTO test.user_friends VALUES (1,3); id serial not null primary key,
INSERT INTO test.user_friends VALUES (2,3); name varchar(128) NOT NULL,
category_id integer NOT NULL references tbl_category(id) on UPDATE CASCADE on DELETE CASCADE
CREATE TABLE test.profiles
(
id SERIAL NOT NULL PRIMARY KEY,
first_name VARCHAR(128) NOT NULL,
last_name VARCHAR(128) NOT NULL,
user_id INTEGER NOT NULL,
CONSTRAINT FK_profile_user FOREIGN KEY (user_id)
REFERENCES test.users (id) ON DELETE CASCADE ON UPDATE RESTRICT
);
INSERT INTO test.profiles (first_name, last_name, user_id) VALUES ('first 1','last 1',1);
INSERT INTO test.profiles (first_name, last_name, user_id) VALUES ('first 2','last 2',2);
CREATE TABLE test.posts
(
id SERIAL NOT NULL PRIMARY KEY,
title VARCHAR(128) NOT NULL,
create_time TIMESTAMP NOT NULL,
author_id INTEGER NOT NULL,
content TEXT,
CONSTRAINT FK_post_author FOREIGN KEY (author_id)
REFERENCES test.users (id) ON DELETE CASCADE ON UPDATE RESTRICT
); );
INSERT INTO test.posts (title, create_time, author_id, content) VALUES ('post 1',TIMESTAMP '2004-10-19 10:23:54',1,'content 1'); CREATE TABLE tbl_order (
INSERT INTO test.posts (title, create_time, author_id, content) VALUES ('post 2',TIMESTAMP '2004-10-19 10:23:54',2,'content 2'); id serial not null primary key,
INSERT INTO test.posts (title, create_time, author_id, content) VALUES ('post 3',TIMESTAMP '2004-10-19 10:23:54',2,'content 3'); customer_id integer NOT NULL references tbl_customer(id) on UPDATE CASCADE on DELETE CASCADE,
INSERT INTO test.posts (title, create_time, author_id, content) VALUES ('post 4',TIMESTAMP '2004-10-19 10:23:54',2,'content 4'); create_time integer NOT NULL,
INSERT INTO test.posts (title, create_time, author_id, content) VALUES ('post 5',TIMESTAMP '2004-10-19 10:23:54',3,'content 5'); total decimal(10,0) NOT NULL
CREATE TABLE test.comments
(
id SERIAL NOT NULL PRIMARY KEY,
content TEXT NOT NULL,
post_id INTEGER NOT NULL,
author_id INTEGER NOT NULL,
CONSTRAINT FK_post_comment FOREIGN KEY (post_id)
REFERENCES test.posts (id) ON DELETE CASCADE ON UPDATE RESTRICT,
CONSTRAINT FK_user_comment FOREIGN KEY (author_id)
REFERENCES test.users (id) ON DELETE CASCADE ON UPDATE RESTRICT
); );
INSERT INTO test.comments (content, post_id, author_id) VALUES ('comment 1',1, 2); CREATE TABLE tbl_order_item (
INSERT INTO test.comments (content, post_id, author_id) VALUES ('comment 2',1, 2); order_id integer NOT NULL references tbl_order(id) on UPDATE CASCADE on DELETE CASCADE,
INSERT INTO test.comments (content, post_id, author_id) VALUES ('comment 3',1, 2); item_id integer NOT NULL references tbl_item(id) on UPDATE CASCADE on DELETE CASCADE,
INSERT INTO test.comments (content, post_id, author_id) VALUES ('comment 4',2, 2); quantity integer NOT NULL,
INSERT INTO test.comments (content, post_id, author_id) VALUES ('comment 5',2, 2); subtotal decimal(10,0) NOT NULL,
INSERT INTO test.comments (content, post_id, author_id) VALUES ('comment 6',3, 2); PRIMARY KEY (order_id,item_id)
INSERT INTO test.comments (content, post_id, author_id) VALUES ('comment 7',3, 2);
INSERT INTO test.comments (content, post_id, author_id) VALUES ('comment 8',3, 2);
INSERT INTO test.comments (content, post_id, author_id) VALUES ('comment 9',3, 2);
INSERT INTO test.comments (content, post_id, author_id) VALUES ('comment 10',5, 3);
CREATE TABLE test.categories
(
id SERIAL NOT NULL PRIMARY KEY,
name VARCHAR(128) NOT NULL,
parent_id INTEGER,
CONSTRAINT FK_category_category FOREIGN KEY (parent_id)
REFERENCES test.categories (id) ON DELETE CASCADE ON UPDATE RESTRICT
); );
INSERT INTO test.categories (name, parent_id) VALUES ('cat 1',NULL); CREATE TABLE tbl_type (
INSERT INTO test.categories (name, parent_id) VALUES ('cat 2',NULL); int_col integer NOT NULL,
INSERT INTO test.categories (name, parent_id) VALUES ('cat 3',NULL); int_col2 integer DEFAULT '1',
INSERT INTO test.categories (name, parent_id) VALUES ('cat 4',1); char_col char(100) NOT NULL,
INSERT INTO test.categories (name, parent_id) VALUES ('cat 5',1); char_col2 varchar(100) DEFAULT 'something',
INSERT INTO test.categories (name, parent_id) VALUES ('cat 6',5); char_col3 text,
INSERT INTO test.categories (name, parent_id) VALUES ('cat 7',5); float_col double precision NOT NULL,
float_col2 double precision DEFAULT '1.23',
CREATE TABLE test.post_category blob_col bytea,
( numeric_col decimal(5,2) DEFAULT '33.22',
category_id INTEGER NOT NULL, time timestamp NOT NULL DEFAULT '2002-01-01 00:00:00',
post_id INTEGER NOT NULL, bool_col smallint NOT NULL,
PRIMARY KEY (category_id, post_id), bool_col2 smallint DEFAULT '1'
CONSTRAINT FK_post_category_post FOREIGN KEY (post_id)
REFERENCES test.posts (id) ON DELETE CASCADE ON UPDATE RESTRICT,
CONSTRAINT FK_post_category_category FOREIGN KEY (category_id)
REFERENCES test.categories (id) ON DELETE CASCADE ON UPDATE RESTRICT
); );
INSERT INTO test.post_category (category_id, post_id) VALUES (1,1); INSERT INTO tbl_customer (email, name, address, status) VALUES ('user1@example.com', 'user1', 'address1', 1);
INSERT INTO test.post_category (category_id, post_id) VALUES (2,1); INSERT INTO tbl_customer (email, name, address, status) VALUES ('user2@example.com', 'user2', 'address2', 1);
INSERT INTO test.post_category (category_id, post_id) VALUES (3,1); INSERT INTO tbl_customer (email, name, address, status) VALUES ('user3@example.com', 'user3', 'address3', 2);
INSERT INTO test.post_category (category_id, post_id) VALUES (4,2);
INSERT INTO test.post_category (category_id, post_id) VALUES (1,2); INSERT INTO tbl_category (name) VALUES ('Books');
INSERT INTO test.post_category (category_id, post_id) VALUES (1,3); INSERT INTO tbl_category (name) VALUES ('Movies');
CREATE TABLE test.orders 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);
key1 INTEGER NOT NULL, INSERT INTO tbl_item (name, category_id) VALUES ('Ice Age', 2);
key2 INTEGER NOT NULL, INSERT INTO tbl_item (name, category_id) VALUES ('Toy Story', 2);
name VARCHAR(128), INSERT INTO tbl_item (name, category_id) VALUES ('Cars', 2);
PRIMARY KEY (key1, key2)
); 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 test.orders (key1,key2,name) VALUES (1,2,'order 12'); INSERT INTO tbl_order (customer_id, create_time, total) VALUES (2, 1325502201, 40.0);
INSERT INTO test.orders (key1,key2,name) VALUES (1,3,'order 13');
INSERT INTO test.orders (key1,key2,name) VALUES (2,1,'order 21'); INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (1, 1, 1, 30.0);
INSERT INTO test.orders (key1,key2,name) VALUES (2,2,'order 22'); 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);
CREATE TABLE test.items 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);
id SERIAL NOT NULL PRIMARY KEY, INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (3, 2, 1, 40.0);
name VARCHAR(128),
col1 INTEGER NOT NULL,
col2 INTEGER NOT NULL,
CONSTRAINT FK_order_item FOREIGN KEY (col1,col2)
REFERENCES test.orders (key1,key2) ON DELETE CASCADE ON UPDATE RESTRICT
);
INSERT INTO test.items (name,col1,col2) VALUES ('item 1',1,2);
INSERT INTO test.items (name,col1,col2) VALUES ('item 2',1,2);
INSERT INTO test.items (name,col1,col2) VALUES ('item 3',1,3);
INSERT INTO test.items (name,col1,col2) VALUES ('item 4',2,2);
INSERT INTO test.items (name,col1,col2) VALUES ('item 5',2,2);
CREATE TABLE public.yii_types
(
int_col INT NOT NULL,
int_col2 INTEGER DEFAULT 1,
char_col CHAR(100) NOT NULL,
char_col2 VARCHAR(100) DEFAULT 'something',
char_col3 TEXT,
numeric_col NUMERIC(4,3) NOT NULL,
real_col REAL DEFAULT 1.23,
blob_col BYTEA,
time TIMESTAMP,
bool_col BOOL NOT NULL,
bool_col2 BOOLEAN DEFAULT TRUE
);
\ No newline at end of file
...@@ -239,6 +239,7 @@ class AssetControllerTest extends TestCase ...@@ -239,6 +239,7 @@ class AssetControllerTest extends TestCase
// Then : // Then :
$this->assertTrue(file_exists($bundleFile), 'Unable to create output bundle file!'); $this->assertTrue(file_exists($bundleFile), 'Unable to create output bundle file!');
$this->assertTrue(is_array(require($bundleFile)), 'Output bundle file has incorrect format!');
$compressedCssFileName = $this->testAssetsBasePath . DIRECTORY_SEPARATOR . 'all.css'; $compressedCssFileName = $this->testAssetsBasePath . DIRECTORY_SEPARATOR . 'all.css';
$this->assertTrue(file_exists($compressedCssFileName), 'Unable to compress CSS files!'); $this->assertTrue(file_exists($compressedCssFileName), 'Unable to compress CSS files!');
......
...@@ -37,6 +37,9 @@ abstract class DatabaseTestCase extends TestCase ...@@ -37,6 +37,9 @@ abstract class DatabaseTestCase extends TestCase
$db->username = $this->database['username']; $db->username = $this->database['username'];
$db->password = $this->database['password']; $db->password = $this->database['password'];
} }
if (isset($this->database['attributes'])) {
$db->attributes = $this->database['attributes'];
}
if ($open) { if ($open) {
$db->open(); $db->open();
$lines = explode(';', file_get_contents($this->database['fixture'])); $lines = explode(';', file_get_contents($this->database['fixture']));
......
<?php
namespace yiiunit\framework\db;
use yii\db\QueryBuilder;
use yii\db\Schema;
use yii\db\mysql\QueryBuilder as MysqlQueryBuilder;
use yii\db\sqlite\QueryBuilder as SqliteQueryBuilder;
use yii\db\mssql\QueryBuilder as MssqlQueryBuilder;
class QueryBuilderTest extends DatabaseTestCase
{
/**
* @throws \Exception
* @return QueryBuilder
*/
protected function getQueryBuilder()
{
switch($this->driverName)
{
case 'mysql':
return new MysqlQueryBuilder($this->getConnection());
case 'sqlite':
return new SqliteQueryBuilder($this->getConnection());
case 'mssql':
return new MssqlQueryBuilder($this->getConnection());
}
throw new \Exception('Test is not implemented for ' . $this->driverName);
}
/**
* this is not used as a dataprovider for testGetColumnType to speed up the test
* when used as dataprovider every single line will cause a reconnect with the database which is not needed here
*/
public function columnTypes()
{
return array(
array(Schema::TYPE_PK, 'int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY'),
array(Schema::TYPE_PK . '(8)', 'int(8) NOT NULL AUTO_INCREMENT PRIMARY KEY'),
array(Schema::TYPE_PK . ' CHECK (value > 5)', 'int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY CHECK (value > 5)'),
array(Schema::TYPE_PK . '(8) CHECK (value > 5)', 'int(8) 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, 'text'),
array(Schema::TYPE_TEXT . '(255)', 'text'),
array(Schema::TYPE_TEXT . ' CHECK (value LIKE "test%")', 'text CHECK (value LIKE "test%")'),
array(Schema::TYPE_TEXT . '(255) CHECK (value LIKE "test%")', 'text CHECK (value LIKE "test%")'),
array(Schema::TYPE_TEXT . ' NOT NULL', 'text NOT NULL'),
array(Schema::TYPE_TEXT . '(255) NOT NULL', 'text NOT NULL'),
array(Schema::TYPE_SMALLINT, 'smallint(6)'),
array(Schema::TYPE_SMALLINT . '(8)', 'smallint(8)'),
array(Schema::TYPE_INTEGER, 'int(11)'),
array(Schema::TYPE_INTEGER . '(8)', 'int(8)'),
array(Schema::TYPE_INTEGER . ' CHECK (value > 5)', 'int(11) CHECK (value > 5)'),
array(Schema::TYPE_INTEGER . '(8) CHECK (value > 5)', 'int(8) CHECK (value > 5)'),
array(Schema::TYPE_INTEGER . ' NOT NULL', 'int(11) NOT NULL'),
array(Schema::TYPE_BIGINT, 'bigint(20)'),
array(Schema::TYPE_BIGINT . '(8)', 'bigint(8)'),
array(Schema::TYPE_BIGINT . ' CHECK (value > 5)', 'bigint(20) CHECK (value > 5)'),
array(Schema::TYPE_BIGINT . '(8) CHECK (value > 5)', 'bigint(8) CHECK (value > 5)'),
array(Schema::TYPE_BIGINT . ' NOT NULL', 'bigint(20) NOT NULL'),
array(Schema::TYPE_FLOAT, 'float'),
array(Schema::TYPE_FLOAT . '(16,5)', 'float'),
array(Schema::TYPE_FLOAT . ' CHECK (value > 5.6)', 'float CHECK (value > 5.6)'),
array(Schema::TYPE_FLOAT . '(16,5) CHECK (value > 5.6)', 'float CHECK (value > 5.6)'),
array(Schema::TYPE_FLOAT . ' NOT NULL', 'float 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, 'tinyint(1)'),
array(Schema::TYPE_BOOLEAN . ' NOT NULL DEFAULT 1', 'tinyint(1) 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'),
);
}
/**
*
*/
public function testGetColumnType()
{
$qb = $this->getQueryBuilder();
foreach($this->columnTypes() as $item) {
list ($column, $expected) = $item;
$this->assertEquals($expected, $qb->getColumnType($column));
}
}
}
<?php
namespace yiiunit\framework\db\pgsql;
use yiiunit\framework\db\ActiveRecordTest;
class PostgreSQLActiveRecordTest extends ActiveRecordTest
{
protected function setUp()
{
$this->driverName = 'pgsql';
parent::setUp();
}
}
<?php
namespace yiiunit\framework\db\pgsql;
use yiiunit\framework\db\ConnectionTest;
class PostgreSQLConnectionTest extends ConnectionTest {
public function setUp() {
$this->driverName = 'pgsql';
parent::setUp();
}
public function testConnection() {
$connection = $this->getConnection(true);
}
function testQuoteValue() {
$connection = $this->getConnection(false);
$this->assertEquals(123, $connection->quoteValue(123));
$this->assertEquals("'string'", $connection->quoteValue('string'));
$this->assertEquals("'It''s interesting'", $connection->quoteValue("It's interesting"));
}
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('"schema"."table"', $connection->quoteTableName('"schema"."table"'));
$this->assertEquals('{{table}}', $connection->quoteTableName('{{table}}'));
$this->assertEquals('(table)', $connection->quoteTableName('(table)'));
}
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('"table"."column"', $connection->quoteColumnName('"table"."column"'));
$this->assertEquals('[[column]]', $connection->quoteColumnName('[[column]]'));
$this->assertEquals('{{column}}', $connection->quoteColumnName('{{column}}'));
$this->assertEquals('(column)', $connection->quoteColumnName('(column)'));
}
}
<?php
namespace yiiunit\framework\db\sqlite;
use yii\db\sqlite\Schema;
use yiiunit\framework\db\QueryBuilderTest;
class SqliteQueryBuilderTest extends QueryBuilderTest
{
public $driverName = 'sqlite';
public function columnTypes()
{
return array(
array(Schema::TYPE_PK, 'integer PRIMARY KEY AUTOINCREMENT NOT NULL'),
array(Schema::TYPE_PK . '(8)', 'integer PRIMARY KEY AUTOINCREMENT NOT NULL'),
array(Schema::TYPE_PK . ' CHECK (value > 5)', 'integer PRIMARY KEY AUTOINCREMENT NOT NULL CHECK (value > 5)'),
array(Schema::TYPE_PK . '(8) CHECK (value > 5)', 'integer PRIMARY KEY AUTOINCREMENT NOT NULL 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, 'text'),
array(Schema::TYPE_TEXT . '(255)', 'text'),
array(Schema::TYPE_TEXT . ' CHECK (value LIKE "test%")', 'text CHECK (value LIKE "test%")'),
array(Schema::TYPE_TEXT . '(255) CHECK (value LIKE "test%")', 'text CHECK (value LIKE "test%")'),
array(Schema::TYPE_TEXT . ' NOT NULL', 'text NOT NULL'),
array(Schema::TYPE_TEXT . '(255) NOT NULL', 'text NOT NULL'),
array(Schema::TYPE_SMALLINT, 'smallint'),
array(Schema::TYPE_SMALLINT . '(8)', 'smallint'),
array(Schema::TYPE_INTEGER, 'integer'),
array(Schema::TYPE_INTEGER . '(8)', 'integer'),
array(Schema::TYPE_INTEGER . ' CHECK (value > 5)', 'integer CHECK (value > 5)'),
array(Schema::TYPE_INTEGER . '(8) CHECK (value > 5)', 'integer CHECK (value > 5)'),
array(Schema::TYPE_INTEGER . ' NOT NULL', 'integer 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'),
array(Schema::TYPE_FLOAT . '(16,5)', 'float'),
array(Schema::TYPE_FLOAT . ' CHECK (value > 5.6)', 'float CHECK (value > 5.6)'),
array(Schema::TYPE_FLOAT . '(16,5) CHECK (value > 5.6)', 'float CHECK (value > 5.6)'),
array(Schema::TYPE_FLOAT . ' NOT NULL', 'float 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, 'boolean'),
array(Schema::TYPE_BOOLEAN . ' NOT NULL DEFAULT 1', 'boolean 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'),
);
}
}
\ No newline at end of file
...@@ -4,7 +4,7 @@ namespace yiiunit\framework\helpers; ...@@ -4,7 +4,7 @@ namespace yiiunit\framework\helpers;
use yii\helpers\ArrayHelper; use yii\helpers\ArrayHelper;
use yii\test\TestCase; use yii\test\TestCase;
use yii\web\Sort; use yii\data\Sort;
class ArrayHelperTest extends TestCase class ArrayHelperTest extends TestCase
{ {
......
<?php <?php
namespace yii\web;
use yiiunit\framework\web\ResponseTest;
/**
* Mock PHP header function to check for sent headers
* @param string $string
* @param bool $replace
* @param int $httpResponseCode
*/
function header($string, $replace = true, $httpResponseCode = null) {
ResponseTest::$headers[] = $string;
// TODO implement replace
if ($httpResponseCode !== null) {
ResponseTest::$httpResponseCode = $httpResponseCode;
}
}
namespace yiiunit\framework\web; namespace yiiunit\framework\web;
use Yii;
use yii\helpers\StringHelper; use yii\helpers\StringHelper;
use yii\web\Response; use yii\web\Response;
class ResponseTest extends \yiiunit\TestCase class ResponseTest extends \yiiunit\TestCase
{ {
public static $headers = array(); public $response;
public static $httpResponseCode = 200;
protected function setUp() protected function setUp()
{ {
parent::setUp(); parent::setUp();
$this->reset(); $this->mockApplication();
} $this->response = new Response;
protected function reset()
{
static::$headers = array();
static::$httpResponseCode = 200;
} }
public function rightRanges() public function rightRanges()
...@@ -59,14 +35,15 @@ class ResponseTest extends \yiiunit\TestCase ...@@ -59,14 +35,15 @@ class ResponseTest extends \yiiunit\TestCase
{ {
$content = $this->generateTestFileContent(); $content = $this->generateTestFileContent();
$_SERVER['HTTP_RANGE'] = 'bytes=' . $rangeHeader; $_SERVER['HTTP_RANGE'] = 'bytes=' . $rangeHeader;
$sent = $this->runSendFile('testFile.txt', $content, null); $this->response->sendFile('testFile.txt', $content, null, false);
$this->assertEquals($expectedFile, $sent); $this->assertEquals($expectedFile, $this->response->content);
$this->assertTrue(in_array('HTTP/1.1 206 Partial Content', static::$headers)); $this->assertEquals(206, $this->response->statusCode);
$this->assertTrue(in_array('Accept-Ranges: bytes', static::$headers)); $headers = $this->response->headers;
$this->assertArrayHasKey('Content-Range: bytes ' . $expectedHeader . '/' . StringHelper::strlen($content), array_flip(static::$headers)); $this->assertEquals("bytes", $headers->get('Accept-Ranges'));
$this->assertTrue(in_array('Content-Type: text/plain', static::$headers)); $this->assertEquals("bytes " . $expectedHeader . '/' . StringHelper::strlen($content), $headers->get('Content-Range'));
$this->assertTrue(in_array('Content-Length: ' . $length, static::$headers)); $this->assertEquals('text/plain', $headers->get('Content-Type'));
$this->assertEquals("$length", $headers->get('Content-Length'));
} }
public function wrongRanges() public function wrongRanges()
...@@ -90,21 +67,11 @@ class ResponseTest extends \yiiunit\TestCase ...@@ -90,21 +67,11 @@ class ResponseTest extends \yiiunit\TestCase
$content = $this->generateTestFileContent(); $content = $this->generateTestFileContent();
$_SERVER['HTTP_RANGE'] = 'bytes=' . $rangeHeader; $_SERVER['HTTP_RANGE'] = 'bytes=' . $rangeHeader;
$this->runSendFile('testFile.txt', $content, null); $this->response->sendFile('testFile.txt', $content, null, false);
} }
protected function generateTestFileContent() protected function generateTestFileContent()
{ {
return '12ёжик3456798áèabcdefghijklmnopqrstuvwxyz!"§$%&/(ёжик)=?'; return '12ёжик3456798áèabcdefghijklmnopqrstuvwxyz!"§$%&/(ёжик)=?';
} }
protected function runSendFile($fileName, $content, $mimeType)
{
ob_start();
ob_implicit_flush(false);
$response = new Response();
$response->sendFile($fileName, $content, $mimeType, false);
$file = ob_get_clean();
return $file;
}
} }
...@@ -248,4 +248,58 @@ class UrlManagerTest extends TestCase ...@@ -248,4 +248,58 @@ class UrlManagerTest extends TestCase
$result = $manager->parseRequest($request); $result = $manager->parseRequest($request);
$this->assertFalse($result); $this->assertFalse($result);
} }
public function testParseRESTRequest()
{
$manager = new UrlManager(array(
'cache' => null,
));
$request = new Request;
// pretty URL rules
$manager = new UrlManager(array(
'enablePrettyUrl' => true,
'cache' => null,
'rules' => array(
'PUT,POST post/<id>/<title>' => 'post/create',
'DELETE post/<id>' => 'post/delete',
'post/<id>/<title>' => 'post/view',
'POST/GET' => 'post/get',
),
));
// matching pathinfo GET request
$_SERVER['REQUEST_METHOD'] = 'GET';
$request->pathInfo = 'post/123/this+is+sample';
$result = $manager->parseRequest($request);
$this->assertEquals(array('post/view', array('id' => '123', 'title' => 'this+is+sample')), $result);
// matching pathinfo PUT/POST request
$_SERVER['REQUEST_METHOD'] = 'PUT';
$request->pathInfo = 'post/123/this+is+sample';
$result = $manager->parseRequest($request);
$this->assertEquals(array('post/create', array('id' => '123', 'title' => 'this+is+sample')), $result);
$_SERVER['REQUEST_METHOD'] = 'POST';
$request->pathInfo = 'post/123/this+is+sample';
$result = $manager->parseRequest($request);
$this->assertEquals(array('post/create', array('id' => '123', 'title' => 'this+is+sample')), $result);
// no wrong matching
$_SERVER['REQUEST_METHOD'] = 'POST';
$request->pathInfo = 'POST/GET';
$result = $manager->parseRequest($request);
$this->assertEquals(array('post/get', array()), $result);
// createUrl should ignore REST rules
$this->mockApplication(array(
'components' => array(
'request' => array(
'hostInfo' => 'http://localhost/',
'baseUrl' => '/app'
)
)
), \yii\web\Application::className());
$this->assertEquals('/app/post/delete?id=123', $manager->createUrl('post/delete', array('id' => 123)));
$this->destroyApplication();
unset($_SERVER['REQUEST_METHOD']);
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment