Commit dc7aa25a by Carsten Brandt

Merge branch 'master' of github.com:yiisoft/yii2

* 'master' of github.com:yiisoft/yii2: (23 commits) datepicker should show empty field when value is empty string complete docs about Nav to include the style Update tutorial-mailing.md Reverted #3665 (reverted from commit 2aa39499) Unit test for `yii\console\controllers\AssetController` advanced Doc comments for `yii\console\controllers\AssetController` extended `yii\console\controllers\AssetController` now handles bundle files from external resources properly skip requirements checker test on HHVM Update README.md in guide-es [skip ci] Add helper-array.md in guide-es [skip ci] a note about database naming style Add syntax highlighting [skip ci] docs/guide-ja/tutorial-core-validators.md - completed [ci skip] docs/guide-ja/tutorial-core-validators.md - WIP [ci skip] docs/guide-ja/tutorial-core-validators.md - WIP [ci skip] Fixed `\yii\authclient\OAuth2::refreshAccessToken()` does not save fetched token `\yii\authclient\AuthAction::defaultCancelUrl()` changed to use `yii\web\User::loginUrl` MongoDB PHP extension min version raised up to 1.5.0 Были различные ссылки в русском гайде - привел все к английскому виду ссылки. Файлы по этим ссылкам еще не существуют поэтому переименовывать их и не нужно. Fixed typo. ...
parents fea4c8da 548e19ef
......@@ -168,7 +168,7 @@ Temas especiales
* **TBD** [Plantilla aplicación avanzada](tutorial-advanced-app.md)
* **TBD** [Creación de una aplicación desde cero](tutorial-start-from-scratch.md)
* **TBD** [Comandos de consola](tutorial-console.md)
* **TBD** [Validadores de base](tutorial-core-validators.md)
* [Validadores del núcleo](tutorial-core-validators.md)
* **TBD** [Internacionalización](tutorial-i18n.md)
* **TBD** [Envío de correos electrónicos](tutorial-mailing.md)
* **TBD** [Mejora del rendimiento](tutorial-performance-tuning.md)
......@@ -180,14 +180,14 @@ Temas especiales
Widgets
-------
* GridView: link to demo page
* ListView: link to demo page
* DetailView: link to demo page
* ActiveForm: link to demo page
* Pjax: link to demo page
* Menu: link to demo page
* LinkPager: link to demo page
* LinkSorter: link to demo page
* GridView: **TBD** link to demo page
* ListView: **TBD** link to demo page
* DetailView: **TBD** link to demo page
* ActiveForm: **TBD** link to demo page
* Pjax: **TBD** link to demo page
* Menu: **TBD** link to demo page
* LinkPager: **TBD** link to demo page
* LinkSorter: **TBD** link to demo page
* **TBD** [Bootstrap Widgets](bootstrap-widgets.md)
* **TBD** [Jquery UI Widgets](jui-widgets.md)
......@@ -196,6 +196,6 @@ Clases auxiliares
-----------------
* [Información general](helper-overview.md)
* **TBD** [ArrayHelper](helper-array.md)
* [ArrayHelper](helper-array.md)
* [Html](helper-html.md)
* [Url](helper-url.md)
......@@ -164,7 +164,7 @@ RESTful ウェブサービス
* [アドバンストアプリケーションテンプレート](tutorial-advanced-app.md)
* [アプリケーションを一から構築する](tutorial-start-from-scratch.md)
* [コンソールコマンド](tutorial-console.md)
* **翻訳中** [コアのバリデータ](tutorial-core-validators.md)
* [コアバリデータ](tutorial-core-validators.md)
* **翻訳中** [国際化](tutorial-i18n.md)
* **翻訳中** [メール](tutorial-mailing.md)
* **翻訳中** [パフォーマンスチューニング](tutorial-performance-tuning.md)
......
......@@ -81,7 +81,7 @@ All Rights Reserved.
* **TBD** [Sphinx](db-sphinx.md)
* **TBD** [Redis](db-redis.md)
* **TBD** [MongoDB](db-mongodb.md)
* **TBD** [ElasticSearch](db-elastic-search.md)
* **TBD** [ElasticSearch](db-elasticsearch.md)
Получение данных от пользователя
......@@ -89,14 +89,14 @@ All Rights Reserved.
* [Создание форм](input-forms.md)
* [Валидация](input-validation.md)
* **TBD** [Загрузка файлов](input-file-uploading.md)
* **TBD** [Загрузка файлов](input-file-upload.md)
* **TBD** [Работа с несколькими моделями](input-multiple-models.md)
Отображение данных
------------------
* **TBD** [Форматирование данных](output-formatting.md)
* **TBD** [Форматирование данных](output-formatter.md)
* **TBD** [Постраничная разбивка](output-pagination.md)
* **TBD** [Сортировка](output-sorting.md)
* [Провайдеры данных](output-data-providers.md)
......@@ -191,8 +191,8 @@ All Rights Reserved.
* Menu: link to demo page
* LinkPager: link to demo page
* LinkSorter: link to demo page
* [Виджеты Bootstrap](bootstrap-widgets.md)
* **TBD** [Виджеты Jquery UI](jui-widgets.md)
* [Виджеты Bootstrap](widget-bootstrap.md)
* **TBD** [Виджеты Jquery UI](widget-jui.md)
Хелперы
......
......@@ -69,7 +69,7 @@
Более детальная информация представлена в разделе [Обработка ошибок](runtime-handling-errors.md);
* [[yii\base\Formatter|formatter]]: форматирует данные для отображения их конечному пользователю. Например, число может
быть отображено с различными разделителями, дата может быть отображена в формате `long`.
Более детальная информация представлена в разделе [Форматирование данных](output-formatting.md);
Более детальная информация представлена в разделе [Форматирование данных](output-formatter.md);
* [[yii\i18n\I18N|i18n]]: используется для перевода сообщений и форматирования.
Более детальная информация представлена в разделе [Интернационализация](tutorial-i18n.md);
* [[yii\log\Dispatcher|log]]: обработка и маршрутизация логов.
......
......@@ -96,6 +96,12 @@ $customer->email = 'jane@example.com';
$customer->save();
```
> Note: Obviously, because column names become attribute names of the active record class directly, you
> get attribute names with underscores if you have that kind of naming schema in your database. For example
> a column `user_name` will be accessed as `$user->user_name` on the active record object. If you are concerned about code style
> you should adopt your database naming schema to use camelCase too. However, camelCase if not a requirement, Yii can work
> well with any other naming style.
Connecting to Database
----------------------
......
......@@ -3,14 +3,14 @@ ArrayHelper
Additionally to [rich set of PHP array functions](http://php.net/manual/en/book.array.php) Yii array helper provides
extra static methods allowing you to deal with arrays more efficiently.
## Getting Values <a name="getting-values"></a>
Retrieving values from an array, an object or a complex structure consisting of both using standard PHP is quite
repetitive. You have to check if key exists with `isset` first, then if it does you're getting it, if not,
repetitive. You have to check if key exists with `isset` first, then if it does you're getting it, if not,
providing default value:
```php
class User
{
......@@ -34,9 +34,9 @@ $value = ArrayHelper::getValue($array, 'foo.bar.name');
First method argument is where we're getting value from. Second argument specifies how to get the data. It could be one
of the following:
- Name of array key or object property to retrieve value from.
- Set of dot separated array keys or object property names. The one we've used in the example above.
- Set of dot separated array keys or object property names. The one we've used in the example above.
- A callback returning a value.
The callback should be the following:
......@@ -54,7 +54,7 @@ $username = ArrayHelper::getValue($comment, 'user.username', 'Unknown');
```
In case you want to get the value and then immediately remove it from array you can use `remove` method:
```php
$array = ['type' => 'A', 'options' => [1, 2]];
$type = ArrayHelper::remove($array, 'type');
......@@ -96,7 +96,7 @@ $ids = ArrayHelper::getColumn($array, 'id');
```
The result will be `['123', '345']`.
If additional transformations are required or the way of getting value is complex, second argument could be specified
as an anonymous function:
......@@ -106,7 +106,7 @@ $result = ArrayHelper::getColumn($array, function ($element) {
});
```
## Re-indexing Arrays <a name="reindexing-arrays"></a>
In order to index an array according to a specified key, the `index` method can be used. The input array should be
......@@ -114,7 +114,7 @@ multidimensional or an array of objects. The key can be a key name of the sub-ar
an anonymous function which returns the key value given an array element.
If a key value is null, the corresponding array element will be discarded and not put in the result. For example,
```php
$array = [
['id' => '123', 'data' => 'abc'],
......@@ -133,13 +133,13 @@ $result = ArrayHelper::index($array, function ($element) {
});
```
## Building Maps <a name="building-maps"></a>
## Building Maps <a name="building-maps"></a>
In order to build a map (key-value pairs) from a multidimensional array or an array of objects you can use `map` method.
The `$from` and `$to` parameters specify the key names or property names to set up the map. Optionally, one can further
group the map according to a grouping field `$group`. For example,
```php
$array = [
['id' => '123', 'name' => 'aaa', 'class' => 'x'],
......@@ -167,9 +167,9 @@ $result = ArrayHelper::map($array, 'id', 'name', 'class');
// ],
// ]
```
## Multidimensional Sorting <a name="multidimensional-sorting"></a>
## Multidimensional Sorting <a name="multidimensional-sorting"></a>
`multisort` method helps to sort an array of objects or nested arrays by one or several keys. For example,
......@@ -200,19 +200,19 @@ ArrayHelper::multisort($data, function($item) {
return isset($item['age']) ? ['age', 'name'] : 'name';
});
```
Third argument is direction. In case of sorting by a single key it could be either `SORT_ASC` or
`SORT_DESC`. If sorting by multiple values you can sort each value differently by providing an array of
sort direction.
Last argument is PHP sort flag that could take the same values as the ones passed to
PHP [sort()](http://php.net/manual/en/function.sort.php).
## Detecting Array Types <a name="detecting-array-types"></a>
It is handy to know whether an array is indexed or an associative. Here's an example:
```php
// no keys specified
$indexed = ['Qiang', 'Paul'];
......@@ -222,7 +222,7 @@ echo ArrayHelper::isIndexed($indexed);
$associative = ['framework' => 'Yii', 'version' => '2.0'];
echo ArrayHelper::isAssociative($associative);
```
## HTML Encoding and Decoding Values <a name="html-encoding-values"></a>
......@@ -235,26 +235,28 @@ $decoded = ArrayHelper::htmlDecode($data);
Only values will be encoded by default. By passing second argument as `false` you can encode array's keys as well.
Encoding will use application charset and could be changed via third argument.
## Merging Arrays <a name="merging-arrays"></a>
```php
/**
* Merges two or more arrays into one recursively.
* If each array has an element with the same string key value, the latter
* will overwrite the former (different from array_merge_recursive).
* Recursive merging will be conducted if both arrays have an element of array
* type and are having the same key.
* For integer-keyed elements, the elements from the latter array will
* be appended to the former array.
* @param array $a array to be merged to
* @param array $b array to be merged from. You can specify additional
* arrays via third argument, fourth argument etc.
* @return array the merged array (the original arrays are not changed.)
*/
* Merges two or more arrays into one recursively.
* If each array has an element with the same string key value, the latter
* will overwrite the former (different from array_merge_recursive).
* Recursive merging will be conducted if both arrays have an element of array
* type and are having the same key.
* For integer-keyed elements, the elements from the latter array will
* be appended to the former array.
* @param array $a array to be merged to
* @param array $b array to be merged from. You can specify additional
* arrays via third argument, fourth argument etc.
* @return array the merged array (the original arrays are not changed.)
*/
public static function merge($a, $b)
```
## Converting Objects to Arrays <a name="converting-objects-to-arrays"></a>
Often you need to convert an object or an array of objects into an array. The most common case is converting active record
......@@ -276,18 +278,18 @@ $data = ArrayHelper::toArray($post, [
]);
```
The first argument contains the data we want to convert. In our case we're converting a `Post` AR model.
The first argument contains the data we want to convert. In our case we're converting a `Post` AR model.
The second argument is conversion mapping per class. We're setting a mapping for `Post` model.
The second argument is conversion mapping per class. We're setting a mapping for `Post` model.
Each mapping array contains a set of mappings. Each mapping could be:
- A field name to include as is.
- A key-value pair of desired array key name and model column name to take value from.
- A key-value pair of desired array key name and a callback which returns value.
The result of conversion above will be:
```php
[
'id' => 123,
......
......@@ -32,7 +32,7 @@ return [
Basic usage
-----------
Once 'mailer' component is configured, you can use the following code to send an email message:
Once the 'mailer' component is configured, you can use the following code to send an email message:
```php
Yii::$app->mailer->compose()
......@@ -44,7 +44,7 @@ Yii::$app->mailer->compose()
->send();
```
In above example method `compose()` creates an instance of the mail message, which then is populated and sent.
In the above example the method `compose()` creates an instance of the mail message, which then is populated and sent.
You may put more complex logic in this process if needed:
```php
......
......@@ -11,6 +11,7 @@ use yii\base\Action;
use yii\base\Exception;
use yii\base\InvalidConfigException;
use yii\base\NotSupportedException;
use yii\helpers\Url;
use yii\web\Response;
use yii\web\HttpException;
use yii\web\NotFoundHttpException;
......@@ -156,7 +157,7 @@ class AuthAction extends Action
*/
protected function defaultCancelUrl()
{
return Yii::$app->getRequest()->getAbsoluteUrl();
return Url::to(Yii::$app->getUser()->loginUrl);
}
/**
......
......@@ -4,7 +4,8 @@ Yii Framework 2 authclient extension Change Log
2.0.2 under development
-----------------------
- no changes in this release.
- Bug #6502: Fixed `\yii\authclient\OAuth2::refreshAccessToken()` does not save fetched token (sebathi)
- Bug #6510: Fixed infinite redirect loop using default `\yii\authclient\AuthAction::cancelUrl` (klimov-paul)
2.0.1 December 07, 2014
......
......@@ -158,7 +158,10 @@ class OAuth2 extends BaseOAuth
$params = array_merge($token->getParams(), $params);
$response = $this->sendRequest('POST', $this->tokenUrl, $params);
return $response;
$token = $this->createToken(['params' => $response]);
$this->setAccessToken($token);
return $token;
}
/**
......
......@@ -50,6 +50,9 @@ class OAuthToken extends Object
private $_params = [];
/**
* @inheritdoc
*/
public function init()
{
if ($this->createTimestamp === null) {
......
......@@ -35,6 +35,7 @@ use yii\helpers\Html;
* ],
* ],
* ],
* 'options' => ['class' =>'nav-pills'], // set this to nav-tab to get tab-styled navigation
* ]);
* ```
*
......
......@@ -5,7 +5,6 @@ Yii Framework 2 gii extension Change Log
-----------------------
- Bug #6463: The Gii controller generator generates incorrect controller namespace (pana1990)
- Enh #3665: Improved Gii CRUD generated code to support setting initial conditions via initializing search model (mdmunir, fsateler, samdark)
2.0.1 December 07, 2014
......
......@@ -69,7 +69,7 @@ class <?= $searchModelClass ?> extends <?= isset($modelAlias) ? $modelAlias : $m
'query' => $query,
]);
if ($this->load($params) && !$this->validate()) {
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
......
......@@ -5,6 +5,7 @@ Yii Framework 2 jui extension Change Log
-----------------------
- Enh #6570: Datepicker now uses fallback to find language files, e.g. application language is `de-DE` and the translation files does not exists, it will use `de` instead (cebe)
- Enh #6471: Datepicker will now show an empty field when value is an empty string (cebe)
2.0.1 December 07, 2014
......
......@@ -169,7 +169,7 @@ class DatePicker extends InputWidget
} else {
$value = $this->value;
}
if ($value !== null) {
if ($value !== null && $value !== '') {
// format value according to dateFormat
try {
$value = Yii::$app->formatter->asDate($value, $this->dateFormat);
......
......@@ -36,9 +36,10 @@ use yii\di\Instance;
class Cache extends \yii\caching\Cache
{
/**
* @var Connection|string the MongoDB connection object or the application component ID of the MongoDB connection.
* @var Connection|array|string the MongoDB connection object or the application component ID of the MongoDB connection.
* After the Cache object is created, if you want to change this property, you should only assign it
* with a MongoDB connection object.
* Starting from version 2.0.2, this can also be a configuration array for creating the object.
*/
public $db = 'mongodb';
/**
......
......@@ -34,8 +34,9 @@ use yii\helpers\Json;
abstract class Migration extends Component implements MigrationInterface
{
/**
* @var Connection|string the MongoDB connection object or the application component ID of the MongoDB connection
* @var Connection|array|string the MongoDB connection object or the application component ID of the MongoDB connection
* that this migration should work with.
* Starting from version 2.0.2, this can also be a configuration array for creating the object.
*/
public $db = 'mongodb';
......@@ -217,4 +218,4 @@ abstract class Migration extends Component implements MigrationInterface
return $collection;
}
}
}
\ No newline at end of file
}
......@@ -7,7 +7,7 @@ This extension provides the [MongoDB](http://www.mongodb.org/) integration for t
Installation
------------
This extension requires [MongoDB PHP Extension](http://us1.php.net/manual/en/book.mongo.php) version 1.4.0 or higher.
This extension requires [MongoDB PHP Extension](http://us1.php.net/manual/en/book.mongo.php) version 1.5.0 or higher.
The preferred way to install this extension is through [composer](http://getcomposer.org/download/).
......
......@@ -38,9 +38,10 @@ use yii\di\Instance;
class Session extends \yii\web\Session
{
/**
* @var Connection|string the MongoDB connection object or the application component ID of the MongoDB connection.
* @var Connection|array|string the MongoDB connection object or the application component ID of the MongoDB connection.
* After the Session object is created, if you want to change this property, you should only assign it
* with a MongoDB connection object.
* Starting from version 2.0.2, this can also be a configuration array for creating the object.
*/
public $db = 'mongodb';
/**
......
......@@ -8,6 +8,12 @@ if you want to upgrade from version A to version C and there is
version B between A and C, you need to following the instructions
for both A and B.
Upgrade from Yii 2.0.1
----------------------
* MongoDB PHP extension min version raised up to 1.5.0. You should upgrade your environment in case you are
using older version.
Upgrade from Yii 2.0.0
----------------------
......
......@@ -19,7 +19,7 @@
],
"require": {
"yiisoft/yii2": "*",
"ext-mongo": ">=1.4.0"
"ext-mongo": ">=1.5.0"
},
"autoload": {
"psr-4": { "yii\\mongodb\\": "" }
......
......@@ -11,8 +11,11 @@ Yii Framework 2 Change Log
- Bug #6648: Added explicit type casting to avoid dblib issues on SQL Server 2014 (o-rey)
- Bug #6691: Fixed console help description parsing with UTF8 characters (cebe)
- Bug #6717: Fixed issue with UrlManager not matching a route on url creation when it was prefixed with `/` and pattern was empty (cebe)
- Bug #6736: Removed `Content-Transfer-Encoding` from the list of default download headers (DaSourcerer)
- Enh #4502: Added alias support to URL route when calling `Url::toRoute()` and `Url::to()` (qiangxue, lynicidn)
- Enh #5194: `yii\console\controllers\AssetController` now handles bundle files from external resources properly (klimov-paul)
- Enh #6247: Logger and error handler are now using slightly less memory (stepanselyuk, samdark)
- Enh #6398: Added support for specifying dependent component in terms of a configuration array for classes such as `DbCache` (qiangxue)
- Enh #6434: Added `yii\behaviors\SluggableBehavior::immutable` to support keeping the generated slug unchanged (trntv)
- Enh #6467: `ActiveForm` will scroll to the nearest visible element when the first error input is hidden (newartix)
- Enh #6488: Support changing `yii\base\Theme::basePath` during runtime (qiangxue)
......
......@@ -37,9 +37,10 @@ use yii\di\Instance;
class DbCache extends Cache
{
/**
* @var Connection|string the DB connection object or the application component ID of the DB connection.
* @var Connection|array|string the DB connection object or the application component ID of the DB connection.
* After the DbCache object is created, if you want to change this property, you should only assign it
* with a DB connection object.
* Starting from version 2.0.2, this can also be a configuration array for creating the object.
*/
public $db = 'db';
/**
......
......@@ -12,6 +12,7 @@ use yii\console\Exception;
use yii\console\Controller;
use yii\helpers\Console;
use yii\helpers\VarDumper;
use yii\web\AssetBundle;
/**
* Allows you to combine and compress your JavaScript and CSS files.
......@@ -65,6 +66,37 @@ class AssetController extends Controller
* ~~~
*
* File names can contain placeholder "{hash}", which will be filled by the hash of the resulting file.
*
* You may specify several target bundles in order to compress different groups of assets.
* In this case you should use 'depends' key to specify, which bundles should be covered with particular
* target bundle. You may leave 'depends' to be empty for single bundle, which will compress all remaining
* bundles in this case.
* For example:
*
* ~~~
* 'app\config\AllShared' => [
* 'js' => 'js/all-shared-{hash}.js',
* 'css' => 'css/all-shared-{hash}.css',
* 'depends' => [
* // Include all assets shared between 'backend' and 'frontend'
* 'yii\web\YiiAsset',
* 'app\assets\SharedAsset',
* ],
* ],
* 'app\config\AllBackEnd' => [
* 'js' => 'js/all-{hash}.js',
* 'css' => 'css/all-{hash}.css',
* 'depends' => [
* // Include only 'backend' assets:
* 'app\assets\AdminAsset'
* ],
* ],
* 'app\config\AllFrontEnd' => [
* 'js' => 'js/all-{hash}.js',
* 'css' => 'css/all-{hash}.css',
* 'depends' => [], // Include all remaining assets
* ],
* ~~~
*/
public $targets = [];
/**
......@@ -298,8 +330,10 @@ class AssetController extends Controller
foreach ($target->depends as $name) {
if (isset($bundles[$name])) {
foreach ($bundles[$name]->$type as $file) {
$inputFiles[] = $bundles[$name]->basePath . '/' . $file;
if (!$this->isBundleExternal($bundles[$name])) {
foreach ($bundles[$name]->$type as $file) {
$inputFiles[] = $bundles[$name]->basePath . '/' . $file;
}
}
} else {
throw new Exception("Unknown bundle: '{$name}'");
......@@ -352,9 +386,14 @@ class AssetController extends Controller
}
foreach ($map as $bundle => $target) {
$sourceBundle = $bundles[$bundle];
$depends = $sourceBundle->depends;
if (!$this->isBundleExternal($sourceBundle)) {
$depends[] = $target;
}
$targets[$bundle] = Yii::createObject([
'class' => strpos($bundle, '\\') !== false ? $bundle : 'yii\\web\\AssetBundle',
'depends' => [$target],
'depends' => $depends,
]);
}
......@@ -402,12 +441,16 @@ class AssetController extends Controller
'css' => $target->css,
];
} else {
$array[$name] = [
'sourcePath' => null,
'js' => [],
'css' => [],
'depends' => $target->depends,
];
if ($this->isBundleExternal($target)) {
$array[$name] = $this->composeBundleConfig($target);
} else {
$array[$name] = [
'sourcePath' => null,
'js' => [],
'css' => [],
'depends' => $target->depends,
];
}
}
}
$array = VarDumper::export($array);
......@@ -683,4 +726,24 @@ EOD;
}
return implode(DIRECTORY_SEPARATOR, $realPathParts);
}
/**
* @param AssetBundle $bundle
* @return boolean whether asset bundle external or not.
*/
private function isBundleExternal($bundle)
{
return (empty($bundle->sourcePath) && empty($bundle->basePath));
}
/**
* @param AssetBundle $bundle asset bundle instance.
* @return array bundle configuration.
*/
private function composeBundleConfig($bundle)
{
$config = Yii::getObjectVars($bundle);
$config['class'] = get_class($bundle);
return $config;
}
}
......@@ -72,8 +72,9 @@ class ActiveDataProvider extends BaseDataProvider
*/
public $key;
/**
* @var Connection|string the DB connection object or the application component ID of the DB connection.
* @var Connection|array|string the DB connection object or the application component ID of the DB connection.
* If not set, the default DB connection will be used.
* Starting from version 2.0.2, this can also be a configuration array for creating the object.
*/
public $db;
......
......@@ -64,7 +64,8 @@ use yii\di\Instance;
class SqlDataProvider extends BaseDataProvider
{
/**
* @var Connection|string the DB connection object or the application component ID of the DB connection.
* @var Connection|array|string the DB connection object or the application component ID of the DB connection.
* Starting from version 2.0.2, this can also be a configuration array for creating the object.
*/
public $db = 'db';
/**
......
......@@ -39,10 +39,13 @@ use \yii\base\Component;
class Migration extends Component implements MigrationInterface
{
/**
* @var Connection|string the DB connection object or the application component ID of the DB connection
* that this migration should work with. Note that when a Migration object is created by
* the `migrate` command, this property will be overwritten by the command. If you do not want to
* use the DB connection provided by the command, you may override the [[init()]] method like the following:
* @var Connection|array|string the DB connection object or the application component ID of the DB connection
* that this migration should work with. Starting from version 2.0.2, this can also be a configuration array
* for creating the object.
*
* Note that when a Migration object is created by the `migrate` command, this property will be overwritten
* by the command. If you do not want to use the DB connection provided by the command, you may override
* the [[init()]] method like the following:
*
* ```php
* public function init()
......
......@@ -92,13 +92,14 @@ class Instance
*
* // returns Yii::$app->db
* $db = Instance::ensure('db', Connection::className());
* // or
* $instance = Instance::of('db');
* $db = Instance::ensure($instance, Connection::className());
* // returns an instance of Connection using the given configuration
* $db = Instance::ensure(['dsn' => 'sqlite:path/to/my.db'], Connection::className());
* ```
*
* @param object|string|static $reference an object or a reference to the desired object.
* @param object|string|array|static $reference an object or a reference to the desired object.
* You may specify a reference in terms of a component ID or an Instance object.
* Starting from version 2.0.2, you may also pass in a configuration array for creating the object.
* If the "class" value is not specified in the configuration array, it will use the value of `$type`.
* @param string $type the class/interface name to be checked. If null, type check will not be performed.
* @param ServiceLocator|Container $container the container. This will be passed to [[get()]].
* @return object the object referenced by the Instance, or `$reference` itself if it is an object.
......@@ -108,6 +109,13 @@ class Instance
{
if ($reference instanceof $type) {
return $reference;
} elseif (is_array($reference)) {
$class = isset($reference['class']) ? $reference['class'] : $type;
if (!$container instanceof Container) {
$container = Yii::$container;
}
unset($reference['class']);
return $container->get($class, [], $reference);
} elseif (empty($reference)) {
throw new InvalidConfigException('The required component is not specified.');
}
......
......@@ -57,7 +57,8 @@ use yii\web\ForbiddenHttpException;
class AccessControl extends ActionFilter
{
/**
* @var User|string the user object representing the authentication status or the ID of the user application component.
* @var User|array|string the user object representing the authentication status or the ID of the user application component.
* Starting from version 2.0.2, this can also be a configuration array for creating the object.
*/
public $user = 'user';
/**
......
......@@ -53,17 +53,19 @@ class DbMessageSource extends MessageSource
const CACHE_KEY_PREFIX = 'DbMessageSource';
/**
* @var Connection|string the DB connection object or the application component ID of the DB connection.
* @var Connection|array|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.
* Starting from version 2.0.2, this can also be a configuration array for creating the object.
*/
public $db = 'db';
/**
* @var Cache|string the cache object or the application component ID of the cache object.
* @var Cache|array|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.
* Starting from version 2.0.2, this can also be a configuration array for creating the object.
*/
public $cache = 'cache';
/**
......
......@@ -32,9 +32,10 @@ use yii\helpers\VarDumper;
class DbTarget extends Target
{
/**
* @var Connection|string the DB connection object or the application component ID of the DB connection.
* @var Connection|array|string the DB connection object or the application component ID of the DB connection.
* After the DbTarget object is created, if you want to change this property, you should only assign it
* with a DB connection object.
* Starting from version 2.0.2, this can also be a configuration array for creating the object.
*/
public $db = 'db';
/**
......
......@@ -50,9 +50,10 @@ class EmailTarget extends Target
*/
public $message = [];
/**
* @var MailerInterface|string the mailer object or the application component ID of the mailer object.
* @var MailerInterface|array|string the mailer object or the application component ID of the mailer object.
* After the EmailTarget object is created, if you want to change this property, you should only assign it
* with a mailer object.
* Starting from version 2.0.2, this can also be a configuration array for creating the object.
*/
public $mailer = 'mailer';
......
......@@ -23,9 +23,10 @@ use yii\di\Instance;
abstract class DbMutex extends Mutex
{
/**
* @var Connection|string the DB connection object or the application component ID of the DB connection.
* @var Connection|array|string the DB connection object or the application component ID of the DB connection.
* After the Mutex object is created, if you want to change this property, you should only assign
* it with a DB connection object.
* Starting from version 2.0.2, this can also be a configuration array for creating the object.
*/
public $db = 'db';
......
......@@ -36,9 +36,10 @@ use yii\di\Instance;
class DbManager extends BaseManager
{
/**
* @var Connection|string the DB connection object or the application component ID of the DB connection.
* @var Connection|array|string the DB connection object or the application component ID of the DB connection.
* After the DbManager object is created, if you want to change this property, you should only assign it
* with a DB connection object.
* Starting from version 2.0.2, this can also be a configuration array for creating the object.
*/
public $db = 'db';
/**
......
......@@ -23,9 +23,10 @@ use yii\base\Object;
abstract class DbFixture extends Fixture
{
/**
* @var Connection|string the DB connection object or the application component ID of the DB connection.
* @var Connection|array|string the DB connection object or the application component ID of the DB connection.
* After the DbFixture object is created, if you want to change this property, you should only assign it
* with a DB connection object.
* Starting from version 2.0.2, this can also be a configuration array for creating the object.
*/
public $db = 'db';
......
......@@ -39,11 +39,13 @@ use yii\di\Instance;
class CacheSession extends Session
{
/**
* @var Cache|string the cache object or the application component ID of the cache object.
* @var Cache|array|string the cache object or the application component ID of the cache object.
* The session data will be stored using this cache object.
*
* After the CacheSession object is created, if you want to change this property,
* you should only assign it with a cache object.
*
* Starting from version 2.0.2, this can also be a configuration array for creating the object.
*/
public $cache = 'cache';
......
......@@ -38,9 +38,10 @@ use yii\di\Instance;
class DbSession extends Session
{
/**
* @var Connection|string the DB connection object or the application component ID of the DB connection.
* @var Connection|array|string the DB connection object or the application component ID of the DB connection.
* After the DbSession object is created, if you want to change this property, you should only assign it
* with a DB connection object.
* Starting from version 2.0.2, this can also be a configuration array for creating the object.
*/
public $db = 'db';
/**
......
......@@ -557,7 +557,6 @@ class Response extends \yii\base\Response
->setDefault('Accept-Ranges', 'bytes')
->setDefault('Expires', '0')
->setDefault('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')
->setDefault('Content-Transfer-Encoding', 'binary')
->setDefault('Content-Disposition', "$disposition; filename=\"$attachmentName\"");
if ($mimeType !== null) {
......
......@@ -24,9 +24,10 @@ use yii\di\Instance;
class FragmentCache extends Widget
{
/**
* @var Cache|string the cache object or the application component ID of the cache object.
* @var Cache|array|string the cache object or the application component ID of the cache object.
* After the FragmentCache object is created, if you want to change this property,
* you should only assign it with a cache object.
* Starting from version 2.0.2, this can also be a configuration array for creating the object.
*/
public $cache = 'cache';
/**
......
......@@ -95,7 +95,9 @@ class AssetControllerTest extends TestCase
*/
protected function createCompressConfig(array $bundles)
{
$className = $this->declareAssetBundleClass(['class' => 'AssetBundleAll']);
static $classNumber = 0;
$classNumber++;
$className = $this->declareAssetBundleClass(['class' => 'AssetBundleAll' . $classNumber]);
$baseUrl = '/test';
$config = [
'bundles' => $bundles,
......@@ -283,7 +285,15 @@ EOL;
// Then :
$this->assertTrue(file_exists($bundleFile), 'Unable to create output bundle file!');
$this->assertTrue(is_array(require($bundleFile)), 'Output bundle file has incorrect format!');
$compressedBundleConfig = require($bundleFile);
$this->assertTrue(is_array($compressedBundleConfig), 'Output bundle file has incorrect format!');
$this->assertCount(2, $compressedBundleConfig, 'Output bundle config contains wrong bundle count!');
$this->assertArrayHasKey($assetBundleClassName, $compressedBundleConfig, 'Source bundle is lost!');
$compressedAssetBundleConfig = $compressedBundleConfig[$assetBundleClassName];
$this->assertEmpty($compressedAssetBundleConfig['css'], 'Compressed bundle css is not empty!');
$this->assertEmpty($compressedAssetBundleConfig['js'], 'Compressed bundle js is not empty!');
$this->assertNotEmpty($compressedAssetBundleConfig['depends'], 'Compressed bundle dependency is invalid!');
$compressedCssFileName = $this->testAssetsBasePath . DIRECTORY_SEPARATOR . 'all.css';
$this->assertTrue(file_exists($compressedCssFileName), 'Unable to compress CSS files!');
......@@ -301,6 +311,73 @@ EOL;
}
/**
* @depends testActionCompress
*
* @see https://github.com/yiisoft/yii2/issues/5194
*/
public function testCompressExternalAsset()
{
// Given :
$externalAssetConfig = [
'class' => 'ExternalAsset',
'sourcePath' => null,
'basePath' => null,
'js' => [
'//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js',
],
'css' => [
'//ajax.googleapis.com/css/libs/jquery/2.1.1/jquery.ui.min.css'
],
];
$externalAssetBundleClassName = $this->declareAssetBundleClass($externalAssetConfig);
$cssFiles = [
'css/test.css' => 'body {
padding-top: 20px;
padding-bottom: 60px;
}',
];
$this->createAssetSourceFiles($cssFiles);
$jsFiles = [
'js/test.js' => "function test() {
alert('Test message');
}",
];
$this->createAssetSourceFiles($jsFiles);
$regularAssetBundleClassName = $this->declareAssetBundleClass([
'class' => 'RegularAsset',
'css' => array_keys($cssFiles),
'js' => array_keys($jsFiles),
'depends' => [
$externalAssetBundleClassName
],
]);
$bundles = [
$regularAssetBundleClassName
];
$bundleFile = $this->testFilePath . DIRECTORY_SEPARATOR . 'bundle.php';
$configFile = $this->testFilePath . DIRECTORY_SEPARATOR . 'config.php';
$this->createCompressConfigFile($configFile, $bundles);
// When :
$this->runAssetControllerAction('compress', [$configFile, $bundleFile]);
// Then :
$this->assertTrue(file_exists($bundleFile), 'Unable to create output bundle file!');
$compressedBundleConfig = require($bundleFile);
$this->assertTrue(is_array($compressedBundleConfig), 'Output bundle file has incorrect format!');
$this->assertArrayHasKey($externalAssetBundleClassName, $compressedBundleConfig, 'External bundle is lost!');
$compressedExternalAssetConfig = $compressedBundleConfig[$externalAssetBundleClassName];
$this->assertEquals($externalAssetConfig['js'], $compressedExternalAssetConfig['js'], 'External bundle js is lost!');
$this->assertEquals($externalAssetConfig['css'], $compressedExternalAssetConfig['css'], 'External bundle css is lost!');
$compressedRegularAssetConfig = $compressedBundleConfig[$regularAssetBundleClassName];
$this->assertContains($externalAssetBundleClassName, $compressedRegularAssetConfig['depends'], 'Dependency on external bundle is lost!');
}
/**
* Data provider for [[testAdjustCssUrl()]].
* @return array test data.
*/
......
......@@ -8,6 +8,7 @@
namespace yiiunit\framework\di;
use yii\base\Component;
use yii\db\Connection;
use yii\di\Container;
use yii\di\Instance;
use yiiunit\TestCase;
......@@ -29,4 +30,20 @@ class InstanceTest extends TestCase
$this->assertTrue(Instance::ensure($instance, $className, $container) instanceof Component);
$this->assertTrue($instance->get($container) !== Instance::ensure($instance, $className, $container));
}
public function testEnsure()
{
$container = new Container;
$container->set('db', [
'class' => 'yii\db\Connection',
'dsn' => 'test',
]);
$this->assertTrue(Instance::ensure('db', 'yii\db\Connection', $container) instanceof Connection);
$this->assertTrue(Instance::ensure(new Connection, 'yii\db\Connection', $container) instanceof Connection);
$this->assertTrue(Instance::ensure([
'class' => 'yii\db\Connection',
'dsn' => 'test',
], 'yii\db\Connection', $container) instanceof Connection);
}
}
......@@ -129,6 +129,10 @@ class YiiRequirementCheckerTest extends TestCase
public function testCheckPhpExtensionVersion()
{
if (defined('HHVM_VERSION')) {
$this->markTestSkipped('Can not test this on HHVM.');
}
$requirementsChecker = new YiiRequirementChecker();
$this->assertFalse($requirementsChecker->checkPhpExtensionVersion('some_unexisting_php_extension', '0.1'), 'No fail while checking unexisting extension!');
......
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