Commit 238f393f by Qiang Xue

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

parents 231111da 9c4570ec
Запуск приложения
====================
После установки Yii, базовое приложение будет доступно либо по URL `http://hostname/basic/web/index.php`, либо по `http://hostname/index.php`, в зависимости от настроек Web сервера. Данный раздел - общее введение в организацию кода, встроенный функционал и обработку обращений приложением Yii.
После установки Yii базовое приложение будет доступно либо по URL `http://hostname/basic/web/index.php`, либо по `http://hostname/index.php`, в зависимости от настроек Web сервера. Данный раздел - общее введение в организацию кода, встроенный функционал и обработку обращений приложением Yii.
> Информация: Далее, в данном руководстве предполагается что Yii установлен в директорию `basic/web`, которая, в свою очередь, установлена как корневой каталог в настройках Web сервера. В результате, обратившись по URL `http://hostname/index.php` Вы получите доступ к приложению, расположенному в `basic/web`. Детальнее с процессом начальной настройки можно познакомиться в разделе [Установка Yii](start-installation.md).
> Информация: далее в данном руководстве предполагается, что Yii установлен в директорию `basic/web`, которая, в свою очередь, установлена как корневой каталог в настройках Web сервера. В результате, обратившись по URL `http://hostname/index.php`, Вы получите доступ к приложению, расположенному в `basic/web`. Детальнее с процессом начальной настройки можно познакомиться в разделе [Установка Yii](start-installation.md).
Функционал <a name="functionality"></a>
---------------
......@@ -11,7 +11,7 @@
Установленный шаблон простого приложения состоит из четырех страниц:
* домашняя страница, отображается при переходе по URL `http://hostname/index.php`
* "About" ("О нас")
* страница "About" ("О нас")
* на странице "Contact" находится форма обратной связи, на которой пользователь может обратиться к разработчику по e-mail
* на странице "Login" отображается форма авторизации. Попытайтесь авторизоваться с логином/паролем "admin/admin". Обратите внимание на изменение раздела "Login" в главном меню на "Logout".
......@@ -69,7 +69,7 @@ basic/ корневой каталог приложения
3. Приложение определяет [маршрут](runtime-routing.md) запроса при помощи компонента приложения [запрос](runtime-requests.md).
4. Приложение создает экземпляр [контроллера](structure-controllers.md) для выполнения запроса.
5. Контроллер, в свою очередь, создает [действие](structure-controllers.md) и накладывает на него фильтры.
6. Если хотя бы один фильтр дает сбой выполнение приложения останавливается.
6. Если хотя бы один фильтр дает сбой, выполнение приложения останавливается.
7. Если все фильтры пройдены - приложение выполняется.
8. Действие загружает модель данных. Вероятнее всего из базы данных.
9. Действие генерирует вид, отображая в нем данные (в т.ч. и полученные из модели).
......
Yii 2.0 bo`yicha to`liq qo`llanma
Yii 2.0 bo'yicha to'liq qo'llanma
=============================
Ushbu qo`llanma [Yii qo`llanmalarining holati bilan](http://www.yiiframework.com/doc/terms/) bilan mos holda yo`lga qo`yildi.
Ushbu qo'llanma [Yii qo'llanmalarining holati bilan](http://www.yiiframework.com/doc/terms/) bilan mos holda yo'lga qo'yildi.
All Rights Reserved.
......@@ -17,11 +17,11 @@ Kirish
Birinchi tanishuv
-----------------
* [Yii ni o`rnatish](start-installation.md)
* [Yii ni o'rnatish](start-installation.md)
* [Ilovani ishga tushirish](start-workflow.md)
* [«Salom» deymiz](start-hello.md)
* [Formalar bilan ishlash](start-forms.md)
* [Ma`lumotlar ombori bilan ishlash](start-databases.md)
* [Ma'lumotlar ombori bilan ishlash](start-databases.md)
* [Gii yordamida kodlarni generatsiya qilish](start-gii.md)
* [Keyin nima?](start-looking-ahead.md)
......@@ -33,26 +33,26 @@ Ilova strukturasi
* [Kirish skriptlari](structure-entry-scripts.md)
* [Ilova](structure-applications.md)
* [Ilova komponentlari](structure-application-components.md)
* [Kontrollerlar](structure-controllers.md)
* [Kontrollyorlar](structure-controllers.md)
* [Namoyish](structure-views.md)
* [Modellar](structure-models.md)
* **TBD** [Filtrlar](structure-filters.md)
* **TBD** [Vidjetlar](structure-widgets.md)
* **TBD** [Modullar](structure-modules.md)
* [Ресурсы](structure-assets.md)
* [Resurslar](structure-assets.md)
* **TBD** [Kengaytmalar](structure-extensions.md)
So`rovlarni qayta ishlash
So'rovlarni qayta ishlash
-------------------------
* **TBD** [Bootstrapping](runtime-bootstrapping.md)
* **TBD** [Routing](runtime-routing.md)
* **TBD** [So`rovlar](runtime-requests.md)
* **TBD** [So'rovlar](runtime-requests.md)
* **TBD** [Javoblar](runtime-responses.md)
* **TBD** [Sessiyalar va kuklar](runtime-sessions-cookies.md)
* [URL ni tahlil va generatsiya qilish](runtime-url-handling.md)
* [Xatolilarni qayta ishlash](runtime-handling-errors.md)
* [Xatoliklarni qayta ishlash](runtime-handling-errors.md)
* [Jurnallarga yozish](runtime-logging.md)
......@@ -62,28 +62,28 @@ Asosiy tushunchalar
* [Komponentlar](concept-components.md)
* [Xususiyat](concept-properties.md)
* [Xodisa](concept-events.md)
* [O`zini tutish](concept-behaviors.md)
* [Muxim sozlashlar](concept-configurations.md)
* [O'zini tutish](concept-behaviors.md)
* [Muhim sozlashlar](concept-configurations.md)
* [Taxalluslar](concept-aliases.md)
* [Sinflarni avtoyuklash](concept-autoloading.md)
* [Service Locator](concept-service-locator.md)
* [Dependency Injection Container](concept-di-container.md)
Ma`lumotlar ombori bilan ishlash
Ma'lumotlar ombori bilan ishlash
--------------------------------
* [Ma`lumotlarga imkon beruvchi obektlar(DAO)](db-dao.md) - Ma`lumotlar ombori bilan bog`lanish, oddiy so`rovlar, tranzaksiya va sxema bilan ishlash.
* [So`rovlarni yaratuvchi](db-query-builder.md) - Ma`lumotlar omboriga abstraksiyaning oddiy qatlamidan so`rovlar.
* [Active Record](db-active-record.md) - AR obektlarini olish, ular bilan ishlash va bog`lanishlarni aniqlash.
* [Migratsiyalar](db-migrations.md) - Komandada ishlaganda ma`lumotlar sxemasini talqinlarini boshqarish.
* [Ma'lumotlar bilan ishlashga imkon beruvchi obektlar(DAO)](db-dao.md) - Ma'lumotlar ombori bilan bog'lanish, oddiy so'rovlar, tranzaksiya va sxema bilan ishlash.
* [So'rovlarni yaratuvchi](db-query-builder.md) - Ma'lumotlar omboriga abstraksiyaning oddiy qatlamidan so'rovlar.
* [Active Record](db-active-record.md) - AR obektlarini olish, ular bilan ishlash va bog'lanishlarni aniqlash.
* [Migratsiyalar](db-migrations.md) - Komandada (jamoada) ishlaganda ma'lumotlar sxemasini talqinlarini boshqarish.
* **TBD** [Sphinx](db-sphinx.md)
* **TBD** [Redis](db-redis.md)
* **TBD** [MongoDB](db-mongodb.md)
* **TBD** [ElasticSearch](db-elastic-search.md)
Foydalanuvchidan ma`lumotlarni qabul qilish
Foydalanuvchidan ma'lumotlarni qabul qilish
-------------------------------------------
* [Formani yaratish](input-forms.md)
......@@ -92,14 +92,14 @@ Foydalanuvchidan ma`lumotlarni qabul qilish
* **TBD** [Bir nechta modellar bilan ishlash](input-multiple-models.md)
Ma`lumotlarni namoyish etish
Ma'lumotlarni namoyish etish
----------------------------
* **TBD** [Ma`lumotlarni formatlash](output-formatting.md)
* **TBD** [Sahifalar bo`yicha bo`ajratish](output-pagination.md)
* **TBD** [Ma'lumotlarni formatlash](output-formatting.md)
* **TBD** [Sahifalar bo'yicha ajratish](output-pagination.md)
* **TBD** [Saralash](output-sorting.md)
* [Ma`lumotlar provayderlari](output-data-providers.md)
* [Ma`lumotlar uchun vidjetlar](output-data-widgets.md)
* [Ma'lumotlar provayderlari](output-data-providers.md)
* [Ma'lumotlar uchun vidjetlar](output-data-widgets.md)
* [Mavzulashtirish](output-theming.md)
......@@ -107,9 +107,9 @@ Xavfsizlik
----------
* [Autentifikatsiya](security-authentication.md)
* [Mualliflikka tekshiruvi](security-authorization.md)
* [Avtorizatsiya](security-authorization.md)
* [Parollar bilan ishlash](security-passwords.md)
* **TBD** [Mualliflikka tekshiruvlar mijozlari](security-auth-clients.md)
* **TBD** [Avtorizatsiya mijozlari](security-auth-clients.md)
* **TBD** [Eng yaxshi amaliyotlar](security-best-practices.md)
......@@ -117,35 +117,35 @@ Keshlash
--------
* [Sharh](caching-overview.md)
* [Ma`lumotlarni keshlash](caching-data.md)
* [Fragmentlasrni keshlash](caching-fragment.md)
* [Ma'lumotlarni keshlash](caching-data.md)
* [Fragmentlarni keshlash](caching-fragment.md)
* [Sahifalarni keshlash](caching-page.md)
* [HTTP ni keshlash](caching-http.md)
REST veb-xizmatlari
REST web-xizmatlari
-------------------
* [Tezkor boshlash](rest-quick-start.md)
* [Resurslar](rest-resources.md)
* [Kontrollerlar](rest-controllers.md)
* [Kontrollyorlar](rest-controllers.md)
* [Routing](rest-routing.md)
* [Javoblarni formatlash](rest-response-formatting.md)
* [Autentifikatsiya](rest-authentication.md)
* [So`rovlarni chastotasini chegaralash](rest-rate-limiting.md)
* [So'rovlarni chastotasini chegaralash](rest-rate-limiting.md)
* [Talqin yaratish](rest-versioning.md)
* [Xatoliklarni qayta ishlash](rest-error-handling.md)
Ishlab chiquvchi uskunalari
Ishlab chiquvchining uskunalari
---------------------------
* [Sozlashlar paneli va sozlovchi](tool-debugger.md)
* [Qayta ishlash paneli va qayta ishlovchi](tool-debugger.md)
* [Gii bilan kodni generatsiya qilish](tool-gii.md)
* **TBD** [API qo`llanmani generatori](tool-api-doc.md)
* **TBD** [API qo'llanmani generatori](tool-api-doc.md)
Test o`tkazish
Test o'tkazish
--------------
* [Sharh](test-overview.md)
......@@ -160,7 +160,7 @@ Yii kengaytmalari
* [Kengaytmani yaratish](extend-creating-extensions.md)
* [Freymvork kodini kengaytirish](extend-customizing-core.md)
* [Tashqi kutubxonalarni qo`llash](extend-using-libs.md)
* [Tashqi kutubxonalarni qo'llash](extend-using-libs.md)
* **TBD** [Tashqi tizimlarda Yii integratsiyasi](extend-embedding-in-others.md)
* **TBD** [Yii 1.1 va 2.0 larni bir vaqtda ishlatish](extend-using-v1-v2.md)
* [Composer ni ishlatish](extend-using-composer.md)
......
......@@ -229,7 +229,7 @@ In order to securely pass query parameters you can use prepared statements:
```php
$command = $connection->createCommand('SELECT * FROM post WHERE id=:id');
$command->bindValue(':id', $_GET['id']);
$post = $command->query();
$post = $command->queryOne();
```
Another usage is performing a query multiple times while preparing it only once:
......
......@@ -19,7 +19,7 @@ Yii 2.0 fully embraces [Composer](https://getcomposer.org/), the de facto PHP pa
of the core framework, as well as extensions, are handled through Composer. Please refer to
the [Installing Yii](start-installation.md) section to learn how to install Yii 2.0. If you want to
create new extensions, or turn your existing 1.1 extensions into 2.0-compatible extensions, please refer to
the [Creating Extensions](extend-creating-extensions.md) section of the guide.
the [Creating Extensions](structure-extensions.md#creating-extensions) section of the guide.
PHP Requirements
......@@ -209,7 +209,7 @@ To learn more details about models, please refer to the [Models](structure-model
Controllers
-----------
Yii 2.0 uses [[yii\web\Controller]] as the base controller class, similar to `CWebController` in Yii 1.1.
Yii 2.0 uses [[yii\web\Controller]] as the base controller class, which is similar to `CController` in Yii 1.1.
[[yii\base\Action]] is the base class for action classes.
The most obvious impact of these changes on your code is that a controller action should return the content
......
......@@ -144,7 +144,7 @@ return [
```
Note that this configuration will only work if the web server has been properly configured for Yii, see
[installation](installation.md#recommended-apache-configuration).
[installation](start-installation.md#recommended-apache-configuration).
### Named parameters
......
......@@ -202,8 +202,9 @@ return [
The `authManager` can now be accessed via `\Yii::$app->authManager`.
> Tip: By default, [[yii\rbac\PhpManager]] stores RBAC data in the file `@app/data/rbac.php`.
Sometime you need to create this file manually.
> Tip: By default, [[yii\rbac\PhpManager]] stores RBAC data in three files: `@app/rbac/items.php`, `@app/rbac/assignments.php` and `@app/rbac/rules.php`.
Make sure these files are writable by the Web server process if the authorization needs to be changed online.
Sometimes you will need to create these files manually.
### Building Authorization Data
......@@ -301,8 +302,9 @@ For applications that require complex access control with dynamically updated au
(i.e. admin panel) may need to be developed using APIs offered by `authManager`.
> Tip: By default, [[yii\rbac\PhpManager]] stores RBAC data in the file `@app/data/rbac.php`.
Sometimes when you want to make some minor changes to the RBAC data, you may directly edit this file.
> Tip: By default, [[yii\rbac\PhpManager]] stores RBAC data in three files: `@app/rbac/items.php`, `@app/rbac/assignments.php` and `@app/rbac/rules.php`.
Make sure these files are writable by the Web server process if the authorization needs to be changed online.
Sometimes you will need to create these files manually.
### Using Rules
......
......@@ -2,7 +2,7 @@ Installing Yii
==============
You can install Yii in two ways, using [Composer](http://getcomposer.org/) or by downloading an archive file.
The former is the preferred way, as it allows you to install new [extensions](extend-creating-extensions.md) or update Yii by simply running a single command.
The former is the preferred way, as it allows you to install new [extensions](structure-extensions.md) or update Yii by simply running a single command.
> Note: Unlike with Yii 1, standard installations of Yii 2 result in both, the framework and an application skeleton being downloaded and installed.
......@@ -114,7 +114,7 @@ Configuring Web Servers <a name="configuring-web-servers"></a>
The application installed according to the above instructions should work out of box with either
an [Apache HTTP server](http://httpd.apache.org/) or an [Nginx HTTP server](http://nginx.org/), on
Windows, Mac OS X, or Linux running PHP 5.4 or higher. Yii 2.0 is also compatible the facebooks
Windows, Mac OS X, or Linux running PHP 5.4 or higher. Yii 2.0 is also compatible with facebooks
[HHVM](http://hhvm.com/) however there are some edge cases where HHVM behaves different than native
PHP so you have to take some extra care when using HHVM.
......
......@@ -463,7 +463,7 @@ use yii\i18n\MissingTranslationEvent;
class TranslationEventHandler
{
public static function(MissingTranslationEvent $event) {
public static function handleMissingTranslation(MissingTranslationEvent $event) {
$event->translatedMessage = "@MISSING: {$event->category}.{$event->message} FOR LANGUAGE {$event->language} @";
}
}
......
O'zbekchaga tarjima qilish bilan qanday ishlash kerak
=====================================================
Yii juda ko'p tillarga tarjima qilinayabdi shu jumladan o'zbekchaga ham. Tarjima qo'llanma va habarlarni o'z ichiga oladi.
Freymvork habari
----------------
Ikki turdagi habarlar bor: istisnolar, qaysiki ishlab chiquvchi nazarda tutgan va ular tarjima qilinmaydi va habarlar, qaysiki foydalanuvchilarga ko'rsatiladigan. Masalan, validatsiyaning xatoliklari.
Tarjimani yangilash uchun:
1. Konsolda `framework` direktoriyani ochamiz, `yii message/extract messages/config.php` ni ishga tushiramiz.
3. Habarlarni `framework/messages/uz/yii.php` ga ko`chiramiz. Muhimi fayllar UTF-8 kodlashda bo'lishi kerak.
4. `uz` dagi tarjimalar bilan [pull request qilamiz](https://github.com/yiisoft/yii2/blob/master/docs/internals/git-workflow.md), qolgan tillarga tegmaymiz.
Tarjima fayllarda massiv joylashgan. Uning kalitlari - boshlang'ich kodlar, qiymatlari - tarjima. Agar qiymat bo'sh bo'lsa habar tarjima qilinmagan hisoblanadi. Kodda boshqa uchramaydigan habarlar tarjimasi '@@' ga o'ralgan. Ayrim habarlar uchun [sonlar bilan qo'llanilishini qo'llab-quvvatlash uchun maxsus format](../guide/i18n.md) ni ishlatish zarur.
Qo'llanma
---------
Qo'llanamani tarjimasi `docs/<original>-uz` da joylashgan, bu yerda <original> - original direktoriyalarga mos keladi, masalan,
`guide` yoki `internals`.
Agar qo'llanma tarjimasi tugagan bo'lsa, build direktoriyasida konsolni ochib va quyidagini bajarib, originaldagi oxirgi tarjimadan keyingi diff o'zgarishlarni olish mumkin:
```
php build translation "../docs/guide" "../docs/guide-uz" "Uzbek guide translation report" > report_guide_uz.html
```
Agar composer uchun urushsa, bosh direktoriyada `composer install` ni bajaring.
Tarjima qilishdan oldin hech kim shug'ullanmayotganligini tekshiring va o'zingizga [barcha tarjima qilinayotgan hujjatlarni ro'yhatini] yozib oling
//Ushbu manzilni ulardan olgandan keyin o'zgartirib qo'yish kerak bo'ladi.
(https://docs.google.com/spreadsheets/d/10dS7VB_3jSxUorryRlplB7nhA59e3i2vLYmTwn_1d3I/edit?usp=sharing).
Barcha o'zgarishlarni quyidagi ko'rinishda olib boramiz [pull request](https://github.com/yiisoft/yii2/blob/master/docs/internals/git-workflow.md).
### Umumiy qoidalar
- Ko'p terminlar o'zbekchada bitta ma'noga ega emas va o'zbekchada ko'p qo'llanilmaydigandir, shu sababli agar matnda
shunday terminlar uchrasa ularni birinchi bor qo'llanilgan joyida qavs ichida ingliz tilidagi varianti
ko'rsatilishi kerak; (terminlarning tarjimasini qo'llanilish variantlari quyida keltirilgan);
- Agar tarjima vaqtida matnning qaysidir qismi mazmuni o'zgarayotgan bo'lsa va siz uni shunday tarjima qilish
kerakligiga ishonchingiz komil bo'lmayotganday tuyulsa ushbu qismni * ichiga oling(ichidagi matn qiya holatga keladi).
Bu olib tashlash/to'g'rilashlar vaqtida ushbu matnlarga alohida e'tibor qaratishga imkon beradi;
- Tarjima vaqtida fakt xatoliklarni qilmang!
- Matnda tashqi manbalarga murojaatlar uchraydi, agar murojaat terminni izohlash maqolasiga olib boradigan bo'lsa, u holda
o'zbekchada tarjimasi bo'r bo'lgan vaziyatda o'zbekchasiga murojaat qilinadi.
Masalan `http://en.wikipedia.org/wiki/Captcha` → `http://uz.wikipedia.org/wiki/Captcha`.
- Sharhlar kodda tarjima qilinadi, agarda birinchi holatdagi mazmunini o'zgartirmasa; Matndagi vaqtinchalik sharhlarni
imkon qadar faqat *lokal*da ishlatish kerak! Aks holda uni reliz ga tushib qolish ehtimoli bor;
- Bo'limlarni tarjima qilish vaqtida `README.md` dagi tarjimani olib ketamiz;
- Shaxsiy qo'shimcha-sharhlarni qo'shish imkoni bor, lekin xaosdan qochish uchun original bitta bo'lishi kerak. Bunga zarurat vaqtida sharh oxiriga
"tar. shar." ni qo'shish kerak;
- Hujjatni umumiy to'g'rilashni o'tkazgandan so'ng mustaqil ravishda faqat ushbu bo'limga tegsihli bo'lgan grammatikadagi, fakt xatoliklardagi o'zgarishlarni kiritish talab darajasida tavsiya etiladi. Boshqa holatlarda gaplarni to'g'rilash, yaxshilash uchun va zarur hollarda o'zgarishlarni markazlashgan tarzda barcha bo'limlar uchun amalga oshirish uchun ularni tahlilga qo'yish zarur.
### Qo'llanma strukturasi
Tarjima qilish vaqtida hujjatning struktura birligini to'g'ri nomlash muhim. Quyida keltirilgan strukturaga amal qilamiz :
- Bob 1
- Bo'lim 1
- Bo'lim 2
- Qism bo'lim 1
- ...
- Bo'lim N
- Bob 2
- ...
- Bob N
### Maxsus habarlarni tarjimasi
- Tip → Ko'rsatma
- Note → Eslatma
- Info → Ma'lumot
### Rasmlarni tarjima qilish
Qo'llanma uchun rasmlar `images` qism katalogida joylashgan. Ularning barchasi [yED](http://www.yworks.com/en/products_yed_about.html) da yaratilgan.
Zarurat tug'ilgan vaqtda fayl tarjima qilinayotgan katalogning `images` katalogiga nusxalanadi va tarjima qilinib png formatida saqlanadi.
Rasmlardagi yozuvlar tarjima qilinadi.
### Grammatika
Oxirgi variantni tashlashdan oldin uni umumiy stilini, orfografiyasini, punktlarini tekshiring. Tarjimani o'zbek tili uchun orfografiyani Wordda tekshirish imkoni bo'lmasada uning yordamida tayyorlashingiz mumkin;
### Terminlar ro'yhati
- action — amal.
- active record — tarjimasiz.
- attach handler — «qayta ishlovchini tayinlash».
- attribute of the model — model atributi.
- camel case — tarjimasiz.
- customization — (nozik) sozlash
- column — ustun (agar MO haqida gap ketayotgan bo'lsa).
- content — tashkil etuvchilari.
- controller — kontrollyor.
- debug (mode) — kod sozlash (tartibi) (production mode ga qarang).
- eager loading — ziqna yuklash uslubi/ziqna yuklash (lazy loading ga qarang).
- PHP extension — PHP kengaytmasi.
- field (of the table) — jadval (yoki atribut) maydoni.
- framework — freymvork.
- front-controller — front-kontrollyor.
- getter — getter.
- (event) handler — qayta ishlovchi (hodisa).
- hash — xesh.
- helper - yordamchi.
- id — qiymatlovchi(identifikatsiyalovchi).
- instance — nusxa.
- lazy loading — chetga olingan yuklash (qanday kerak bo'lsa shunday yuklasymiz va erta emas).
- method — metod (obektniki) //Diqqat! Obekt/klaslarda funksiyasi yo'q, faqat metodlari bor.
- model — model, ma`lumotlar modeli.
- model form — formalar modeli.
- parameter — parametr (metod yoki funksiyada va lekin klasda emas).
- to parse — qayta ishlash, agar *kontekst* tushunarsiz bo'lsa *parsing* qilish.
- placeholder — marker.
- production (mode) — ishlab chiqarish (rejimi) (см. debug mode).
- property — xususiyati (obekt).
- to render — *render* qilish, formallashtirish.
- related, relation — bog'langan, bog'lanish.
- resolve request — so'rovni oldindan qayta ishlash.
- route — marshrut.
- row (of the table) — satr(jadvallarniki).
- setter — setter.
- tabular input — tabli kiritish.
- to validate — tekshirish.
- valid — mos.
- validator — validator.
- validator class — validator klasi.
- view — namoyish.
- query builder — so'rovlar konstruktori.
\ No newline at end of file
......@@ -64,11 +64,13 @@ use yii\db\ActiveRelationTrait;
* This methods may only be called in a relational context. Same is true for [[inverseOf()]], which
* marks a relation as inverse of another relation.
*
* > NOTE: elasticsearch limits the number of records returned by any query to 10 records by default.
* > Note: elasticsearch limits the number of records returned by any query to 10 records by default.
* > If you expect to get more records you should specify limit explicitly in relation definition.
* > This is also important for relations that use [[via()]] so that if via records are limited to 10
* > the relations records can also not be more than 10.
*
* > Note: Currently [[with]] is not supported in combination with [[asArray]].
*
* @author Carsten Brandt <mail@cebe.cc>
* @since 2.0
*/
......
......@@ -270,6 +270,7 @@ class ActiveRecord extends BaseActiveRecord
* for the `_id` field so that it is part of the `_source` fields and thus becomes part of the attributes.
*
* @return string[] list of attribute names.
* @throws \yii\base\InvalidConfigException if not overridden in a child class.
*/
public function attributes()
{
......@@ -277,6 +278,19 @@ class ActiveRecord extends BaseActiveRecord
}
/**
* A list of attributes that should be treated as array valued when retrieved through [[ActiveQuery::fields]].
*
* If not listed by this method, attributes retrieved through [[ActiveQuery::fields]] will converted to a scalar value
* when the result array contains only one value.
*
* @return string[] list of attribute names. Must be a subset of [[attributes()]].
*/
public function arrayAttributes()
{
return [];
}
/**
* @return string the name of the index this record is stored in.
*/
public static function index()
......@@ -294,6 +308,10 @@ class ActiveRecord extends BaseActiveRecord
/**
* @inheritdoc
*
* @param ActiveRecord $record the record to be populated. In most cases this will be an instance
* created by [[instantiate()]] beforehand.
* @param array $row attribute values (name => value)
*/
public static function populateRecord($record, $row)
{
......@@ -302,9 +320,10 @@ class ActiveRecord extends BaseActiveRecord
$attributes = $row['_source'];
}
if (isset($row['fields'])) {
// reset fields in case it is scalar value TODO use field metadata for this
// reset fields in case it is scalar value
$arrayAttributes = $record->arrayAttributes();
foreach($row['fields'] as $key => $value) {
if (count($value) == 1) {
if (!isset($arrayAttributes[$key]) && count($value) == 1) {
$row['fields'][$key] = reset($value);
}
}
......@@ -439,6 +458,7 @@ class ActiveRecord extends BaseActiveRecord
* @param array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
* Please refer to [[ActiveQuery::where()]] on how to specify this parameter.
* @return integer the number of rows updated
* @throws Exception on error.
*/
public static function updateAll($attributes, $condition = [])
{
......@@ -498,6 +518,7 @@ class ActiveRecord extends BaseActiveRecord
* @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
* Please refer to [[Query::where()]] on how to specify this parameter.
* @return integer the number of rows updated
* @throws Exception on error.
*/
public static function updateAllCounters($counters, $condition = [])
{
......@@ -562,6 +583,7 @@ class ActiveRecord extends BaseActiveRecord
* @param array $condition the conditions that will be put in the WHERE part of the DELETE SQL.
* Please refer to [[ActiveQuery::where()]] on how to specify this parameter.
* @return integer the number of rows deleted
* @throws Exception on error.
*/
public static function deleteAll($condition = [])
{
......
......@@ -4,7 +4,7 @@ Yii Framework 2 elasticsearch extension Change Log
2.0.0 under development
-----------------------
- no changes in this release.
- Enh #3381: Added ActiveRecord::arrayAttributes() to define attributes that should be treated as array when retrieved via `fields` (cebe)
2.0.0-rc September 27, 2014
......
......@@ -319,7 +319,7 @@ class Connection extends Component
$body = '';
$options = [
CURLOPT_USERAGENT => 'Yii Framework 2 ' . __CLASS__,
CURLOPT_USERAGENT => 'Yii Framework ' . Yii::getVersion() . __CLASS__,
CURLOPT_RETURNTRANSFER => false,
CURLOPT_HEADER => false,
// http://www.php.net/manual/en/function.curl-setopt.php#82418
......
......@@ -320,7 +320,13 @@ class Query extends Component implements QueryInterface
}
$column = [];
foreach ($result['hits']['hits'] as $row) {
$column[] = isset($row['_source'][$field]) ? $row['_source'][$field] : null;
if (isset($row['fields'][$field])) {
$column[] = $row['fields'][$field];
} elseif (isset($row['_source'][$field])) {
$column[] = $row['_source'][$field];
} else {
$column[] = null;
}
}
return $column;
}
......
......@@ -81,7 +81,7 @@ class Markdown extends \cebe\markdown\Parser
*/
protected function renderCode($block)
{
return Console::ansiFormat(implode("\n", $block['content']), [Console::BG_GREY]) . "\n";
return Console::ansiFormat(implode("\n", $block['content']), [Console::NEGATIVE]) . "\n";
}
/**
......
......@@ -182,6 +182,7 @@ class HelpController extends Controller
protected function getDefaultHelp()
{
$commands = $this->getCommandDescriptions();
$this->stdout("\nThis is Yii version " . \Yii::getVersion() . ".\n");
if (!empty($commands)) {
$this->stdout("\nThe following commands are available:\n\n", Console::BOLD);
$len = 0;
......
......@@ -727,6 +727,7 @@ class Formatter extends Component
$value = $this->normalizeNumericValue($value);
if ($this->_intlLoaded) {
$f = $this->createNumberFormatter(NumberFormatter::DECIMAL, null, $options, $textOptions);
$f->setAttribute(NumberFormatter::FRACTION_DIGITS, 0);
return $f->format($value, NumberFormatter::TYPE_INT64);
} else {
return number_format((int) $value, 0, $this->decimalSeparator, $this->thousandSeparator);
......
......@@ -16,8 +16,8 @@ use yii\helpers\VarDumper;
* PhpManager represents an authorization manager that stores authorization
* information in terms of a PHP script file.
*
* The authorization data will be saved to and loaded from a file
* specified by [[authFile]], which defaults to 'protected/data/rbac.php'.
* The authorization data will be saved to and loaded from three files
* specified by [[itemFile]], [[assignmentFile]] and [[ruleFile]].
*
* PhpManager is mainly suitable for authorization data that is not too big
* (for example, the authorization data for a personal blog system).
......
......@@ -30,4 +30,14 @@ class Category extends ActiveRecord
return $this->hasMany(Item::className(), ['category_id' => 'id'])
->onCondition(['item.id' => [1, 2, 3]]);
}
public function getOrderItems()
{
return $this->hasMany(OrderItem::className(), ['item_id' => 'id'])->via('items');
}
public function getOrders()
{
return $this->hasMany(Order::className(), ['id' => 'order_id'])->via('orderItems');
}
}
......@@ -176,6 +176,34 @@ class ActiveRecordTest extends DatabaseTestCase
$this->assertEquals(2, $items[1]->id);
}
/**
* https://github.com/yiisoft/yii2/issues/5341
*
* Issue: Plan 1 -- * Account * -- * User
* Our Tests: Category 1 -- * Item * -- * Order
*/
public function testDeeplyNestedTableRelation2()
{
/* @var $category Category */
$category = Category::findOne(1);
$this->assertNotNull($category);
$orders = $category->orders;
$this->assertEquals(2, count($orders));
$this->assertInstanceOf(Order::className(), $orders[0]);
$this->assertInstanceOf(Order::className(), $orders[1]);
$ids = [$orders[0]->id, $orders[1]->id];
sort($ids);
$this->assertEquals([1, 3], $ids);
$category = Category::findOne(2);
$this->assertNotNull($category);
$orders = $category->orders;
$this->assertEquals(1, count($orders));
$this->assertInstanceOf(Order::className(), $orders[0]);
$this->assertEquals(2, $orders[0]->id);
}
public function testStoreNull()
{
$record = new NullValues();
......
......@@ -2,7 +2,9 @@
namespace yiiunit\framework\i18n;
use NumberFormatter;
use yii\i18n\Formatter;
use Yii;
use yiiunit\TestCase;
use DateTime;
use DateInterval;
......@@ -575,9 +577,49 @@ class FormatterTest extends TestCase
// number format
/**
* Provides some configuration that should not affect Integer formatter
*/
public function differentConfigProvider()
{
// make this test not break when intl is not installed
if (!extension_loaded('intl')) {
return [];
}
public function testIntlAsInteger()
return [
[[
'numberFormatterOptions' => [
NumberFormatter::MIN_FRACTION_DIGITS => 2,
],
]],
[[
'numberFormatterOptions' => [
NumberFormatter::MAX_FRACTION_DIGITS => 2,
],
]],
[[
'numberFormatterOptions' => [
NumberFormatter::FRACTION_DIGITS => 2,
],
]],
[[
'numberFormatterOptions' => [
NumberFormatter::MIN_FRACTION_DIGITS => 2,
NumberFormatter::MAX_FRACTION_DIGITS => 4,
],
]],
];
}
/**
* @dataProvider differentConfigProvider
*/
public function testIntlAsInteger($config)
{
// configure formatter with different configs that should not affect integer format
Yii::configure($this->formatter, $config);
$this->testAsInteger();
}
......
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