Skip to content

Commit

Permalink
Merge branch 'master' into patch-2
Browse files Browse the repository at this point in the history
  • Loading branch information
WinterSilence authored Apr 15, 2022
2 parents 70fedcd + 4f1ffd2 commit 10d23ed
Show file tree
Hide file tree
Showing 186 changed files with 815 additions and 605 deletions.
1 change: 1 addition & 0 deletions build/controllers/MimeTypeController.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ class MimeTypeController extends Controller
* @var array MIME type aliases
*/
private $aliases = [
'text/rtf' => 'application/rtf',
'text/xml' => 'application/xml',
'image/svg' => 'image/svg+xml',
'image/x-bmp' => 'image/bmp',
Expand Down
10 changes: 8 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,14 @@
},
"autoload": {
"psr-4": {
"yii\\": "framework/",
"yii\\cs\\": "cs/src/"
"yii\\": "framework/"
}
},
"autoload-dev": {
"psr-4": {
"yii\\cs\\": "cs/src/",
"yii\\build\\": "build/",
"yiiunit\\": "tests/"
}
},
"config": {
Expand Down
16 changes: 8 additions & 8 deletions docs/guide-ru/db-active-record.md
Original file line number Diff line number Diff line change
Expand Up @@ -875,14 +875,14 @@ SQL-выражения. Для принудительного повторног
операции: `unset($customer->orders)`.

> Note: Несмотря на то, что эта концепция выглядит похожей на концепцию [свойств объектов](concept-properties.md),
между ними есть важное различие. Для обычных свойств объектов значения свойств имеют тот же тип, который возвращает
геттер. Однако метод получения связных данных возвращает объект [[yii\db\ActiveQuery]], в то время как доступ к
свойству связи возвращает объект [[yii\db\ActiveRecord]] или массив таких объектов.
```php
$customer->orders; // массив объектов `Order`
$customer->getOrders(); // объект ActiveQuery
```
Это полезно при тонкой настройке запросов к связным данным, что будет описано в следующем разделе.
> между ними есть важное различие. Для обычных свойств объектов значения свойств имеют тот же тип, который возвращает
> геттер. Однако метод получения связных данных возвращает объект [[yii\db\ActiveQuery]], в то время как доступ к
> свойству связи возвращает объект [[yii\db\ActiveRecord]] или массив таких объектов.
> ```php
> $customer->orders; // массив объектов `Order`
> $customer->getOrders(); // объект ActiveQuery
> ```
> Это полезно при тонкой настройке запросов к связным данным, что будет описано в следующем разделе.
### Динамические запросы связных данных <span id="dynamic-relational-query"></span>
Expand Down
1 change: 1 addition & 0 deletions docs/guide-ru/rest-resources.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ class User extends ActiveRecord implements Linkable
```

При отправке ответа объект `User` содержит поле `_links`, значение которого — ссылки, связанные с объектом:

```
{
"id": 100,
Expand Down
1 change: 1 addition & 0 deletions docs/guide-ru/security-cryptography.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ $data = Yii::$app->getSecurity()->decryptByPassword($encryptedData, $secretKey);
Есть ситуации, в которых вам нужно убедиться, что ваши данные не были изменены третьей стороной или даже повреждены каким-либо образом. Yii обеспечивает простой способ для подтверждения целостности данных в виде двух вспомогательных функций.

Префикс данных генерируются из секретного ключа и данных:

```php
// $secretKey нашего приложения или пользователя, $genuineData полученые из надежного источника
$data = Yii::$app->getSecurity()->hashData($genuineData, $secretKey);
Expand Down
39 changes: 25 additions & 14 deletions docs/guide/input-tabular-input.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,6 @@ Let's start with the controller action:

namespace app\controllers;

use Yii;
use yii\base\Model;
use yii\web\Controller;
use app\models\Setting;

Expand All @@ -43,11 +41,13 @@ class SettingsController extends Controller
{
$settings = Setting::find()->indexBy('id')->all();

if (Model::loadMultiple($settings, Yii::$app->request->post()) && Model::validateMultiple($settings)) {
foreach ($settings as $setting) {
$setting->save(false);
if ($this->request->isPost) {
if (Setting::loadMultiple($settings, $this->request->post()) && Setting::validateMultiple($settings)) {
foreach ($settings as $setting) {
$setting->save(false);
}
return $this->redirect('index');
}
return $this->redirect('index');
}

return $this->render('update', ['settings' => $settings]);
Expand All @@ -71,10 +71,12 @@ use yii\widgets\ActiveForm;

$form = ActiveForm::begin();

foreach ($settings as $index => $setting) {
echo $form->field($setting, "[$index]value")->label($setting->name);
foreach ($settings as $id => $setting) {
echo $form->field($setting, "[$id]value")->label($setting->name);
}

echo Html::submitButton('Save');

ActiveForm::end();
```

Expand All @@ -88,20 +90,29 @@ Creating new records is similar to updating, except the part, where we instantia
```php
public function actionCreate()
{
$count = count(Yii::$app->request->post('Setting', []));
$settings = [new Setting()];
for($i = 1; $i < $count; $i++) {
$settings[] = new Setting();
$settings = [];
if ($this->request->isPost) {
$count = count($this->request->post($setting->tableName())) - 1;
for ($i = 0; $i < $count; $i++) {
$settings[$i] = new Setting();
}
if (Setting::loadMultiple($settings, $this->request->post()) && Setting::validateMultiple($settings)) {
foreach ($settings as $setting) {
$setting->save(false);
}
return $this->redirect('index');
}
}
$settings[] = new Setting();

// ...
return $this->render('create', ['settings' => $settings]);
}
```

Here we create an initial `$settings` array containing one model by default so that always at least one text field will be
visible in the view. Additionally we add more models for each line of input we may have received.

In the view you can use javascript to add new input lines dynamically.
In the view you can use JavaScript to add new input lines dynamically.

### Combining Update, Create and Delete on one page

Expand Down
6 changes: 3 additions & 3 deletions framework/BaseYii.php
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ public static function getRootAlias($alias)
* @param string $alias the alias name (e.g. "@yii"). It must start with a '@' character.
* It may contain the forward-slash '/' which serves as a boundary character when performing
* alias translation by [[getAlias()]].
* @param string $path the path corresponding to the alias. If this is null, the alias will
* @param string|null $path the path corresponding to the alias. If this is null, the alias will
* be removed. Trailing '/' and '\' characters will be trimmed. This can be
*
* - a directory or a file path (e.g. `/tmp`, `/tmp/main.txt`)
Expand Down Expand Up @@ -384,7 +384,7 @@ public static function getLogger()

/**
* Sets the logger object.
* @param Logger $logger the logger object.
* @param Logger|null $logger the logger object.
*/
public static function setLogger($logger)
{
Expand Down Expand Up @@ -528,7 +528,7 @@ public static function powered()
* @param string $category the message category.
* @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 string $language the language code (e.g. `en-US`, `en`). If this is null, the current
* @param string|null $language the language code (e.g. `en-US`, `en`). If this is null, the current
* [[\yii\base\Application::language|application language]] will be used.
* @return string the translated message.
*/
Expand Down
11 changes: 11 additions & 0 deletions framework/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,24 @@ Yii Framework 2 Change Log
2.0.46 under development
------------------------

- Bug #19349: Fix PHP 8.1 error when attribute and label of `yii\grid\DataColumn` are empty (githubjeka)
- Bug #19243: Handle `finfo_open` for tar.xz as `application/octet-stream` on PHP 8.1 (longthanhtran)
- Bug #19235: Fix return type compatibility of `yii\web\SessionIterator` class methods for PHP 8.1 (virtual-designer)
- Bug #19256: Pass missed `$view` to user's callback in `yii\validators\InlineValidator::clientValidateAttribute()` (WinterSilence)
- Enh #19270: Replace deprecated `scss` converter in `yii\web\AssetConverter::$commands` (WinterSilence)
- Enh #19254: Support specifying custom characters for `yii.validation.trim()` and replace deprecated `jQuery.trim()` (WinterSilence)
- Bug #19291: Reset errors and validators in `yii\base\Model::__clone()` (WinterSilence)
- Enh #19295: Added alias `text/rtf` for mime-type `application/rtf` (lesha724)
- Enh #19308: Add `yii\web\UploadedFile::$fullPath` represents 'full_path' key added in PHP 8.1 (WinterSilence)
- Bug #19303: Fix serialization in `yii\caching\Dependency::generateReusableHash()` (WinterSilence)
- Enh #19304: Add filtering validator `yii\validators\TrimValidator` (WinterSilence)
- Enh #19309: Optimize `yii\base\Model::attributes()` (WinterSilence)
- Bug #19322: Revert force setting value to empty string in case it's `null` in `yii\validators\FilterValidator::validateAttribute()` (bizley)
- Bug #19324: Fix `yii\helpers\BaseHtml::renderSelectOptions()` giving wrong selection for boolean attributes (adnandautovic)
- Bug #19329: Fix `yii\web\GroupUrlRule` to properly normalize prefix (bizley)
- Bug #19328: Passing null to parameter #1 ($string) of type string is deprecated in `yii\db\oci\Schema` (Arkeins)
- Bug #19237: Fix OCI PHP 8.1 passing `null` to trim() (longthanhtran)
- Bug #19312: Fix PHP 8.1 error when passing null to `yii\helpers\BaseInflector` (WinterSilence)


2.0.45 February 11, 2022
Expand Down
35 changes: 32 additions & 3 deletions framework/assets/yii.validation.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ yii.validation = (function ($) {
var valid = false;
if (options.requiredValue === undefined) {
var isString = typeof value == 'string' || value instanceof String;
if (options.strict && value !== undefined || !options.strict && !pub.isEmpty(isString ? $.trim(value) : value)) {
if (options.strict && value !== undefined || !options.strict && !pub.isEmpty(isString ? trimString(value) : value)) {
valid = true;
}
} else if (!options.strict && value == options.requiredValue || options.strict && value === options.requiredValue) {
Expand Down Expand Up @@ -243,8 +243,17 @@ yii.validation = (function ($) {
}

value = $input.val();
if (!options.skipOnEmpty || !pub.isEmpty(value)) {
value = $.trim(value);
if (
(!options.skipOnEmpty || !pub.isEmpty(value))
&& (!options.skipOnArray || !Array.isArray(value))
) {
if (Array.isArray(value)) {
for (var i = 0; i < value.length; i++) {
value[i] = trimString(value[i], options);
}
} else {
value = trimString(value, options);
}
$input.val(value);
}

Expand Down Expand Up @@ -467,5 +476,25 @@ yii.validation = (function ($) {
}
}

/**
* PHP: `trim($path, ' /')`, JS: `yii.helpers.trim(path, {chars: ' /'})`
*/
function trimString(value, options = {skipOnEmpty: true, chars: null}) {
if (options.skipOnEmpty !== false && pub.isEmpty(value)) {
return value;
}

value = new String(value);
if (options.chars || !String.prototype.trim) {
var chars = !options.chars
? ' \\s\xA0'
: options.chars.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\$1');

return value.replace(new RegExp('^[' + chars + ']+|[' + chars + ']+$', 'g'), '');
}

return value.trim();
}

return pub;
})(jQuery);
8 changes: 4 additions & 4 deletions framework/base/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -126,15 +126,15 @@ abstract class Application extends Module
*/
public $requestedRoute;
/**
* @var Action the requested Action. If null, it means the request cannot be resolved into an action.
* @var Action|null the requested Action. If null, it means the request cannot be resolved into an action.
*/
public $requestedAction;
/**
* @var array the parameters supplied to the requested action.
*/
public $requestedParams;
/**
* @var array list of installed Yii extensions. Each array element represents a single extension
* @var array|null list of installed Yii extensions. Each array element represents a single extension
* with the following structure:
*
* ```php
Expand Down Expand Up @@ -517,7 +517,7 @@ public function getErrorHandler()

/**
* Returns the cache component.
* @return \yii\caching\CacheInterface the cache application component. Null if the component is not enabled.
* @return \yii\caching\CacheInterface|null the cache application component. Null if the component is not enabled.
*/
public function getCache()
{
Expand Down Expand Up @@ -643,7 +643,7 @@ public function coreComponents()
* This method replaces the `exit()` function by ensuring the application life cycle is completed
* before terminating the application.
* @param int $status the exit status (value 0 means normal exit while other values mean abnormal exit).
* @param Response $response the response to be sent. If not set, the default application [[response]] component will be used.
* @param Response|null $response the response to be sent. If not set, the default application [[response]] component will be used.
* @throws ExitException if the application is in testing mode
*/
public function end($status = 0, $response = null)
Expand Down
6 changes: 3 additions & 3 deletions framework/base/Component.php
Original file line number Diff line number Diff line change
Expand Up @@ -544,7 +544,7 @@ public function on($name, $handler, $data = null, $append = true)
* wildcard will be removed, while handlers registered with plain names matching this wildcard will remain.
*
* @param string $name event name
* @param callable $handler the event handler to be removed.
* @param callable|null $handler the event handler to be removed.
* If it is null, all handlers attached to the named event will be removed.
* @return bool if a handler is found and detached
* @see on()
Expand Down Expand Up @@ -645,7 +645,7 @@ public function trigger($name, Event $event = null)
/**
* Returns the named behavior object.
* @param string $name the behavior name
* @return null|Behavior the behavior object, or null if the behavior does not exist
* @return Behavior|null the behavior object, or null if the behavior does not exist
*/
public function getBehavior($name)
{
Expand Down Expand Up @@ -703,7 +703,7 @@ public function attachBehaviors($behaviors)
* Detaches a behavior from the component.
* The behavior's [[Behavior::detach()]] method will be invoked.
* @param string $name the behavior's name.
* @return null|Behavior the detached behavior. Null if the behavior does not exist.
* @return Behavior|null the detached behavior. Null if the behavior does not exist.
*/
public function detachBehavior($name)
{
Expand Down
2 changes: 1 addition & 1 deletion framework/base/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ class Controller extends Component implements ViewContextInterface
*/
public $defaultAction = 'index';
/**
* @var null|string|false the name of the layout to be applied to this controller's views.
* @var string|null|false the name of the layout to be applied to this controller's views.
* This property mainly affects the behavior of [[render()]].
* Defaults to null, meaning the actual layout value should inherit that from [[module]]'s layout value.
* If false, no layout will be applied.
Expand Down
2 changes: 1 addition & 1 deletion framework/base/ErrorException.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ class ErrorException extends \ErrorException
* @param int $severity [optional]
* @param string $filename [optional]
* @param int $lineno [optional]
* @param \Throwable|\Exception $previous [optional]
* @param \Throwable|null $previous [optional]
*/
public function __construct($message = '', $code = 0, $severity = 1, $filename = __FILE__, $lineno = __LINE__, $previous = null)
{
Expand Down
Loading

0 comments on commit 10d23ed

Please sign in to comment.