From d4d80ed3120a28e7808e35f1cfa583ace5cea0bb Mon Sep 17 00:00:00 2001 From: Ivan Date: Mon, 24 Apr 2017 21:50:37 +0300 Subject: [PATCH 01/22] Add setup for Apache Describes the settings for Apache. --- docs/guide-ru/test-environment-setup.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/docs/guide-ru/test-environment-setup.md b/docs/guide-ru/test-environment-setup.md index 84311969c4..09ac6cd69e 100644 --- a/docs/guide-ru/test-environment-setup.md +++ b/docs/guide-ru/test-environment-setup.md @@ -47,3 +47,25 @@ Changed current directory to путём запуска команды `codecept` без указания пути. Тем не менее, данный подход может не подойти. К примеру, в двух разных проектах может потребоваться установить разные версии Codeception. Для простоты все команды в разделах про тестирование используются так, будто Codeception установлен глобально. + +### Настройка веб сервера Apache + +Если вы использутете Apache и настроили его как описано в разделе «[Установк Yii](start-installation.md)», то для тестов вам необходимо создать отдельнвй виртуальный хост который будет работать с той же папкой, но использовать входной скрипт index-test.php: +``` + + DocumentRoot "path/to/basic/webb" + ServerName mysite-test + + Order Allow,Deny + Allow from all + AddDefaultCharset utf-8 + DirectoryIndex index-test.php + RewriteEngine on + RewriteCond %{REQUEST_FILENAME} !-f + RewriteCond %{REQUEST_FILENAME} !-d + RewriteRule . index-test.php + + +``` +Так мы укажем веб серверу перенаправлять все запросы на скрипт index-test.php. +> Note: Обратите внимание, что здесь мы указываем параметр DirectoryIndex, помимо тех параметров, которые были указаны для первого хоста. Это сделано с той целью, чтобы при обращении к главной странице по адресу mysite-test также использовался бы скрипт index-test.php. From 918aee784ef30be88dbfbef0bc90fca544e31fec Mon Sep 17 00:00:00 2001 From: Dmitry Naumenko Date: Tue, 25 Apr 2017 07:54:55 +0300 Subject: [PATCH 02/22] Fixed spelling and typos --- docs/guide-ru/test-environment-setup.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/guide-ru/test-environment-setup.md b/docs/guide-ru/test-environment-setup.md index 09ac6cd69e..bc537476cf 100644 --- a/docs/guide-ru/test-environment-setup.md +++ b/docs/guide-ru/test-environment-setup.md @@ -48,9 +48,9 @@ Changed current directory to разных проектах может потребоваться установить разные версии Codeception. Для простоты все команды в разделах про тестирование используются так, будто Codeception установлен глобально. -### Настройка веб сервера Apache +### Настройка веб-сервера Apache -Если вы использутете Apache и настроили его как описано в разделе «[Установк Yii](start-installation.md)», то для тестов вам необходимо создать отдельнвй виртуальный хост который будет работать с той же папкой, но использовать входной скрипт index-test.php: +Если вы используете Apache и настроили его как описано в разделе «[Установка Yii](start-installation.md)», то для тестов вам необходимо создать отдельный виртуальный хост который будет работать с той же папкой, но использовать входной скрипт `index-test.php`: ``` DocumentRoot "path/to/basic/webb" @@ -67,5 +67,5 @@ Changed current directory to ``` -Так мы укажем веб серверу перенаправлять все запросы на скрипт index-test.php. -> Note: Обратите внимание, что здесь мы указываем параметр DirectoryIndex, помимо тех параметров, которые были указаны для первого хоста. Это сделано с той целью, чтобы при обращении к главной странице по адресу mysite-test также использовался бы скрипт index-test.php. +Так мы укажем веб серверу перенаправлять все запросы на скрипт `index-test.php`. +> Note: Обратите внимание, что здесь мы указываем параметр `DirectoryIndex`, помимо тех параметров, которые были указаны для первого хоста. Это сделано с той целью, чтобы при обращении к главной странице по адресу `mysite-test` также использовался бы скрипт `index-test.php`. From 6ce6385094f4830b2d66a7b731584db3e7edcc73 Mon Sep 17 00:00:00 2001 From: depesr Date: Tue, 25 Apr 2017 09:45:29 +0200 Subject: [PATCH 03/22] Updated slovak localization Fixed missing translation for '{attribute} must be an integer.' string --- framework/messages/sk/yii.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/framework/messages/sk/yii.php b/framework/messages/sk/yii.php index ac2269b530..ef89a0f5db 100644 --- a/framework/messages/sk/yii.php +++ b/framework/messages/sk/yii.php @@ -79,7 +79,7 @@ return [ '{attribute} must be a string.' => '{attribute} musí byť reťazec.', '{attribute} must be a valid IP address.' => '{attribute} musí byť platná IP adresa.', '{attribute} must be an IP address with specified subnet.' => '{attribute} musí byť IP adresa so špecifikovanou podsieťou.', - '{attribute} must be an integer.' => '{attribute} musí byť integer.', + '{attribute} must be an integer.' => '{attribute} musí byť celé číslo.', '{attribute} must be either "{true}" or "{false}".' => '{attribute} musí byť "{true}" alebo "{false}".', '{attribute} must be equal to "{compareValueOrAttribute}".' => '{attribute} musí byť "{compareValueOrAttribute}".', '{attribute} must be greater than "{compareValueOrAttribute}".' => '{attribute} musí byť väčšie ako "{compareValueOrAttribute}".', From 98871123c9765896e181788c2ea653681e92782d Mon Sep 17 00:00:00 2001 From: Sam Mousa Date: Tue, 25 Apr 2017 10:54:18 +0200 Subject: [PATCH 04/22] Fixed ignored params when using count in `SqlDataProvider` --- framework/data/SqlDataProvider.php | 5 ++++- tests/framework/data/SqlDataProviderTest.php | 12 ++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/framework/data/SqlDataProvider.php b/framework/data/SqlDataProvider.php index e0062ba4df..0b894d355e 100644 --- a/framework/data/SqlDataProvider.php +++ b/framework/data/SqlDataProvider.php @@ -163,6 +163,9 @@ class SqlDataProvider extends BaseDataProvider */ protected function prepareTotalCount() { - return (new Query())->from(['sub' => "({$this->sql})"])->count('*', $this->db); + return (new Query([ + 'from' => ['sub' => "({$this->sql})"], + 'params' => $this->params + ]))->count('*', $this->db); } } diff --git a/tests/framework/data/SqlDataProviderTest.php b/tests/framework/data/SqlDataProviderTest.php index 0be1882549..d5edc47341 100644 --- a/tests/framework/data/SqlDataProviderTest.php +++ b/tests/framework/data/SqlDataProviderTest.php @@ -32,4 +32,16 @@ class SqlDataProviderTest extends DatabaseTestCase ]); $this->assertEquals(3, $dataProvider->getTotalCount()); } + + public function testTotalCountWithParams() + { + $dataProvider = new SqlDataProvider([ + 'sql' => 'select * from `customer` where id > :minimum', + 'params' => [ + ':minimum' => -1 + ], + 'db' => $this->getConnection(), + ]); + $this->assertEquals(3, $dataProvider->getTotalCount()); + } } From 4af62a6bd76e30c6771c3201d64c942b1f0b5e97 Mon Sep 17 00:00:00 2001 From: Carsten Brandt Date: Tue, 25 Apr 2017 23:02:19 +0200 Subject: [PATCH 05/22] improve session PHPdoc --- framework/web/Session.php | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/framework/web/Session.php b/framework/web/Session.php index d658064efe..588c29f9fb 100644 --- a/framework/web/Session.php +++ b/framework/web/Session.php @@ -190,6 +190,11 @@ class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Co /** * Frees all session variables and destroys all data registered to a session. + * + * This method has no effect when session is not [[getIsActive()|active]]. + * Make sure to call [[open()]] before calling it. + * @see open() + * @see isActive */ public function destroy() { @@ -270,9 +275,16 @@ class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Co } /** - * Updates the current session ID with a newly generated one . + * Updates the current session ID with a newly generated one. + * * Please refer to for more details. + * + * This method has no effect when session is not [[getIsActive()|active]]. + * Make sure to call [[open()]] before calling it. + * * @param bool $deleteOldSession Whether to delete the old associated session file or not. + * @see open() + * @see isActive */ public function regenerateID($deleteOldSession = false) { From 339c7663eb921982df35a65403eeac737cdb8b56 Mon Sep 17 00:00:00 2001 From: sasha-ch Date: Thu, 26 Jan 2017 17:16:38 +0300 Subject: [PATCH 06/22] Fixes #10346: Fixed "DOMException: Invalid Character Error" in `yii\web\XmlResponseFormatter::buildXml()` --- framework/CHANGELOG.md | 1 + framework/web/XmlResponseFormatter.php | 40 ++++++++++++++++++- .../web/XmlResponseFormatterTest.php | 10 +++++ 3 files changed, 49 insertions(+), 2 deletions(-) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 20eb6f5356..961099f82b 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -4,6 +4,7 @@ Yii Framework 2 Change Log 2.0.12 under development -------------------------- +- Bug #10346: Fixed "DOMException: Invalid Character Error" in `yii\web\XmlResponseFormatter::buildXml()` (sasha-ch) - Bug #13694: `yii\widgets\Pjax` now sends `X-Pjax-Url` header with response to fix redirect (wleona3, Faryshta) - Bug #14012: `yii\db\pgsql\Schema::findViewNames()` was skipping materialized views (insolita) - Bug #13362: Fixed return value of `yii\caching\MemCache::setValues()` (masterklavi) diff --git a/framework/web/XmlResponseFormatter.php b/framework/web/XmlResponseFormatter.php index 441a522a71..fadf5bb499 100644 --- a/framework/web/XmlResponseFormatter.php +++ b/framework/web/XmlResponseFormatter.php @@ -10,6 +10,7 @@ namespace yii\web; use DOMDocument; use DOMElement; use DOMText; +use DOMException; use yii\base\Arrayable; use yii\base\Component; use yii\helpers\StringHelper; @@ -94,11 +95,11 @@ class XmlResponseFormatter extends Component implements ResponseFormatterInterfa if (is_int($name) && is_object($value)) { $this->buildXml($element, $value); } elseif (is_array($value) || is_object($value)) { - $child = new DOMElement(is_int($name) ? $this->itemTag : $name); + $child = new DOMElement($this->getValidXmlElementName($name)); $element->appendChild($child); $this->buildXml($child, $value); } else { - $child = new DOMElement(is_int($name) ? $this->itemTag : $name); + $child = new DOMElement($this->getValidXmlElementName($name)); $element->appendChild($child); $child->appendChild(new DOMText($this->formatScalarValue($value))); } @@ -143,4 +144,39 @@ class XmlResponseFormatter extends Component implements ResponseFormatterInterfa return (string) $value; } + + /** + * Returns element name ready to be used in DOMElement if + * name is not empty, is not int and is valid. + * + * Falls back to [[itemTag]] otherwise. + * + * @param mixed $name + * @return string + * @since 2.0.12 + */ + protected function getValidXmlElementName($name) + { + if (empty($name) || is_int($name) || !$this->isValidXmlName($name)) { + return $this->itemTag; + } + return $name; + } + + /** + * Checks if name is valid to be used in XML + * + * @param mixed $name + * @return bool + * @see http://stackoverflow.com/questions/2519845/how-to-check-if-string-is-a-valid-xml-element-name/2519943#2519943 + */ + protected function isValidXmlName($name) + { + try { + new DOMElement($name); + return true; + } catch (DOMException $e) { + return false; + } + } } diff --git a/tests/framework/web/XmlResponseFormatterTest.php b/tests/framework/web/XmlResponseFormatterTest.php index 519d96cf43..046f2bbf18 100644 --- a/tests/framework/web/XmlResponseFormatterTest.php +++ b/tests/framework/web/XmlResponseFormatterTest.php @@ -69,6 +69,16 @@ class XmlResponseFormatterTest extends FormatterTest 'c' => [2, '<>'], false, ], "1abc2<>false\n"], + + // Checks if empty keys and keys not valid in XML are processed. + // See https://github.com/yiisoft/yii2/pull/10346/ + [[ + '' => 1, + '2015-06-18' => '2015-06-18', + 'b:c' => 'b:c', + 'a b c' => 'a b c', + 'äøñ' => 'äøñ' + ], "12015-06-18b:ca b c<äøñ>äøñ\n"], ]); } From 3598f8180ce72e9e8048634e2105068081ac8b47 Mon Sep 17 00:00:00 2001 From: Paul Klimov Date: Wed, 26 Apr 2017 02:29:10 +0300 Subject: [PATCH 07/22] Fixes #13087: Fixed getting active validators for safe attribute --- framework/CHANGELOG.md | 2 +- framework/validators/Validator.php | 24 ++++---------------- tests/framework/validators/ValidatorTest.php | 16 ++++++++++--- 3 files changed, 19 insertions(+), 23 deletions(-) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 961099f82b..6c51715193 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -14,7 +14,7 @@ Yii Framework 2 Change Log - Bug #13671: Fixed error handler trace to work correctly with XDebug (samdark) - Bug #13657: Fixed `yii\helpers\StringHelper::truncateHtml()` skip extra tags at the end (sam002) - Bug #7946: Fixed a bug when the `form` attribute was not propagated to the hidden input of the checkbox (Kolyunya) -- Bug #13087: Fixed getting active validators for safe attribute (developeruz) +- Bug #13087: Fixed getting active validators for safe attribute (developeruz, klimov-paul) - Bug #13571: Fix `yii\db\mssql\QueryBuilder::checkIntegrity` for all tables (boboldehampsink) - Bug #11230: Include `defaultRoles` in `yii\rbac\DbManager->getRolesByUser()` results (developeruz) - Enh #13243: Added support for unicode attribute names in `yii\widgets\DetailView` (arogachev) diff --git a/framework/validators/Validator.php b/framework/validators/Validator.php index f6543807f9..2915d310c4 100644 --- a/framework/validators/Validator.php +++ b/framework/validators/Validator.php @@ -47,6 +47,8 @@ use yii\base\NotSupportedException; * - `ip`: [[IpValidator]] * * For more details and usage information on Validator, see the [guide article on validators](guide:input-validation). + * + * @property array $attributeNames cleaned attribute names without the `!` character at the beginning. This property is read-only. * * @author Qiang Xue * @since 2.0 @@ -101,11 +103,6 @@ class Validator extends Component * please specify them as an array; for single attribute, you may use either a string or an array. */ public $attributes = []; - /** - * @var array cleaned attribute names. Contains attribute names without `!` character at the beginning - * @since 2.0.12 - */ - private $_attributeNames = []; /** * @var string the user-defined error message. It may contain the following placeholders which * will be replaced accordingly by the validator: @@ -238,7 +235,6 @@ class Validator extends Component $this->attributes = (array) $this->attributes; $this->on = (array) $this->on; $this->except = (array) $this->except; - $this->setAttributeNames((array)$this->attributes); } /** @@ -459,23 +455,13 @@ class Validator extends Component /** * Returns cleaned attribute names without the `!` character at the beginning - * @return array + * @return array attribute names. * @since 2.0.12 */ public function getAttributeNames() { - return $this->_attributeNames; - } - - /** - * Saves attribute names without `!` character at the beginning - * @param array $attributeNames - * @since 2.0.12 - */ - private function setAttributeNames($attributeNames) - { - $this->_attributeNames = array_map(function($attribute) { + return array_map(function($attribute) { return ltrim($attribute, '!'); - }, $attributeNames); + }, $this->attributes); } } diff --git a/tests/framework/validators/ValidatorTest.php b/tests/framework/validators/ValidatorTest.php index eb3ab05422..0921076fb4 100644 --- a/tests/framework/validators/ValidatorTest.php +++ b/tests/framework/validators/ValidatorTest.php @@ -240,17 +240,27 @@ class ValidatorTest extends TestCase $this->assertEquals('attr_msg_val::abc::param_value', $errors[0]); } + public function testGetAttributeNames() + { + $validator = new TestValidator(); + $validator->attributes = ['id', 'name', '!email']; + $this->assertEquals(['id', 'name', 'email'], $validator->getAttributeNames()); + } + + /** + * @depends testGetAttributeNames + */ public function testGetActiveValidatorsForSafeAttributes() { $model = $this->getTestModel(); $validators = $model->getActiveValidators('safe_attr'); - $is_found = false; + $isFound = false; foreach ($validators as $v) { if ($v instanceof NumberValidator) { - $is_found = true; + $isFound = true; break; } } - $this->assertTrue($is_found); + $this->assertTrue($isFound); } } From 385eb8804878404bb023bd44c4e75d5cf28f7805 Mon Sep 17 00:00:00 2001 From: Leandro Guindani Gehlen Date: Wed, 26 Apr 2017 01:28:52 +0200 Subject: [PATCH 08/22] Added `yii\data\Sort::parseSortParams` allowing customize other params request formats in descendant class. close #13170 --- framework/CHANGELOG.md | 1 + framework/data/Sort.php | 31 ++++++++++++++++++++++++++++-- tests/framework/data/SortTest.php | 32 +++++++++++++++++++++++++++++++ 3 files changed, 62 insertions(+), 2 deletions(-) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 6c51715193..1101a59c23 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -34,6 +34,7 @@ Yii Framework 2 Change Log - Bug #8120: Fixes LIKE special characters escaping for Cubrid/MSSQL/Oracle/SQLite in `yii\db\QueryBuilder` (sergeymakinen) - Bug #12715: Exception `SAVEPOINT LEVEL1 does not exist` instead of deadlock exception (Vovan-VE) - Enh #8641: Enhanced `yii\console\Request::resolve()` to prevent passing parameters, that begin from digits (silverfire) +- Enh #13179: Added `yii\data\Sort::parseSortParam` allowing to customize sort param in descendant class (leandrogehlen) - Enh #13278: `yii\caching\DbQueryDependency` created allowing specification of the cache dependency via `yii\db\QueryInterface` (klimov-paul) - Enh #13467: `yii\data\ActiveDataProvider` no longer queries models if models count is zero (kLkA, Kolyunya) - Enh #13523: Plural rule for pasta (developeruz) diff --git a/framework/data/Sort.php b/framework/data/Sort.php index 6049af4ea4..30185dbe14 100644 --- a/framework/data/Sort.php +++ b/framework/data/Sort.php @@ -243,8 +243,8 @@ class Sort extends Object $request = Yii::$app->getRequest(); $params = $request instanceof Request ? $request->getQueryParams() : []; } - if (isset($params[$this->sortParam]) && is_scalar($params[$this->sortParam])) { - $attributes = explode($this->separator, $params[$this->sortParam]); + if (isset($params[$this->sortParam])) { + $attributes = $this->parseSortParam($params[$this->sortParam]); foreach ($attributes as $attribute) { $descending = false; if (strncmp($attribute, '-', 1) === 0) { @@ -268,6 +268,33 @@ class Sort extends Object return $this->_attributeOrders; } + /** + * Parses the value of [[sortParam]] into an array of sort attributes. + * + * The format must be the attribute name only for ascending + * or the attribute name prefixed with `-` for descending. + * + * For example the following return value will result in ascending sort by + * `category` and descending sort by `created_at`: + * + * ```php + * [ + * 'category', + * '-created_at' + * ] + * ``` + * + * @param string $param the value of the [[sortParam]]. + * @return array the valid sort attributes. + * @since 2.0.12 + * @see $separator for the attribute name separator. + * @see $sortParam + */ + protected function parseSortParam($param) + { + return is_scalar($param) ? explode($this->separator, $param) : []; + } + /** * Sets up the currently sort information. * @param array|null $attributeOrders sort directions indexed by attribute names. diff --git a/tests/framework/data/SortTest.php b/tests/framework/data/SortTest.php index d0fd5056ce..31fe3256a7 100644 --- a/tests/framework/data/SortTest.php +++ b/tests/framework/data/SortTest.php @@ -225,4 +225,36 @@ class SortTest extends TestCase $this->assertEquals('Age', $sort->link('age')); } + + public function testParseSortParam() + { + $sort = new CustomSort([ + 'attributes' => [ + 'age', + 'name' + ], + 'params' => [ + 'sort' => [ + ['field' => 'age', 'dir' => 'asc'], + ['field' => 'name', 'dir' => 'desc'] + ] + ], + 'enableMultiSort' => true + ]); + + $this->assertEquals(SORT_ASC, $sort->getAttributeOrder('age')); + $this->assertEquals(SORT_DESC, $sort->getAttributeOrder('name')); + } +} + +class CustomSort extends Sort +{ + protected function parseSortParam($params) + { + $attributes = []; + foreach ($params as $item) { + $attributes[] = ($item['dir'] == 'desc') ? '-' . $item['field'] : $item['field']; + } + return $attributes; + } } From 70dc2fa33b33fafcd30cc9ac9747645b5d5b91f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C3=ABl=20Arnauts?= Date: Fri, 3 Feb 2017 11:29:44 +0100 Subject: [PATCH 09/22] Fixes #11719: Fixed `yii\db\Connection::$enableQueryCache` caused infinite loop when the same connection was used for `yii\caching\DbCache` --- framework/CHANGELOG.md | 1 + framework/caching/DbCache.php | 37 +++++++++++++++++++++-------------- 2 files changed, 23 insertions(+), 15 deletions(-) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 1101a59c23..50b23aee01 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -4,6 +4,7 @@ Yii Framework 2 Change Log 2.0.12 under development -------------------------- +- Bug #11719: Fixed `yii\db\Connection::$enableQueryCache` caused infinite loop when the same connection was used for `yii\caching\DbCache` (michaelarnauts) - Bug #10346: Fixed "DOMException: Invalid Character Error" in `yii\web\XmlResponseFormatter::buildXml()` (sasha-ch) - Bug #13694: `yii\widgets\Pjax` now sends `X-Pjax-Url` header with response to fix redirect (wleona3, Faryshta) - Bug #14012: `yii\db\pgsql\Schema::findViewNames()` was skipping materialized views (insolita) diff --git a/framework/caching/DbCache.php b/framework/caching/DbCache.php index cecc8d6360..a57bd48880 100644 --- a/framework/caching/DbCache.php +++ b/framework/caching/DbCache.php @@ -187,13 +187,16 @@ class DbCache extends Cache */ protected function setValue($key, $value, $duration) { - $command = $this->db->createCommand() - ->update($this->cacheTable, [ - 'expire' => $duration > 0 ? $duration + time() : 0, - 'data' => [$value, \PDO::PARAM_LOB], - ], ['id' => $key]); + $result = $this->db->noCache(function (Connection $db) use ($key, $value, $duration) { + $command = $db->createCommand() + ->update($this->cacheTable, [ + 'expire' => $duration > 0 ? $duration + time() : 0, + 'data' => [$value, \PDO::PARAM_LOB], + ], ['id' => $key]); + return $command->execute(); + }); - if ($command->execute()) { + if ($result) { $this->gc(); return true; @@ -216,12 +219,14 @@ class DbCache extends Cache $this->gc(); try { - $this->db->createCommand() - ->insert($this->cacheTable, [ - 'id' => $key, - 'expire' => $duration > 0 ? $duration + time() : 0, - 'data' => [$value, \PDO::PARAM_LOB], - ])->execute(); + $this->db->noCache(function (Connection $db) use ($key, $value, $duration) { + $db->createCommand() + ->insert($this->cacheTable, [ + 'id' => $key, + 'expire' => $duration > 0 ? $duration + time() : 0, + 'data' => [$value, \PDO::PARAM_LOB], + ])->execute(); + }); return true; } catch (\Exception $e) { @@ -237,9 +242,11 @@ class DbCache extends Cache */ protected function deleteValue($key) { - $this->db->createCommand() - ->delete($this->cacheTable, ['id' => $key]) - ->execute(); + $this->db->noCache(function (Connection $db) use ($key) { + $db->createCommand() + ->delete($this->cacheTable, ['id' => $key]) + ->execute(); + }); return true; } From 3a8f702759924f3d13200b5f98295a2917f7f083 Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Wed, 26 Apr 2017 03:16:12 +0300 Subject: [PATCH 10/22] Adjusted code style for less conditions branching --- framework/caching/DbCache.php | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/framework/caching/DbCache.php b/framework/caching/DbCache.php index a57bd48880..0bae1abfcc 100644 --- a/framework/caching/DbCache.php +++ b/framework/caching/DbCache.php @@ -136,9 +136,8 @@ class DbCache extends Cache $this->db->enableQueryCache = true; return $result; - } else { - return $query->createCommand($this->db)->queryScalar(); } + return $query->createCommand($this->db)->queryScalar(); } /** @@ -200,9 +199,8 @@ class DbCache extends Cache $this->gc(); return true; - } else { - return $this->addValue($key, $value, $duration); } + return $this->addValue($key, $value, $duration); } /** From 70cd75c84e2d993a9f6c8cad0219d46cdc80686f Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Wed, 26 Apr 2017 03:19:49 +0300 Subject: [PATCH 11/22] Fixes #13226: `yii cache` command now warns about the fact that it's not able to flush APC cache from console --- framework/CHANGELOG.md | 1 + .../console/controllers/CacheController.php | 25 +++++++++++++++---- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 50b23aee01..62fa5a04d3 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -4,6 +4,7 @@ Yii Framework 2 Change Log 2.0.12 under development -------------------------- +- Enh #13226: `yii cache` command now warns about the fact that it's not able to flush APC cache from console (samdark) - Bug #11719: Fixed `yii\db\Connection::$enableQueryCache` caused infinite loop when the same connection was used for `yii\caching\DbCache` (michaelarnauts) - Bug #10346: Fixed "DOMException: Invalid Character Error" in `yii\web\XmlResponseFormatter::buildXml()` (sasha-ch) - Bug #13694: `yii\widgets\Pjax` now sends `X-Pjax-Url` header with response to fix redirect (wleona3, Faryshta) diff --git a/framework/console/controllers/CacheController.php b/framework/console/controllers/CacheController.php index 1f393103d7..9d65f8d381 100644 --- a/framework/console/controllers/CacheController.php +++ b/framework/console/controllers/CacheController.php @@ -8,6 +8,7 @@ namespace yii\console\controllers; use Yii; +use yii\caching\ApcCache; use yii\console\Controller; use yii\caching\Cache; use yii\helpers\Console; @@ -32,7 +33,7 @@ use yii\console\Exception; * configured are different from web application, web application cache won't be cleared. In order to fix it please * duplicate web application cache components in console config. You can use any component names. * - * Both APC and OpCache aren't shared between PHP processes so flushing cache from command line has no effect on web. + * APC is not shared between PHP processes so flushing cache from command line has no effect on web. * Flushing web cache could be either done by: * * - Putting a php file under web root and calling it via HTTP @@ -99,7 +100,7 @@ class CacheController extends Controller $cachesInfo[] = [ 'name' => $name, 'class' => $class, - 'is_flushed' => Yii::$app->get($name)->flush(), + 'is_flushed' => $this->canBeFlushed($class) ? Yii::$app->get($name)->flush() : false, ]; } @@ -123,7 +124,7 @@ class CacheController extends Controller $cachesInfo[] = [ 'name' => $name, 'class' => $class, - 'is_flushed' => Yii::$app->get($name)->flush(), + 'is_flushed' => $this->canBeFlushed($class) ? Yii::$app->get($name)->flush() : false, ]; } @@ -178,7 +179,11 @@ class CacheController extends Controller $this->stdout("The following caches were found in the system:\n\n", Console::FG_YELLOW); foreach ($caches as $name => $class) { - $this->stdout("\t* $name ($class)\n", Console::FG_GREEN); + if ($this->canBeFlushed($class)) { + $this->stdout("\t* $name ($class)\n", Console::FG_GREEN); + } else { + $this->stdout("\t* $name ($class) - can not be flushed via console\n", Console::FG_YELLOW); + } } $this->stdout("\n"); @@ -256,7 +261,7 @@ class CacheController extends Controller $findAll = ($cachesNames === []); foreach ($components as $name => $component) { - if (!$findAll && !in_array($name, $cachesNames)) { + if (!$findAll && !in_array($name, $cachesNames, true)) { continue; } @@ -281,4 +286,14 @@ class CacheController extends Controller { return is_subclass_of($className, Cache::className()); } + + /** + * Checks if cache of a certain class can be flushed + * @param string $className class name. + * @return bool + */ + private function canBeFlushed($className) + { + return !is_a($className, ApcCache::className(), true) || php_sapi_name() !== "cli"; + } } From db0e7a6c8f31351df5c38a5f2ad638c57ca8770b Mon Sep 17 00:00:00 2001 From: Cyrillos Jonua Date: Wed, 26 Apr 2017 03:28:05 +0300 Subject: [PATCH 12/22] Fixes #13848: `yii\di\Instance::ensure()` wasn't throwing an exception when `$type` is specified and `$reference` object isn't instance of `$type` --- framework/CHANGELOG.md | 1 + framework/di/Instance.php | 7 ++++++- tests/framework/di/InstanceTest.php | 9 ++++++++- 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 62fa5a04d3..5786abc65a 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -4,6 +4,7 @@ Yii Framework 2 Change Log 2.0.12 under development -------------------------- +- Bug #13848: `yii\di\Instance::ensure()` wasn't throwing an exception when `$type` is specified and `$reference` object isn't instance of `$type` (c-jonua) - Enh #13226: `yii cache` command now warns about the fact that it's not able to flush APC cache from console (samdark) - Bug #11719: Fixed `yii\db\Connection::$enableQueryCache` caused infinite loop when the same connection was used for `yii\caching\DbCache` (michaelarnauts) - Bug #10346: Fixed "DOMException: Invalid Character Error" in `yii\web\XmlResponseFormatter::buildXml()` (sasha-ch) diff --git a/framework/di/Instance.php b/framework/di/Instance.php index b4d6dea278..2300cc4e94 100644 --- a/framework/di/Instance.php +++ b/framework/di/Instance.php @@ -116,7 +116,12 @@ class Instance $container = Yii::$container; } unset($reference['class']); - return $container->get($class, [], $reference); + $component = $container->get($class, [], $reference); + if ($type === null || $component instanceof $type) { + return $component; + } else { + throw new InvalidConfigException('Invalid data type: ' . $class .'. ' . $type . ' is expected.'); + } } elseif (empty($reference)) { throw new InvalidConfigException('The required component is not specified.'); } diff --git a/tests/framework/di/InstanceTest.php b/tests/framework/di/InstanceTest.php index 3e673dde22..a6689195eb 100644 --- a/tests/framework/di/InstanceTest.php +++ b/tests/framework/di/InstanceTest.php @@ -112,7 +112,6 @@ class InstanceTest extends TestCase $this->expectExceptionMessage('"db" refers to a yii\db\Connection component. yii\base\Widget is expected.'); Instance::ensure('db', 'yii\base\Widget', $container); - Instance::ensure(['class' => 'yii\db\Connection', 'dsn' => 'test'], 'yii\base\Widget', $container); } public function testExceptionInvalidDataType() @@ -191,4 +190,12 @@ PHP Instance::__set_state([]); } + + public function testExceptionInvalidDataTypeInArray() + { + $this->setExpectedException('yii\base\InvalidConfigException', 'Invalid data type: yii\db\Connection. yii\base\Widget is expected.'); + Instance::ensure([ + 'class' => Connection::className(), + ], 'yii\base\Widget'); + } } From 6792099bcc0b682cc9fcfa9e91157a29e8bfe460 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michael=20H=C3=A4rtl?= Date: Tue, 21 Mar 2017 18:23:27 +0100 Subject: [PATCH 13/22] Fixes #13689: Fixed handling of errors in closures --- framework/CHANGELOG.md | 1 + framework/web/ErrorHandler.php | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 5786abc65a..2d35d49b9c 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -6,6 +6,7 @@ Yii Framework 2 Change Log - Bug #13848: `yii\di\Instance::ensure()` wasn't throwing an exception when `$type` is specified and `$reference` object isn't instance of `$type` (c-jonua) - Enh #13226: `yii cache` command now warns about the fact that it's not able to flush APC cache from console (samdark) +- Bug #13689: Fixed handling of errors in closures (mikehaertl) - Bug #11719: Fixed `yii\db\Connection::$enableQueryCache` caused infinite loop when the same connection was used for `yii\caching\DbCache` (michaelarnauts) - Bug #10346: Fixed "DOMException: Invalid Character Error" in `yii\web\XmlResponseFormatter::buildXml()` (sasha-ch) - Bug #13694: `yii\widgets\Pjax` now sends `X-Pjax-Url` header with response to fix redirect (wleona3, Faryshta) diff --git a/framework/web/ErrorHandler.php b/framework/web/ErrorHandler.php index bf9e66207a..a6c4e01fe6 100644 --- a/framework/web/ErrorHandler.php +++ b/framework/web/ErrorHandler.php @@ -191,7 +191,7 @@ class ErrorHandler extends \yii\base\ErrorHandler $url = null; $shouldGenerateLink = true; - if ($method !== null) { + if ($method !== null && substr_compare($method, '{closure}', -9) !== 0) { $reflection = new \ReflectionMethod($class, $method); $shouldGenerateLink = $reflection->isPublic() || $reflection->isProtected(); } From d786b78f2553613f7b31efcceb56a044c1b33cb6 Mon Sep 17 00:00:00 2001 From: Carsten Brandt Date: Wed, 26 Apr 2017 09:49:44 +0200 Subject: [PATCH 14/22] Helper independent (#14050) * Made sure most helpers are independent of Yii::$app * Made sure most validators are independent of Yii::$app --- tests/framework/helpers/ArrayHelperTest.php | 6 +++++- tests/framework/helpers/ConsoleTest.php | 8 ++++++++ tests/framework/helpers/FileHelperTest.php | 6 ++++++ tests/framework/helpers/InflectorTest.php | 8 ++++++++ tests/framework/helpers/JsonTest.php | 8 ++++++++ tests/framework/helpers/MarkdownTest.php | 8 ++++++++ tests/framework/helpers/VarDumperTest.php | 8 ++++++++ tests/framework/validators/BooleanValidatorTest.php | 4 +++- tests/framework/validators/CompareValidatorTest.php | 4 +++- tests/framework/validators/DefaultValueValidatorTest.php | 4 +++- tests/framework/validators/EachValidatorTest.php | 4 +++- tests/framework/validators/EmailValidatorTest.php | 4 +++- tests/framework/validators/ExistValidatorTest.php | 6 ++++-- tests/framework/validators/FileValidatorTest.php | 3 ++- tests/framework/validators/FilterValidatorTest.php | 3 ++- tests/framework/validators/IpValidatorTest.php | 3 ++- tests/framework/validators/NumberValidatorTest.php | 5 ++++- tests/framework/validators/RangeValidatorTest.php | 4 +++- .../validators/RegularExpressionValidatorTest.php | 4 +++- tests/framework/validators/RequiredValidatorTest.php | 4 +++- tests/framework/validators/UniqueValidatorTest.php | 6 ++++-- tests/framework/validators/UrlValidatorTest.php | 4 +++- tests/framework/validators/ValidatorTest.php | 4 +++- 23 files changed, 99 insertions(+), 19 deletions(-) diff --git a/tests/framework/helpers/ArrayHelperTest.php b/tests/framework/helpers/ArrayHelperTest.php index 224ef06692..282ae7f304 100644 --- a/tests/framework/helpers/ArrayHelperTest.php +++ b/tests/framework/helpers/ArrayHelperTest.php @@ -44,7 +44,9 @@ class ArrayHelperTest extends TestCase protected function setUp() { parent::setUp(); - $this->mockApplication(); + + // destroy application, Helper must work without Yii::$app + $this->destroyApplication(); } public function testToArray() @@ -267,6 +269,7 @@ class ArrayHelperTest extends TestCase $sort = new Sort([ 'attributes' => ['name', 'age'], 'defaultOrder' => ['name' => SORT_ASC], + 'params' => [], ]); $orders = $sort->getOrders(); @@ -284,6 +287,7 @@ class ArrayHelperTest extends TestCase $sort = new Sort([ 'attributes' => ['name', 'age'], 'defaultOrder' => ['name' => SORT_ASC, 'age' => SORT_DESC], + 'params' => [], ]); $orders = $sort->getOrders(); diff --git a/tests/framework/helpers/ConsoleTest.php b/tests/framework/helpers/ConsoleTest.php index 61f777de38..89521067d4 100644 --- a/tests/framework/helpers/ConsoleTest.php +++ b/tests/framework/helpers/ConsoleTest.php @@ -12,6 +12,14 @@ use yiiunit\TestCase; */ class ConsoleTest extends TestCase { + protected function setUp() + { + parent::setUp(); + + // destroy application, Helper must work without Yii::$app + $this->destroyApplication(); + } + public function testStripAnsiFormat() { ob_start(); diff --git a/tests/framework/helpers/FileHelperTest.php b/tests/framework/helpers/FileHelperTest.php index d70c3787ad..ca976db12c 100644 --- a/tests/framework/helpers/FileHelperTest.php +++ b/tests/framework/helpers/FileHelperTest.php @@ -33,8 +33,14 @@ class FileHelperTest extends TestCase */ $this->markTestInComplete('Unit tests runtime directory should be local!'); } + + parent::setUp(); + + // destroy application, Helper must work without Yii::$app + $this->destroyApplication(); } + public function tearDown() { $this->removeDir($this->testFilePath); diff --git a/tests/framework/helpers/InflectorTest.php b/tests/framework/helpers/InflectorTest.php index 0d8875c6a0..2408ba131e 100644 --- a/tests/framework/helpers/InflectorTest.php +++ b/tests/framework/helpers/InflectorTest.php @@ -10,6 +10,14 @@ use yiiunit\TestCase; */ class InflectorTest extends TestCase { + protected function setUp() + { + parent::setUp(); + + // destroy application, Helper must work without Yii::$app + $this->destroyApplication(); + } + public function testPluralize() { $testData = [ diff --git a/tests/framework/helpers/JsonTest.php b/tests/framework/helpers/JsonTest.php index a88ef943a6..9788858a4e 100644 --- a/tests/framework/helpers/JsonTest.php +++ b/tests/framework/helpers/JsonTest.php @@ -14,6 +14,14 @@ use yiiunit\framework\web\Post; */ class JsonTest extends TestCase { + protected function setUp() + { + parent::setUp(); + + // destroy application, Helper must work without Yii::$app + $this->destroyApplication(); + } + public function testEncode() { // basic data encoding diff --git a/tests/framework/helpers/MarkdownTest.php b/tests/framework/helpers/MarkdownTest.php index af83c626e7..3e993609f1 100644 --- a/tests/framework/helpers/MarkdownTest.php +++ b/tests/framework/helpers/MarkdownTest.php @@ -12,6 +12,14 @@ use yii\helpers\Markdown; */ class MarkdownTest extends TestCase { + protected function setUp() + { + parent::setUp(); + + // destroy application, Helper must work without Yii::$app + $this->destroyApplication(); + } + public function testOriginalFlavor() { $text = <<destroyApplication(); + } + public function testDumpIncompleteObject() { $serializedObj = 'O:16:"nonExistingClass":0:{}'; diff --git a/tests/framework/validators/BooleanValidatorTest.php b/tests/framework/validators/BooleanValidatorTest.php index c3f013017a..29b008f646 100644 --- a/tests/framework/validators/BooleanValidatorTest.php +++ b/tests/framework/validators/BooleanValidatorTest.php @@ -14,7 +14,9 @@ class BooleanValidatorTest extends TestCase protected function setUp() { parent::setUp(); - $this->mockApplication(); + + // destroy application, Validator must work without Yii::$app + $this->destroyApplication(); } public function testValidateValue() diff --git a/tests/framework/validators/CompareValidatorTest.php b/tests/framework/validators/CompareValidatorTest.php index 181e98abe5..e831cb1e9c 100644 --- a/tests/framework/validators/CompareValidatorTest.php +++ b/tests/framework/validators/CompareValidatorTest.php @@ -14,7 +14,9 @@ class CompareValidatorTest extends TestCase protected function setUp() { parent::setUp(); - $this->mockApplication(); + + // destroy application, Validator must work without Yii::$app + $this->destroyApplication(); } public function testValidateValueException() diff --git a/tests/framework/validators/DefaultValueValidatorTest.php b/tests/framework/validators/DefaultValueValidatorTest.php index 80a0fdcdb1..5699415d2b 100644 --- a/tests/framework/validators/DefaultValueValidatorTest.php +++ b/tests/framework/validators/DefaultValueValidatorTest.php @@ -13,7 +13,9 @@ class DefaultValueValidatorTest extends TestCase protected function setUp() { parent::setUp(); - $this->mockApplication(); + + // destroy application, Validator must work without Yii::$app + $this->destroyApplication(); } public function testValidateAttribute() diff --git a/tests/framework/validators/EachValidatorTest.php b/tests/framework/validators/EachValidatorTest.php index 743052794b..a2757d811f 100644 --- a/tests/framework/validators/EachValidatorTest.php +++ b/tests/framework/validators/EachValidatorTest.php @@ -14,7 +14,9 @@ class EachValidatorTest extends TestCase protected function setUp() { parent::setUp(); - $this->mockApplication(); + + // destroy application, Validator must work without Yii::$app + $this->destroyApplication(); } public function testArrayFormat() diff --git a/tests/framework/validators/EmailValidatorTest.php b/tests/framework/validators/EmailValidatorTest.php index 6e59dee56c..5fa88ae0ee 100644 --- a/tests/framework/validators/EmailValidatorTest.php +++ b/tests/framework/validators/EmailValidatorTest.php @@ -13,7 +13,9 @@ class EmailValidatorTest extends TestCase protected function setUp() { parent::setUp(); - $this->mockApplication(); + + // destroy application, Validator must work without Yii::$app + $this->destroyApplication(); } public function testValidateValue() diff --git a/tests/framework/validators/ExistValidatorTest.php b/tests/framework/validators/ExistValidatorTest.php index 306f98dc8f..d3aacc4719 100644 --- a/tests/framework/validators/ExistValidatorTest.php +++ b/tests/framework/validators/ExistValidatorTest.php @@ -14,10 +14,12 @@ use yiiunit\framework\db\DatabaseTestCase; abstract class ExistValidatorTest extends DatabaseTestCase { - public function setUp() + protected function setUp() { parent::setUp(); - $this->mockApplication(); + + // destroy application, Validator must work without Yii::$app + $this->destroyApplication(); ActiveRecord::$db = $this->getConnection(); } diff --git a/tests/framework/validators/FileValidatorTest.php b/tests/framework/validators/FileValidatorTest.php index 8775bd5f39..bfa88e41ce 100644 --- a/tests/framework/validators/FileValidatorTest.php +++ b/tests/framework/validators/FileValidatorTest.php @@ -14,8 +14,9 @@ use yiiunit\TestCase; */ class FileValidatorTest extends TestCase { - public function setUp() + protected function setUp() { + parent::setUp(); $this->mockApplication(); } diff --git a/tests/framework/validators/FilterValidatorTest.php b/tests/framework/validators/FilterValidatorTest.php index b554e48f13..9512c2f622 100644 --- a/tests/framework/validators/FilterValidatorTest.php +++ b/tests/framework/validators/FilterValidatorTest.php @@ -14,7 +14,8 @@ class FilterValidatorTest extends TestCase protected function setUp() { parent::setUp(); - $this->mockApplication(); + // destroy application, Validator must work without Yii::$app + $this->destroyApplication(); } public function testAssureExceptionOnInit() diff --git a/tests/framework/validators/IpValidatorTest.php b/tests/framework/validators/IpValidatorTest.php index 1fc2a7e138..56f5d9695c 100644 --- a/tests/framework/validators/IpValidatorTest.php +++ b/tests/framework/validators/IpValidatorTest.php @@ -14,7 +14,8 @@ class IpValidatorTest extends TestCase protected function setUp() { parent::setUp(); - $this->mockApplication(); + // destroy application, Validator must work without Yii::$app + $this->destroyApplication(); } public function testInitException() diff --git a/tests/framework/validators/NumberValidatorTest.php b/tests/framework/validators/NumberValidatorTest.php index 7959d1a48e..b4456a5fa9 100644 --- a/tests/framework/validators/NumberValidatorTest.php +++ b/tests/framework/validators/NumberValidatorTest.php @@ -46,8 +46,11 @@ class NumberValidatorTest extends TestCase protected function setUp() { parent::setUp(); - $this->mockApplication(); + $this->oldLocale = setlocale(LC_NUMERIC, 0); + + // destroy application, Validator must work without Yii::$app + $this->destroyApplication(); } public function testEnsureMessageOnInit() diff --git a/tests/framework/validators/RangeValidatorTest.php b/tests/framework/validators/RangeValidatorTest.php index f882eb1153..f995740327 100644 --- a/tests/framework/validators/RangeValidatorTest.php +++ b/tests/framework/validators/RangeValidatorTest.php @@ -14,7 +14,9 @@ class RangeValidatorTest extends TestCase protected function setUp() { parent::setUp(); - $this->mockApplication(); + + // destroy application, Validator must work without Yii::$app + $this->destroyApplication(); } public function testInitException() diff --git a/tests/framework/validators/RegularExpressionValidatorTest.php b/tests/framework/validators/RegularExpressionValidatorTest.php index adbf7be84b..bafb1bc36a 100644 --- a/tests/framework/validators/RegularExpressionValidatorTest.php +++ b/tests/framework/validators/RegularExpressionValidatorTest.php @@ -14,7 +14,9 @@ class RegularExpressionValidatorTest extends TestCase protected function setUp() { parent::setUp(); - $this->mockApplication(); + + // destroy application, Validator must work without Yii::$app + $this->destroyApplication(); } public function testValidateValue() diff --git a/tests/framework/validators/RequiredValidatorTest.php b/tests/framework/validators/RequiredValidatorTest.php index 0c206e4ccf..6f43bff705 100644 --- a/tests/framework/validators/RequiredValidatorTest.php +++ b/tests/framework/validators/RequiredValidatorTest.php @@ -13,7 +13,9 @@ class RequiredValidatorTest extends TestCase protected function setUp() { parent::setUp(); - $this->mockApplication(); + + // destroy application, Validator must work without Yii::$app + $this->destroyApplication(); } public function testValidateValueWithDefaults() diff --git a/tests/framework/validators/UniqueValidatorTest.php b/tests/framework/validators/UniqueValidatorTest.php index afdb0c44b4..c6248d5760 100644 --- a/tests/framework/validators/UniqueValidatorTest.php +++ b/tests/framework/validators/UniqueValidatorTest.php @@ -16,11 +16,13 @@ use yiiunit\framework\db\DatabaseTestCase; abstract class UniqueValidatorTest extends DatabaseTestCase { - public function setUp() + protected function setUp() { parent::setUp(); - $this->mockApplication(); ActiveRecord::$db = $this->getConnection(); + + // destroy application, Validator must work without Yii::$app + $this->destroyApplication(); } public function testAssureMessageSetOnInit() diff --git a/tests/framework/validators/UrlValidatorTest.php b/tests/framework/validators/UrlValidatorTest.php index 063d172f7a..1448866300 100644 --- a/tests/framework/validators/UrlValidatorTest.php +++ b/tests/framework/validators/UrlValidatorTest.php @@ -14,7 +14,9 @@ class UrlValidatorTest extends TestCase protected function setUp() { parent::setUp(); - $this->mockApplication(); + + // destroy application, Validator must work without Yii::$app + $this->destroyApplication(); } public function testValidateValue() diff --git a/tests/framework/validators/ValidatorTest.php b/tests/framework/validators/ValidatorTest.php index 0921076fb4..8e9dcbecd7 100644 --- a/tests/framework/validators/ValidatorTest.php +++ b/tests/framework/validators/ValidatorTest.php @@ -17,7 +17,9 @@ class ValidatorTest extends TestCase protected function setUp() { parent::setUp(); - $this->mockApplication(); + + // destroy application, Validator must work without Yii::$app + $this->destroyApplication(); } protected function getTestModel($additionalAttributes = []) From 1e65fc29edf0d4f10effb88bd77f79e718dfcb6d Mon Sep 17 00:00:00 2001 From: Kolyunya Date: Sat, 22 Apr 2017 19:42:52 +0300 Subject: [PATCH 15/22] Fixes #14033: Fixed `yii\filters\AccessRule::matchIp()` erroring in case IP is not defined under HHVM --- framework/CHANGELOG.md | 1 + framework/filters/AccessRule.php | 11 +++++++++-- tests/framework/filters/AccessRuleTest.php | 8 ++++++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 2d35d49b9c..03d6b0c4c4 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -4,6 +4,7 @@ Yii Framework 2 Change Log 2.0.12 under development -------------------------- +- Bug #14033: Fixed `yii\filters\AccessRule::matchIp()` erroring in case IP is not defined under HHVM (Kolyunya) - Bug #13848: `yii\di\Instance::ensure()` wasn't throwing an exception when `$type` is specified and `$reference` object isn't instance of `$type` (c-jonua) - Enh #13226: `yii cache` command now warns about the fact that it's not able to flush APC cache from console (samdark) - Bug #13689: Fixed handling of errors in closures (mikehaertl) diff --git a/framework/filters/AccessRule.php b/framework/filters/AccessRule.php index 4eacf57942..d827e6330c 100644 --- a/framework/filters/AccessRule.php +++ b/framework/filters/AccessRule.php @@ -165,7 +165,7 @@ class AccessRule extends Component } /** - * @param string $ip the IP address + * @param string|null $ip the IP address * @return bool whether the rule applies to the IP address */ protected function matchIP($ip) @@ -174,7 +174,14 @@ class AccessRule extends Component return true; } foreach ($this->ips as $rule) { - if ($rule === '*' || $rule === $ip || (($pos = strpos($rule, '*')) !== false && !strncmp($ip, $rule, $pos))) { + if ($rule === '*' || + $rule === $ip || + ( + $ip !== null && + ($pos = strpos($rule, '*')) !== false && + strncmp($ip, $rule, $pos) === 0 + ) + ) { return true; } } diff --git a/tests/framework/filters/AccessRuleTest.php b/tests/framework/filters/AccessRuleTest.php index 57e67ac17a..b9a56803cf 100644 --- a/tests/framework/filters/AccessRuleTest.php +++ b/tests/framework/filters/AccessRuleTest.php @@ -292,6 +292,14 @@ class AccessRuleTest extends \yiiunit\TestCase $this->assertNull($rule->allows($action, $user, $request)); $rule->allow = false; $this->assertNull($rule->allows($action, $user, $request)); + + // undefined IP + $_SERVER['REMOTE_ADDR'] = null; + $rule->ips = ['192.168.*']; + $rule->allow = true; + $this->assertNull($rule->allows($action, $user, $request)); + $rule->allow = false; + $this->assertNull($rule->allows($action, $user, $request)); } public function testMatchIPWildcard() From a9bf1a3a7fa377457a4f09ab24562c9c1d8017b4 Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Wed, 26 Apr 2017 12:02:09 +0300 Subject: [PATCH 16/22] Removed redundant use --- tests/framework/filters/AccessRuleTest.php | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/tests/framework/filters/AccessRuleTest.php b/tests/framework/filters/AccessRuleTest.php index b9a56803cf..8bcb21daa5 100644 --- a/tests/framework/filters/AccessRuleTest.php +++ b/tests/framework/filters/AccessRuleTest.php @@ -5,7 +5,6 @@ namespace yiiunit\framework\filters; use Yii; use yii\base\Action; use yii\filters\AccessRule; -use yii\filters\HttpCache; use yii\web\Controller; use yii\web\Request; use yii\web\User; @@ -21,8 +20,8 @@ class AccessRuleTest extends \yiiunit\TestCase { parent::setUp(); - $_SERVER['SCRIPT_FILENAME'] = "/index.php"; - $_SERVER['SCRIPT_NAME'] = "/index.php"; + $_SERVER['SCRIPT_FILENAME'] = '/index.php'; + $_SERVER['SCRIPT_NAME'] = '/index.php'; $this->mockWebApplication(); } @@ -42,7 +41,7 @@ class AccessRuleTest extends \yiiunit\TestCase } /** - * @param string optional user id + * @param string $userid optional user id * @return User */ protected function mockUser($userid = null) From 100213d9b2e2e028a08504d4c719c45c7a4e478b Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Wed, 26 Apr 2017 12:02:17 +0300 Subject: [PATCH 17/22] Removed redundant else --- framework/filters/AccessRule.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/framework/filters/AccessRule.php b/framework/filters/AccessRule.php index d827e6330c..0d859e9091 100644 --- a/framework/filters/AccessRule.php +++ b/framework/filters/AccessRule.php @@ -115,9 +115,9 @@ class AccessRule extends Component && $this->matchCustom($action) ) { return $this->allow ? true : false; - } else { - return null; } + + return null; } /** From a3a123077f4feb3d8031a063fe7dba20d5434464 Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Wed, 26 Apr 2017 12:52:49 +0300 Subject: [PATCH 18/22] Fixes #13790: Fixed error in `\yii\widgets\MaskedInput` JavaScript by raising version required --- framework/CHANGELOG.md | 1 + framework/composer.json | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 03d6b0c4c4..049ebf1acf 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -4,6 +4,7 @@ Yii Framework 2 Change Log 2.0.12 under development -------------------------- +- Bug #13790: Fixed error in `\yii\widgets\MaskedInput` JavaScript by raising version required (samdark) - Bug #14033: Fixed `yii\filters\AccessRule::matchIp()` erroring in case IP is not defined under HHVM (Kolyunya) - Bug #13848: `yii\di\Instance::ensure()` wasn't throwing an exception when `$type` is specified and `$reference` object isn't instance of `$type` (c-jonua) - Enh #13226: `yii cache` command now warns about the fact that it's not able to flush APC cache from console (samdark) diff --git a/framework/composer.json b/framework/composer.json index 2d00889c11..8bbb8c7768 100644 --- a/framework/composer.json +++ b/framework/composer.json @@ -71,7 +71,7 @@ "ezyang/htmlpurifier": "~4.6", "cebe/markdown": "~1.0.0 | ~1.1.0", "bower-asset/jquery": "2.2.*@stable | 2.1.*@stable | 1.11.*@stable | 1.12.*@stable", - "bower-asset/jquery.inputmask": "~3.2.2 | ~3.3.3", + "bower-asset/jquery.inputmask": "~3.2.2 | ~3.3.5", "bower-asset/punycode": "1.3.*", "bower-asset/yii2-pjax": "~2.0.1" }, From 705dae996468985c8213cc6fe1f6b159d61fded5 Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Wed, 26 Apr 2017 12:56:54 +0300 Subject: [PATCH 19/22] Fixes #14052: Fixed processing parse errors on PHP 7 since these are instances of `\ParseError` --- framework/CHANGELOG.md | 1 + framework/web/ErrorHandler.php | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 049ebf1acf..4ff90446b9 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -4,6 +4,7 @@ Yii Framework 2 Change Log 2.0.12 under development -------------------------- +- Bug #14052: Fixed processing parse errors on PHP 7 since these are instances of `\ParseError` (samdark) - Bug #13790: Fixed error in `\yii\widgets\MaskedInput` JavaScript by raising version required (samdark) - Bug #14033: Fixed `yii\filters\AccessRule::matchIp()` erroring in case IP is not defined under HHVM (Kolyunya) - Bug #13848: `yii\di\Instance::ensure()` wasn't throwing an exception when `$type` is specified and `$reference` object isn't instance of `$type` (c-jonua) diff --git a/framework/web/ErrorHandler.php b/framework/web/ErrorHandler.php index a6c4e01fe6..f01d6d083d 100644 --- a/framework/web/ErrorHandler.php +++ b/framework/web/ErrorHandler.php @@ -306,11 +306,11 @@ class ErrorHandler extends \yii\base\ErrorHandler /** * Renders call stack. - * @param \Exception $exception exception to get call stack from + * @param \Exception|\ParseError $exception exception to get call stack from * @return string HTML content of the rendered call stack. * @since 2.0.12 */ - public function renderCallStack(\Exception $exception) + public function renderCallStack($exception) { $out = '
    '; $out .= $this->renderCallStackItem($exception->getFile(), $exception->getLine(), null, null, [], 1); From 375ea7a847271e7c61fdbc1d4991f0d13b551c42 Mon Sep 17 00:00:00 2001 From: Alexander Makarov Date: Wed, 26 Apr 2017 13:32:58 +0300 Subject: [PATCH 20/22] Fixes #13951: renamed get-method which was conflicting with existing property (#14055) --- framework/rbac/BaseManager.php | 2 +- framework/rbac/DbManager.php | 2 +- framework/rbac/PhpManager.php | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/framework/rbac/BaseManager.php b/framework/rbac/BaseManager.php index 879215f831..27e9c874cb 100644 --- a/framework/rbac/BaseManager.php +++ b/framework/rbac/BaseManager.php @@ -194,7 +194,7 @@ abstract class BaseManager extends Component implements ManagerInterface * @since 2.0.12 * @return Role[] default roles. The array is indexed by the role names */ - public function getDefaultRoles() + public function getDefaultRoleInstances() { $result = []; foreach ($this->defaultRoles as $roleName) { diff --git a/framework/rbac/DbManager.php b/framework/rbac/DbManager.php index 3f7becb073..473cbb147d 100644 --- a/framework/rbac/DbManager.php +++ b/framework/rbac/DbManager.php @@ -466,7 +466,7 @@ class DbManager extends BaseManager ->andWhere(['a.user_id' => (string) $userId]) ->andWhere(['b.type' => Item::TYPE_ROLE]); - $roles = $this->getDefaultRoles(); + $roles = $this->getDefaultRoleInstances(); foreach ($query->all($this->db) as $row) { $roles[$row['name']] = $this->populateItem($row); } diff --git a/framework/rbac/PhpManager.php b/framework/rbac/PhpManager.php index d489a751fd..26eccaa677 100644 --- a/framework/rbac/PhpManager.php +++ b/framework/rbac/PhpManager.php @@ -392,7 +392,7 @@ class PhpManager extends BaseManager */ public function getRolesByUser($userId) { - $roles = $this->getDefaultRoles(); + $roles = $this->getDefaultRoleInstances(); foreach ($this->getAssignments($userId) as $name => $assignment) { $role = $this->items[$assignment->roleName]; if ($role->type === Item::TYPE_ROLE) { From d7fad8a5552fb1556795c70920c692e6a6ae3bcc Mon Sep 17 00:00:00 2001 From: Dmitry Eliseev Date: Wed, 26 Apr 2017 16:09:55 +0300 Subject: [PATCH 21/22] Fixes #14059: Removed unused AR instantiating for calling of static methods --- framework/CHANGELOG.md | 1 + framework/db/mssql/QueryBuilder.php | 5 ++--- framework/test/BaseActiveFixture.php | 4 +--- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 4ff90446b9..38d992de23 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -83,6 +83,7 @@ Yii Framework 2 Change Log - Enh #13976: Disabled IPv6 check on `\yii\validators\IpValidator` as it turns out it is not needed for inet_* methods to work (mikk150) - Enh #13981: `yii\caching\Cache::getOrSet()` now supports both `Closure` and `callable` (silverfire) - Enh #13911: Significantly enhanced MSSQL schema reading performance (paulzi, WebdevMerlion) +- Enh #14059: Removed unused AR instantiating for calling of static methods (ElisDN) 2.0.11.2 February 08, 2017 -------------------------- diff --git a/framework/db/mssql/QueryBuilder.php b/framework/db/mssql/QueryBuilder.php index 6cccd40d8d..f8cfa33ea5 100644 --- a/framework/db/mssql/QueryBuilder.php +++ b/framework/db/mssql/QueryBuilder.php @@ -276,9 +276,8 @@ class QueryBuilder extends \yii\db\QueryBuilder if (!$modelClass) { return null; } - /* @var $model \yii\db\ActiveRecord */ - $model = new $modelClass; - $schema = $model->getTableSchema(); + /* @var $modelClass \yii\db\ActiveRecord */ + $schema = $modelClass::getTableSchema(); return array_keys($schema->columns); } diff --git a/framework/test/BaseActiveFixture.php b/framework/test/BaseActiveFixture.php index 7213876254..e3b60920ee 100644 --- a/framework/test/BaseActiveFixture.php +++ b/framework/test/BaseActiveFixture.php @@ -65,10 +65,8 @@ abstract class BaseActiveFixture extends DbFixture implements \IteratorAggregate $row = $this->data[$name]; /* @var $modelClass \yii\db\ActiveRecord */ $modelClass = $this->modelClass; - /* @var $model \yii\db\ActiveRecord */ - $model = new $modelClass; $keys = []; - foreach ($model->primaryKey() as $key) { + foreach ($modelClass::primaryKey() as $key) { $keys[$key] = isset($row[$key]) ? $row[$key] : null; } From da6eada8c88addc3cb4723a1557cb76336eb3d64 Mon Sep 17 00:00:00 2001 From: Nikolay Oleynikov Date: Thu, 27 Apr 2017 17:46:46 +0300 Subject: [PATCH 22/22] Fix an invalid phpDocumentor annotation Fixed an invalid phpDocumentor annotation of `yii\data\DataProviderInterface::getPagination()`. --- framework/data/DataProviderInterface.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/framework/data/DataProviderInterface.php b/framework/data/DataProviderInterface.php index 1eed8824c2..71ed1febfb 100644 --- a/framework/data/DataProviderInterface.php +++ b/framework/data/DataProviderInterface.php @@ -66,7 +66,7 @@ interface DataProviderInterface public function getSort(); /** - * @return Pagination the pagination object. If this is false, it means the pagination is disabled. + * @return Pagination|false the pagination object. If this is false, it means the pagination is disabled. */ public function getPagination(); }