From ba0ab403b52124c941dbeb46fbd9efdc12252a5d Mon Sep 17 00:00:00 2001 From: Robert Korulczyk Date: Mon, 12 Jun 2017 11:25:45 +0200 Subject: [PATCH] Added php-cs-fixer coding standards validation to Travis CI (#14100) * php-cs-fixer: PSR2 rule. * php-cs-fixer: PSR2 rule - fix views. * Travis setup refactoring. * Add php-cs-fixer to travis cs tests. * Fix tests on hhvm-3.12 * improve travis config * composer update * revert composer update * improve travis config * Fix CS. * Extract config to separate classes. * Extract config to separate classes. * Add file header. * Force short array syntax. * binary_operator_spaces fixer * Fix broken tests * cast_spaces fixer * concat_space fixer * dir_constant fixer * ereg_to_preg fixer * function_typehint_space fixer * hash_to_slash_comment fixer * is_null fixer * linebreak_after_opening_tag fixer * lowercase_cast fixer * magic_constant_casing fixer * modernize_types_casting fixer * native_function_casing fixer * new_with_braces fixer * no_alias_functions fixer * no_blank_lines_after_class_opening fixer * no_blank_lines_after_phpdoc fixer * no_empty_comment fixer * no_empty_phpdoc fixer * no_empty_statement fixer * no_extra_consecutive_blank_lines fixer * no_leading_import_slash fixer * no_leading_namespace_whitespace fixer * no_mixed_echo_print fixer * no_multiline_whitespace_around_double_arrow fixer * no_multiline_whitespace_before_semicolons fixer * no_php4_constructor fixer * no_short_bool_cast fixer * no_singleline_whitespace_before_semicolons fixer * no_spaces_around_offset fixer * no_trailing_comma_in_list_call fixer * no_trailing_comma_in_singleline_array fixer * no_unneeded_control_parentheses fixer * no_unused_imports fixer * no_useless_return fixer * no_whitespace_before_comma_in_array fixer * no_whitespace_in_blank_line fixer * not_operator_with_successor_space fixer * object_operator_without_whitespace fixer * ordered_imports fixer * php_unit_construct fixer * php_unit_dedicate_assert fixer * php_unit_fqcn_annotation fixer * phpdoc_indent fixer * phpdoc_no_access fixer * phpdoc_no_empty_return fixer * phpdoc_no_package fixer * phpdoc_no_useless_inheritdoc fixer * Fix broken tests * phpdoc_return_self_reference fixer * phpdoc_single_line_var_spacing fixer * phpdoc_single_line_var_spacing fixer * phpdoc_to_comment fixer * phpdoc_trim fixer * phpdoc_var_without_name fixer * psr4 fixer * self_accessor fixer * short_scalar_cast fixer * single_blank_line_before_namespace fixer * single_quote fixer * standardize_not_equals fixer * ternary_operator_spaces fixer * trailing_comma_in_multiline_array fixer * trim_array_spaces fixer * protected_to_private fixer * unary_operator_spaces fixer * whitespace_after_comma_in_array fixer * `parent::setRules()` -> `$this->setRules()` * blank_line_after_opening_tag fixer * Update finder config. * Revert changes for YiiRequirementChecker. * Fix array formatting. * Add missing import. * Fix CS for new code merged from master. * Fix some indentation issues. --- .php_cs | 29 + .travis.yml | 187 ++-- build/controllers/PhpDocController.php | 57 +- build/controllers/ReleaseController.php | 102 +- build/controllers/TranslationController.php | 2 +- build/controllers/Utf8Controller.php | 34 +- composer.json | 6 +- composer.lock | 1056 +++++++++++++++++++- cs/TODO.md | 1 + cs/src/YiiConfig.php | 174 ++++ cs/src/YiisoftConfig.php | 39 + framework/BaseYii.php | 4 +- framework/Yii.php | 2 - framework/base/Application.php | 6 +- framework/base/Component.php | 2 +- framework/base/ErrorHandler.php | 3 +- framework/base/Event.php | 4 +- framework/base/Model.php | 10 +- framework/base/Module.php | 10 +- framework/base/Security.php | 6 +- framework/base/Widget.php | 2 +- framework/base/WidgetEvent.php | 2 +- framework/behaviors/AttributeTypecastBehavior.php | 2 +- framework/behaviors/SluggableBehavior.php | 4 +- framework/caching/ArrayCache.php | 2 +- framework/caching/Cache.php | 2 +- framework/caching/CacheInterface.php | 5 + framework/caching/DbCache.php | 6 +- framework/caching/MemCache.php | 4 +- .../migrations/m150909_153426_cache_init.php | 1 - framework/captcha/Captcha.php | 2 +- framework/console/Application.php | 4 +- framework/console/Controller.php | 2 +- framework/console/ErrorHandler.php | 2 +- framework/console/UnknownCommandException.php | 4 +- framework/console/controllers/AssetController.php | 6 +- .../console/controllers/BaseMigrateController.php | 19 +- framework/console/controllers/CacheController.php | 8 +- .../console/controllers/FixtureController.php | 12 +- framework/console/controllers/HelpController.php | 8 +- .../console/controllers/MessageController.php | 16 +- .../console/controllers/MigrateController.php | 2 +- framework/data/ActiveDataProvider.php | 4 +- framework/data/SqlDataProvider.php | 2 +- framework/db/ActiveQuery.php | 23 +- framework/db/ActiveQueryTrait.php | 2 +- framework/db/ActiveRelationTrait.php | 4 +- framework/db/BaseActiveRecord.php | 16 +- framework/db/ColumnSchema.php | 2 +- framework/db/Command.php | 2 +- framework/db/Query.php | 4 +- framework/db/QueryBuilder.php | 7 +- framework/db/QueryTrait.php | 2 +- framework/db/Schema.php | 7 +- framework/db/SchemaBuilderTrait.php | 2 +- framework/db/TableSchema.php | 2 +- framework/db/cubrid/Schema.php | 2 +- framework/db/mssql/PDO.php | 2 +- framework/db/mysql/Schema.php | 4 +- framework/db/oci/QueryBuilder.php | 1 - framework/db/oci/Schema.php | 9 +- framework/db/pgsql/Schema.php | 4 +- framework/db/sqlite/QueryBuilder.php | 5 +- framework/db/sqlite/Schema.php | 4 +- framework/di/Container.php | 5 +- framework/di/Instance.php | 2 +- framework/di/NotInstantiableException.php | 2 +- framework/di/ServiceLocator.php | 2 +- framework/filters/AccessControl.php | 2 +- framework/filters/AccessRule.php | 6 +- framework/filters/ContentNegotiator.php | 6 +- framework/filters/Cors.php | 4 +- framework/filters/HostControl.php | 2 +- framework/filters/HttpCache.php | 4 +- framework/filters/PageCache.php | 2 +- framework/filters/RateLimiter.php | 4 +- framework/filters/auth/AuthInterface.php | 4 +- framework/filters/auth/AuthMethod.php | 10 +- framework/filters/auth/CompositeAuth.php | 2 +- framework/grid/DataColumn.php | 4 +- framework/grid/GridView.php | 12 +- framework/helpers/BaseArrayHelper.php | 4 +- framework/helpers/BaseConsole.php | 105 +- framework/helpers/BaseFormatConverter.php | 32 +- framework/helpers/BaseHtml.php | 2 +- framework/helpers/BaseJson.php | 2 +- framework/helpers/BaseStringHelper.php | 4 +- framework/i18n/DbMessageSource.php | 6 +- framework/i18n/Formatter.php | 14 +- framework/i18n/GettextMoFile.php | 4 +- framework/i18n/GettextPoFile.php | 2 +- framework/log/DbTarget.php | 2 +- framework/log/Logger.php | 6 +- framework/mail/BaseMessage.php | 2 +- framework/messages/bs/yii.php | 2 +- framework/mutex/DbMutex.php | 2 +- framework/mutex/OracleMutex.php | 8 +- framework/rbac/DbManager.php | 51 +- framework/rbac/PhpManager.php | 5 +- framework/rbac/Role.php | 1 - .../rbac/migrations/m140506_102106_rbac_init.php | 8 +- framework/requirements/requirements.php | 10 +- framework/requirements/views/console/index.php | 20 +- framework/rest/Controller.php | 2 +- framework/rest/Serializer.php | 4 +- framework/test/DbFixture.php | 2 +- framework/validators/DateValidator.php | 6 +- framework/validators/EachValidator.php | 2 +- framework/validators/EmailValidator.php | 4 +- framework/validators/ExistValidator.php | 4 +- framework/validators/FileValidator.php | 5 +- framework/validators/IpValidator.php | 1 - framework/validators/NumberValidator.php | 2 +- .../validators/RegularExpressionValidator.php | 2 +- framework/validators/UniqueValidator.php | 9 +- framework/validators/UrlValidator.php | 2 +- framework/validators/Validator.php | 2 +- framework/views/errorHandler/callStackItem.php | 10 +- framework/views/errorHandler/error.php | 15 +- framework/views/errorHandler/exception.php | 18 +- framework/views/errorHandler/previousException.php | 10 +- framework/web/Application.php | 4 +- framework/web/AssetBundle.php | 4 +- framework/web/AssetConverter.php | 2 +- framework/web/CompositeUrlRule.php | 2 +- framework/web/CookieCollection.php | 2 +- framework/web/DbSession.php | 4 +- framework/web/ErrorHandler.php | 8 +- framework/web/HeaderCollection.php | 2 +- framework/web/MultiFieldSession.php | 2 +- framework/web/MultipartFormDataParser.php | 8 +- framework/web/Request.php | 19 +- framework/web/Response.php | 12 +- framework/web/Session.php | 2 +- framework/web/UploadedFile.php | 2 +- framework/web/UrlNormalizer.php | 2 +- framework/web/UrlRule.php | 5 +- framework/web/User.php | 2 +- framework/web/View.php | 6 +- framework/web/ViewAction.php | 2 - framework/web/XmlResponseFormatter.php | 2 +- .../web/migrations/m160313_153426_session_init.php | 1 - framework/widgets/ActiveField.php | 6 +- framework/widgets/ActiveForm.php | 4 +- framework/widgets/BaseListView.php | 2 +- framework/widgets/Breadcrumbs.php | 3 +- framework/widgets/DetailView.php | 4 +- framework/widgets/FragmentCache.php | 2 +- framework/widgets/InputWidget.php | 4 +- framework/widgets/LinkPager.php | 2 +- framework/widgets/MaskedInput.php | 8 +- framework/widgets/MaskedInputAsset.php | 4 +- framework/widgets/Menu.php | 2 +- tests/IsOneOfAssert.php | 5 + tests/TestCase.php | 9 +- tests/bootstrap.php | 5 + tests/compatibility.php | 13 +- tests/data/ar/Animal.php | 5 +- tests/data/ar/BitValues.php | 1 - tests/data/ar/Cat.php | 3 - tests/data/ar/Customer.php | 6 + tests/data/ar/CustomerQuery.php | 5 + tests/data/ar/DefaultPk.php | 2 +- tests/data/ar/Document.php | 7 +- tests/data/ar/Dog.php | 3 - tests/data/ar/Item.php | 5 + tests/data/ar/NullValues.php | 5 + tests/data/ar/Order.php | 7 +- tests/data/ar/OrderItem.php | 9 +- tests/data/ar/OrderItemWithNullFK.php | 6 +- tests/data/ar/OrderWithNullFK.php | 7 +- tests/data/ar/Profile.php | 5 +- tests/data/ar/Type.php | 5 + tests/data/base/InvalidRulesModel.php | 6 + tests/data/base/RulesModel.php | 6 + tests/data/base/Singer.php | 8 +- tests/data/base/Speaker.php | 6 + tests/data/cache/MockDependency.php | 8 +- tests/data/config-docker.php | 16 +- tests/data/config.php | 16 +- .../console/controllers/fixtures/FirstFixture.php | 6 +- .../controllers/fixtures/FixtureStorage.php | 9 +- .../console/controllers/fixtures/GlobalFixture.php | 7 +- .../console/controllers/fixtures/SecondFixture.php | 6 +- .../controllers/fixtures/subdir/FirstFixture.php | 6 +- .../controllers/fixtures/subdir/SecondFixture.php | 6 +- .../data/console/migrate_create/add_columns_fk.php | 5 + .../console/migrate_create/add_columns_prefix.php | 5 + .../console/migrate_create/add_columns_test.php | 5 + .../data/console/migrate_create/create_fields.php | 5 + .../console/migrate_create/create_foreign_key.php | 5 + tests/data/console/migrate_create/create_id_pk.php | 5 + .../data/console/migrate_create/create_prefix.php | 5 + .../create_products_from_store_table.php | 5 + tests/data/console/migrate_create/create_test.php | 5 + .../console/migrate_create/create_title_pk.php | 5 + .../create_title_with_comma_default_values.php | 5 + .../migrate_create/create_unsigned_big_pk.php | 5 + .../console/migrate_create/create_unsigned_pk.php | 5 + tests/data/console/migrate_create/default.php | 5 + .../console/migrate_create/drop_columns_test.php | 5 + tests/data/console/migrate_create/drop_fields.php | 5 + .../drop_products_from_store_table.php | 5 + tests/data/console/migrate_create/drop_test.php | 5 + .../data/console/migrate_create/junction_test.php | 8 +- tests/data/helpers/CustomDebugInfo.php | 5 + tests/data/i18n/messages/de-DE/test.php | 6 + tests/data/i18n/messages/de/test.php | 6 + tests/data/i18n/messages/en-US/test.php | 6 + tests/data/i18n/messages/ru/test.php | 6 + tests/data/validators/TestValidator.php | 5 + .../validators/models/FakedValidationModel.php | 7 +- .../validators/models/ValidatorTestMainModel.php | 5 + .../validators/models/ValidatorTestRefModel.php | 6 +- tests/data/views/error.php | 8 +- tests/data/views/errorHandler.php | 6 +- tests/data/views/widgets/ListView/item.php | 13 +- tests/framework/BaseYiiTest.php | 20 +- tests/framework/ar/ActiveRecordTestTrait.php | 24 +- tests/framework/base/ActionFilterTest.php | 3 +- tests/framework/base/ApplicationTest.php | 12 +- tests/framework/base/BehaviorTest.php | 5 + tests/framework/base/ComponentTest.php | 36 +- tests/framework/base/ControllerTest.php | 7 +- tests/framework/base/DynamicModelTest.php | 4 +- tests/framework/base/EventTest.php | 8 +- tests/framework/base/ExposedSecurity.php | 9 +- tests/framework/base/ModelTest.php | 20 +- tests/framework/base/ModuleTest.php | 11 +- tests/framework/base/ObjectTest.php | 17 +- tests/framework/base/SecurityTest.php | 112 +-- tests/framework/base/ThemeTest.php | 7 +- tests/framework/base/ViewTest.php | 7 +- .../fixtures/themes/basic/views/site/index.php | 5 + .../fixtures/themes/christmas/views/site/index.php | 5 + .../fixtures/themes/christmas/views/site/main.php | 5 + .../framework/behaviors/AttributeBehaviorTest.php | 20 +- .../behaviors/AttributeTypecastBehaviorTest.php | 13 +- .../framework/behaviors/BlameableBehaviorTest.php | 18 +- .../framework/behaviors/SluggableBehaviorTest.php | 19 +- .../framework/behaviors/TimestampBehaviorTest.php | 27 +- tests/framework/caching/ApcCacheTest.php | 20 +- tests/framework/caching/ArrayCacheTest.php | 5 + tests/framework/caching/CacheTestCase.php | 5 + tests/framework/caching/DbCacheTest.php | 11 +- tests/framework/caching/DbDependencyTest.php | 7 +- tests/framework/caching/DbQueryDependencyTest.php | 7 +- tests/framework/caching/DependencyTest.php | 7 +- tests/framework/caching/FileCacheTest.php | 6 + tests/framework/caching/MemCacheTest.php | 10 +- tests/framework/caching/MemCachedTest.php | 10 +- tests/framework/caching/TagDependencyTest.php | 8 +- tests/framework/caching/WinCacheTest.php | 10 +- tests/framework/caching/XCacheTest.php | 10 +- tests/framework/caching/ZendDataCacheTest.php | 10 +- tests/framework/console/ControllerTest.php | 16 +- tests/framework/console/FakeController.php | 9 +- tests/framework/console/FakeHelpController.php | 5 + tests/framework/console/RequestTest.php | 7 +- .../console/UnkownCommandExceptionTest.php | 1 - .../console/controllers/AssetControllerTest.php | 61 +- .../controllers/BaseMessageControllerTest.php | 8 +- .../console/controllers/CacheControllerTest.php | 22 +- .../controllers/DbMessageControllerTest.php | 16 +- .../console/controllers/EchoMigrateController.php | 8 +- .../console/controllers/FixtureControllerTest.php | 15 +- .../console/controllers/HelpControllerTest.php | 10 +- .../console/controllers/MigrateControllerTest.php | 19 +- .../controllers/MigrateControllerTestTrait.php | 31 +- .../controllers/PHPMessageControllerTest.php | 7 +- .../controllers/POMessageControllerTest.php | 7 +- .../controllers/SilencedCacheController.php | 10 +- .../controllers/StdOutBufferControllerTrait.php | 7 +- tests/framework/data/ActiveDataProviderTest.php | 24 +- tests/framework/data/ArrayDataProviderTest.php | 81 +- tests/framework/data/BaseDataProviderTest.php | 8 +- tests/framework/data/PaginationTest.php | 7 +- tests/framework/data/SortTest.php | 24 +- tests/framework/data/SqlDataProviderTest.php | 10 +- tests/framework/db/ActiveQueryTest.php | 25 +- tests/framework/db/ActiveRecordTest.php | 142 ++- tests/framework/db/BatchQueryResultTest.php | 9 +- tests/framework/db/ColumnSchemaBuilderTest.php | 12 +- tests/framework/db/CommandTest.php | 20 +- tests/framework/db/ConnectionTest.php | 20 +- tests/framework/db/DatabaseTestCase.php | 11 +- tests/framework/db/QueryBuilderTest.php | 332 +++--- tests/framework/db/QueryTest.php | 67 +- tests/framework/db/SchemaTest.php | 9 +- tests/framework/db/UnqueryableQueryMock.php | 5 + .../framework/db/cubrid/ActiveDataProviderTest.php | 5 + tests/framework/db/cubrid/ActiveFixtureTest.php | 5 + tests/framework/db/cubrid/ActiveQueryTest.php | 5 + tests/framework/db/cubrid/ActiveRecordTest.php | 5 + tests/framework/db/cubrid/BatchQueryResultTest.php | 5 + .../db/cubrid/ColumnSchemaBuilderTest.php | 7 +- tests/framework/db/cubrid/CommandTest.php | 5 + tests/framework/db/cubrid/ConnectionTest.php | 5 + tests/framework/db/cubrid/ExistValidatorTest.php | 5 + tests/framework/db/cubrid/QueryBuilderTest.php | 7 +- tests/framework/db/cubrid/QueryTest.php | 5 + tests/framework/db/cubrid/SchemaTest.php | 5 + tests/framework/db/cubrid/UniqueValidatorTest.php | 5 + .../framework/db/mssql/ActiveDataProviderTest.php | 5 + tests/framework/db/mssql/ActiveFixtureTest.php | 5 + tests/framework/db/mssql/ActiveQueryTest.php | 5 + tests/framework/db/mssql/ActiveRecordTest.php | 5 + tests/framework/db/mssql/BatchQueryResultTest.php | 5 + .../framework/db/mssql/ColumnSchemaBuilderTest.php | 6 +- tests/framework/db/mssql/CommandTest.php | 9 +- tests/framework/db/mssql/ConnectionTest.php | 5 + tests/framework/db/mssql/ExistValidatorTest.php | 5 + tests/framework/db/mssql/QueryBuilderTest.php | 7 +- tests/framework/db/mssql/QueryTest.php | 5 + tests/framework/db/mssql/SchemaTest.php | 5 + tests/framework/db/mssql/UniqueValidatorTest.php | 5 + .../framework/db/mysql/ActiveDataProviderTest.php | 5 + tests/framework/db/mysql/ActiveFixtureTest.php | 5 + tests/framework/db/mysql/ActiveQueryTest.php | 5 + tests/framework/db/mysql/ActiveRecordTest.php | 5 + tests/framework/db/mysql/BatchQueryResultTest.php | 5 + .../framework/db/mysql/ColumnSchemaBuilderTest.php | 7 +- tests/framework/db/mysql/CommandTest.php | 5 + tests/framework/db/mysql/ConnectionTest.php | 5 + tests/framework/db/mysql/ExistValidatorTest.php | 5 + tests/framework/db/mysql/QueryBuilderTest.php | 19 +- tests/framework/db/mysql/QueryTest.php | 8 +- tests/framework/db/mysql/SchemaTest.php | 5 + tests/framework/db/mysql/UniqueValidatorTest.php | 5 + .../framework/db/mysql/connection/DeadLockTest.php | 55 +- tests/framework/db/oci/ActiveDataProviderTest.php | 5 + tests/framework/db/oci/ActiveFixtureTest.php | 5 + tests/framework/db/oci/ActiveQueryTest.php | 5 + tests/framework/db/oci/ActiveRecordTest.php | 5 + tests/framework/db/oci/BatchQueryResultTest.php | 5 + tests/framework/db/oci/ColumnSchemaBuilderTest.php | 5 + tests/framework/db/oci/CommandTest.php | 7 +- tests/framework/db/oci/ConnectionTest.php | 7 +- tests/framework/db/oci/ExistValidatorTest.php | 5 + tests/framework/db/oci/QueryBuilderTest.php | 26 +- tests/framework/db/oci/QueryTest.php | 9 +- tests/framework/db/oci/SchemaTest.php | 8 +- tests/framework/db/oci/UniqueValidatorTest.php | 5 + .../framework/db/pgsql/ActiveDataProviderTest.php | 5 + tests/framework/db/pgsql/ActiveFixtureTest.php | 5 + tests/framework/db/pgsql/ActiveQueryTest.php | 5 + tests/framework/db/pgsql/ActiveRecordTest.php | 7 +- tests/framework/db/pgsql/BatchQueryResultTest.php | 5 + .../framework/db/pgsql/ColumnSchemaBuilderTest.php | 5 + tests/framework/db/pgsql/CommandTest.php | 5 + tests/framework/db/pgsql/ConnectionTest.php | 7 +- tests/framework/db/pgsql/ExistValidatorTest.php | 5 + tests/framework/db/pgsql/QueryBuilderTest.php | 47 +- tests/framework/db/pgsql/QueryTest.php | 6 +- tests/framework/db/pgsql/SchemaTest.php | 7 +- tests/framework/db/pgsql/UniqueValidatorTest.php | 5 + .../framework/db/sqlite/ActiveDataProviderTest.php | 5 + tests/framework/db/sqlite/ActiveFixtureTest.php | 5 + tests/framework/db/sqlite/ActiveQueryTest.php | 5 + tests/framework/db/sqlite/ActiveRecordTest.php | 5 + tests/framework/db/sqlite/BatchQueryResultTest.php | 5 + .../db/sqlite/ColumnSchemaBuilderTest.php | 9 +- tests/framework/db/sqlite/CommandTest.php | 7 +- tests/framework/db/sqlite/ConnectionTest.php | 16 +- tests/framework/db/sqlite/ExistValidatorTest.php | 5 + tests/framework/db/sqlite/QueryBuilderTest.php | 19 +- tests/framework/db/sqlite/QueryTest.php | 8 +- tests/framework/db/sqlite/SchemaTest.php | 5 + tests/framework/db/sqlite/UniqueValidatorTest.php | 5 + tests/framework/db/testBatchInsertWithYield.php | 6 +- tests/framework/di/ContainerTest.php | 47 +- tests/framework/di/InstanceTest.php | 20 +- tests/framework/di/ServiceLocatorTest.php | 6 +- tests/framework/di/stubs/QuxInterface.php | 2 +- tests/framework/filters/AccessRuleTest.php | 30 +- tests/framework/filters/HostControlTest.php | 29 +- tests/framework/filters/HttpCacheTest.php | 21 +- tests/framework/filters/PageCacheTest.php | 59 +- tests/framework/filters/RateLimiterTest.php | 23 +- tests/framework/filters/auth/AuthMethodTest.php | 11 +- tests/framework/filters/auth/AuthTest.php | 35 +- tests/framework/filters/auth/CompositeAuthTest.php | 25 +- tests/framework/filters/stubs/MockAuthManager.php | 13 +- tests/framework/filters/stubs/RateLimit.php | 8 +- tests/framework/filters/stubs/UserIdentity.php | 7 +- tests/framework/grid/ActionColumnTest.php | 24 +- tests/framework/grid/CheckboxColumnTest.php | 8 +- tests/framework/grid/DataColumnTest.php | 25 +- tests/framework/grid/GridViewTest.php | 14 +- tests/framework/grid/RadiobuttonColumnTest.php | 23 +- tests/framework/helpers/ArrayHelperTest.php | 107 +- tests/framework/helpers/ConsoleTest.php | 17 +- tests/framework/helpers/FallbackInflector.php | 9 +- tests/framework/helpers/FileHelperTest.php | 61 +- tests/framework/helpers/FormatConverterTest.php | 5 + tests/framework/helpers/HtmlTest.php | 177 ++-- tests/framework/helpers/InflectorTest.php | 25 +- tests/framework/helpers/JsonTest.php | 20 +- tests/framework/helpers/MarkdownTest.php | 8 +- tests/framework/helpers/StringHelperTest.php | 54 +- tests/framework/helpers/UrlTest.php | 10 +- tests/framework/helpers/VarDumperTest.php | 28 +- tests/framework/i18n/DbMessageSourceTest.php | 13 +- .../i18n/FallbackMessageFormatterTest.php | 72 +- tests/framework/i18n/FormatterDateTest.php | 75 +- tests/framework/i18n/FormatterNumberTest.php | 343 +++---- tests/framework/i18n/FormatterTest.php | 15 +- tests/framework/i18n/GettextMessageSourceTest.php | 5 + tests/framework/i18n/GettextMoFileTest.php | 11 +- tests/framework/i18n/GettextPoFileTest.php | 12 +- tests/framework/i18n/I18NTest.php | 18 +- tests/framework/i18n/IntlTestHelper.php | 8 +- tests/framework/i18n/MessageFormatterTest.php | 130 +-- tests/framework/log/DbTargetTest.php | 14 +- tests/framework/log/DispatcherTest.php | 44 +- tests/framework/log/EmailTargetTest.php | 35 +- tests/framework/log/FileTargetTest.php | 16 +- tests/framework/log/LoggerTest.php | 107 +- tests/framework/log/MySQLTargetTest.php | 8 +- tests/framework/log/PgSQLTargetTest.php | 9 +- tests/framework/log/SqliteTargetTest.php | 9 +- tests/framework/log/SyslogTargetTest.php | 29 +- tests/framework/log/TargetTest.php | 8 +- tests/framework/mail/BaseMailerTest.php | 35 +- tests/framework/mail/BaseMessageTest.php | 53 +- tests/framework/mutex/FileMutexTest.php | 7 +- tests/framework/mutex/MutexTestTrait.php | 9 +- tests/framework/mutex/MysqlMutexTest.php | 8 +- tests/framework/mutex/PgsqlMutexTest.php | 8 +- tests/framework/rbac/ActionRule.php | 5 + tests/framework/rbac/AuthorRule.php | 6 + tests/framework/rbac/DbManagerTestCase.php | 10 +- tests/framework/rbac/ExposedPhpManager.php | 8 +- tests/framework/rbac/ManagerTestCase.php | 11 +- tests/framework/rbac/MySQLManagerCacheTest.php | 8 +- tests/framework/rbac/MySQLManagerTest.php | 7 +- tests/framework/rbac/PgSQLManagerCacheTest.php | 9 +- tests/framework/rbac/PgSQLManagerTest.php | 6 + tests/framework/rbac/PhpManagerTest.php | 11 +- tests/framework/rbac/SqliteManagerTest.php | 6 + .../requirements/YiiRequirementCheckerTest.php | 19 +- tests/framework/rest/SerializerTest.php | 48 +- tests/framework/rest/UrlRuleTest.php | 190 ++-- tests/framework/test/ActiveFixtureTest.php | 12 +- tests/framework/test/ArrayFixtureTest.php | 4 +- tests/framework/test/data/array_fixture.php | 5 + tests/framework/test/data/customer.php | 9 +- tests/framework/test/data/profile.php | 5 + .../framework/validators/BooleanValidatorTest.php | 23 +- .../framework/validators/CompareValidatorTest.php | 29 +- tests/framework/validators/DateValidatorTest.php | 98 +- .../validators/DefaultValueValidatorTest.php | 9 +- tests/framework/validators/EachValidatorTest.php | 15 +- tests/framework/validators/EmailValidatorTest.php | 8 +- tests/framework/validators/ExistValidatorTest.php | 5 + tests/framework/validators/FileValidatorTest.php | 39 +- tests/framework/validators/FilterValidatorTest.php | 10 +- tests/framework/validators/IpValidatorTest.php | 22 +- tests/framework/validators/NumberValidatorTest.php | 20 +- tests/framework/validators/RangeValidatorTest.php | 38 +- .../validators/RegularExpressionValidatorTest.php | 7 +- .../framework/validators/RequiredValidatorTest.php | 16 +- tests/framework/validators/StringValidatorTest.php | 11 +- tests/framework/validators/UniqueValidatorTest.php | 21 +- tests/framework/validators/UrlValidatorTest.php | 21 +- tests/framework/validators/ValidatorTest.php | 5 + tests/framework/web/AssetBundleTest.php | 44 +- tests/framework/web/AssetConverterTest.php | 4 +- tests/framework/web/CacheSessionTest.php | 5 + tests/framework/web/ControllerTest.php | 7 +- tests/framework/web/DbSessionTest.php | 15 +- tests/framework/web/ErrorActionTest.php | 9 +- tests/framework/web/ErrorHandlerTest.php | 21 +- tests/framework/web/FakeController.php | 1 - tests/framework/web/FormatterTest.php | 10 +- tests/framework/web/GroupUrlRuleTest.php | 21 +- tests/framework/web/JsonResponseFormatterTest.php | 54 +- .../framework/web/MultipartFormDataParserTest.php | 15 +- tests/framework/web/Post.php | 8 +- tests/framework/web/RequestTest.php | 8 +- tests/framework/web/ResponseTest.php | 24 +- tests/framework/web/SessionTest.php | 5 + tests/framework/web/UploadedFileTest.php | 13 +- tests/framework/web/UrlManagerCreateUrlTest.php | 11 +- tests/framework/web/UrlManagerParseUrlTest.php | 34 +- tests/framework/web/UrlManagerTest.php | 10 +- tests/framework/web/UrlRuleTest.php | 47 +- tests/framework/web/UserTest.php | 36 +- tests/framework/web/ViewTest.php | 22 +- tests/framework/web/XmlResponseFormatterTest.php | 10 +- tests/framework/web/stubs/CachedUrlRule.php | 5 + tests/framework/web/stubs/ModelStub.php | 5 + tests/framework/web/stubs/VendorImage.php | 8 +- tests/framework/widgets/ActiveFieldTest.php | 52 +- tests/framework/widgets/ActiveFormTest.php | 6 +- tests/framework/widgets/BreadcrumbsTest.php | 15 +- tests/framework/widgets/DetailViewTest.php | 22 +- tests/framework/widgets/FragmentCacheTest.php | 23 +- tests/framework/widgets/LinkPagerTest.php | 17 +- tests/framework/widgets/LinkSorterTest.php | 10 +- tests/framework/widgets/ListViewTest.php | 12 +- tests/framework/widgets/MenuTest.php | 75 +- tests/framework/widgets/PjaxTest.php | 6 +- tests/framework/widgets/SpacelessTest.php | 7 +- 504 files changed, 5790 insertions(+), 2890 deletions(-) create mode 100644 .php_cs create mode 100644 cs/TODO.md create mode 100644 cs/src/YiiConfig.php create mode 100644 cs/src/YiisoftConfig.php diff --git a/.php_cs b/.php_cs new file mode 100644 index 0000000..d98e72f --- /dev/null +++ b/.php_cs @@ -0,0 +1,29 @@ +setCacheFile(__DIR__ . '/tests/runtime/php_cs.cache') + ->mergeRules([ + 'braces' => [ + 'allow_single_line_closure' => true, + ], + ]) + ->setFinder( + PhpCsFixer\Finder::create() + ->in(__DIR__) + ->exclude('docs') + ->exclude('apps') + ->exclude('extensions') + // requirement checker should work even on PHP 4.3, so it needs special treatment + ->exclude('framework/requirements') + ->notPath('framework/classes.php') + ->notPath('framework/helpers/mimeTypes.php') + ->notPath('framework/views/messageConfig.php') + // temporary disable messages processing - conflicts with header fixer + ->exclude('framework/messages') + ); diff --git a/.travis.yml b/.travis.yml index 47df824..9b1e881 100644 --- a/.travis.yml +++ b/.travis.yml @@ -23,17 +23,54 @@ sudo: false language: php -php: - - 5.4 - - 5.5 - - 5.6 - - 7.0 - - 7.1 - - nightly +env: + global: + - DEFAULT_COMPOSER_FLAGS="--prefer-dist --no-interaction --no-progress --optimize-autoloader" + - TASK_TESTS_PHP=1 + - TASK_TESTS_JS=0 + - TASK_TESTS_CS=0 + - TASK_TESTS_COVERAGE=0 + + +services: + - memcached + - mysql + - postgresql + +# cache vendor dirs +cache: + directories: + - vendor + - $HOME/.composer/cache + - $HOME/.npm + +# try running against postgres 9.3 +addons: + postgresql: "9.3" + code_climate: + repo_token: 2935307212620b0e2228ab67eadd92c9f5501ddb60549d0d86007a354d56915b matrix: fast_finish: true include: + # test coding standards + - php: 7.1 + env: TASK_TESTS_PHP=0 TASK_TESTS_CS=1 + # overwrite services used for PHP tests + services: + + # run tests coverage on PHP 7.1 + - php: 7.1 + env: TASK_TESTS_COVERAGE=1 + + - php: 7.0 + + - php: 5.6 + + - php: 5.5 + + - php: 5.4 + # Test against HHVM 3.12 LTS version by using trusty - php: hhvm-3.12 sudo: true @@ -49,6 +86,7 @@ matrix: - mysql-client-5.6 services: - mysql + # test against the latest HHVM version by using a newer image - php: hhvm sudo: true @@ -66,98 +104,111 @@ matrix: services: - mysql - postgresql + + - php: nightly + # have a separate branch for javascript tests - language: node_js node_js: 6 + env: TASK_TESTS_PHP=0 TASK_TESTS_JS=1 dist: trusty - # overwrite php related settings - php: + # overwrite services used for PHP tests services: - addons: - install: - - travis_retry npm install - # disable xdebug for performance in composer - - phpenv config-rm xdebug.ini || echo "xdebug is not installed" - - travis_retry composer self-update && composer --version - - travis_retry composer install --prefer-dist --no-interaction - before_script: - - node --version - - npm --version - - php --version - - composer --version - script: npm test - after_script: allow_failures: - php: nightly +install: + - | + if [[ $TASK_TESTS_COVERAGE != 1 && $TRAVIS_PHP_VERSION != hhv* ]]; then + # disable xdebug for performance reasons when code coverage is not needed. note: xdebug on hhvm is disabled by default + phpenv config-rm xdebug.ini || echo "xdebug is not installed" + fi -services: - - memcached - - mysql - - postgresql - -# cache vendor dirs -cache: - directories: - - vendor - - $HOME/.composer/cache - - $HOME/.npm + # install composer dependencies + - travis_retry composer self-update + - export PATH="$HOME/.composer/vendor/bin:$PATH" + - | + if [[ $TRAVIS_PHP_VERSION == "hhvm-3.12" ]]; then + # remove php-cs-fixer from composer dependencies on hhvm-3.12 - php-cs-fixer requires at least hhvm-3.18 + composer remove friendsofphp/php-cs-fixer --dev + fi + - travis_retry composer install $DEFAULT_COMPOSER_FLAGS -# try running against postgres 9.3 -addons: - postgresql: "9.3" - code_climate: - repo_token: 2935307212620b0e2228ab67eadd92c9f5501ddb60549d0d86007a354d56915b + # setup PHP extension + - | + if [ $TASK_TESTS_PHP == 1 ]; then + tests/data/travis/apc-setup.sh + tests/data/travis/memcache-setup.sh + tests/data/travis/imagick-setup.sh + fi -install: + # setup JS test - | - if [[ $TRAVIS_PHP_VERSION != '7.1' && $TRAVIS_PHP_VERSION != hhv* ]]; then - # disable xdebug for performance reasons when code coverage is not needed. note: xdebug on hhvm is disabled by default - phpenv config-rm xdebug.ini || echo "xdebug is not installed" + if [ $TASK_TESTS_JS == 1 ]; then + travis_retry npm install fi - - travis_retry composer self-update && composer --version - - export PATH="$HOME/.composer/vendor/bin:$PATH" - # core framework: - - travis_retry composer install --prefer-dist --no-interaction - - tests/data/travis/apc-setup.sh - - tests/data/travis/memcache-setup.sh - - tests/data/travis/imagick-setup.sh before_script: # Disable the HHVM JIT for faster Unit Testing - if [[ $TRAVIS_PHP_VERSION = hhv* ]]; then echo 'hhvm.jit = 0' >> /etc/hhvm/php.ini; fi + # show some versions and env information - - php -r "echo INTL_ICU_VERSION . \"\n\";" - - php -r "echo INTL_ICU_DATA_VERSION . \"\n\";" - - mysql --version - - psql --version + - php --version + - composer --version + - | + if [ $TASK_TESTS_PHP == 1 ]; then + php -r "echo INTL_ICU_VERSION . \"\n\";" + php -r "echo INTL_ICU_DATA_VERSION . \"\n\";" + psql --version + mysql --version + fi + - | + if [ $TASK_TESTS_JS == 1 ]; then + node --version + npm --version + fi # initialize databases - - travis_retry mysql -e 'CREATE DATABASE `yiitest`;'; - - mysql -e "CREATE USER 'travis'@'localhost' IDENTIFIED WITH mysql_native_password;"; - - mysql -e "GRANT ALL PRIVILEGES ON *.* TO 'travis'@'localhost' WITH GRANT OPTION;"; - - psql -U postgres -c 'CREATE DATABASE yiitest;'; + - | + if [ $TASK_TESTS_PHP == 1 ]; then + travis_retry mysql -e 'CREATE DATABASE `yiitest`;'; + mysql -e "CREATE USER 'travis'@'localhost' IDENTIFIED WITH mysql_native_password;"; + mysql -e "GRANT ALL PRIVILEGES ON *.* TO 'travis'@'localhost' WITH GRANT OPTION;"; + psql -U postgres -c 'CREATE DATABASE yiitest;'; + fi - # enable code coverage on PHP 7.1, only one PHP version needs to generate coverage data + # enable code coverage - | - if [ $TRAVIS_PHP_VERSION = '7.1' ]; then + if [ $TASK_TESTS_COVERAGE == 1 ]; then PHPUNIT_FLAGS="--coverage-clover=coverage.clover" fi script: - # ensure no files contain UTF-8 byte order mark - - if ! grep -rlI $'\xEF\xBB\xBF' framework/ ; then echo "no utf8 BOM found"; else echo "found utf8 BOM in some files. See above."; exit 1; fi - # validate composer.json - - composer validate --no-check-lock - - cd framework && composer validate --no-check-lock && cd .. - # run PHPUnit - - vendor/bin/phpunit --verbose $PHPUNIT_FLAGS --exclude-group mssql,oci,wincache,xcache,zenddata,cubrid + # test coding standards + - | + if [ $TASK_TESTS_CS == 1 ]; then + composer validate --no-check-lock + cd framework && composer validate --no-check-lock && cd .. + vendor/bin/php-cs-fixer --diff --dry-run -v fix + fi + + # PHP tests + - | + if [ $TASK_TESTS_PHP == 1 ]; then + vendor/bin/phpunit --verbose $PHPUNIT_FLAGS --exclude-group mssql,oci,wincache,xcache,zenddata,cubrid + fi + + # JS tests + - | + if [ $TASK_TESTS_JS == 1 ]; then + npm test + fi after_script: - | - if [ $TRAVIS_PHP_VERSION = '7.1' ]; then + if [ $TASK_TESTS_COVERAGE == 1 ]; then travis_retry wget https://scrutinizer-ci.com/ocular.phar php ocular.phar code-coverage:upload --format=php-clover coverage.clover fi diff --git a/build/controllers/PhpDocController.php b/build/controllers/PhpDocController.php index bb01fa5..d4284e8 100644 --- a/build/controllers/PhpDocController.php +++ b/build/controllers/PhpDocController.php @@ -103,7 +103,6 @@ class PhpDocController extends Controller $this->stdout("\nParsed $nFilesTotal files.\n"); $this->stdout("Updated $nFilesUpdated files.\n"); - } /** @@ -173,7 +172,6 @@ class PhpDocController extends Controller } } } elseif (preg_match('~extensions/([\w-]+)[\\\\/]?$~', $root, $matches)) { - $extensionPath = dirname(rtrim($root, '\\/')); $this->setUpExtensionAliases($extensionPath); @@ -197,7 +195,6 @@ class PhpDocController extends Controller // return []; // } } elseif (preg_match('~apps/([\w-]+)[\\\\/]?$~', $root, $matches)) { - $extensionPath = dirname(dirname(rtrim($root, '\\/'))) . '/extensions'; $this->setUpExtensionAliases($extensionPath); @@ -211,20 +208,19 @@ class PhpDocController extends Controller $except[] = '/vendor/'; $except[] = '/tests/'; $except[] = '/docs/'; - } $root = FileHelper::normalizePath($root); $options = [ 'filter' => function ($path) { - if (is_file($path)) { - $file = basename($path); - if ($file[0] < 'A' || $file[0] > 'Z') { - return false; - } + if (is_file($path)) { + $file = basename($path); + if ($file[0] < 'A' || $file[0] > 'Z') { + return false; } + } - return null; - }, + return null; + }, 'only' => ['*.php'], 'except' => array_merge($except, [ '.git/', @@ -274,15 +270,15 @@ class PhpDocController extends Controller $contentAfterNamespace--; } $lines = array_merge([ - " $type) { switch ($type) { @@ -412,7 +408,7 @@ class PhpDocController extends Controller // check for multi line array if ($level > 0) { - ${'endof'.$property} = $i; + ${'endof' . $property} = $i; } $line = trim($line); @@ -448,8 +444,8 @@ class PhpDocController extends Controller $endofAll = false; foreach (['Private', 'Protected', 'Public', 'Const', 'Use'] as $var) { - if (${'endof'.$var} !== false) { - $endofAll = ${'endof'.$var}; + if (${'endof' . $var} !== false) { + $endofAll = ${'endof' . $var}; break; } } @@ -531,7 +527,6 @@ class PhpDocController extends Controller } if (trim($oldDoc) != trim($newDoc)) { - $fileContent = explode("\n", file_get_contents($file)); $start = $ref->getStartLine() - 2; $docStart = $start - count(explode("\n", $oldDoc)) + 1; @@ -621,8 +616,8 @@ class PhpDocController extends Controller protected function generateClassPropertyDocs($fileName) { - $phpdoc = ""; - $file = str_replace("\r", "", str_replace("\t", " ", file_get_contents($fileName, true))); + $phpdoc = ''; + $file = str_replace("\r", '', str_replace("\t", ' ', file_get_contents($fileName, true))); $ns = $this->match('#\nnamespace (?[\w\\\\]+);\n#', $file); $namespace = reset($ns); $namespace = $namespace['name']; @@ -655,7 +650,6 @@ class PhpDocController extends Controller $className = null; foreach ($classes as &$class) { - $className = $namespace . '\\' . $class['name']; $gets = $this->match( @@ -756,9 +750,11 @@ class PhpDocController extends Controller foreach ($parts as $part) { preg_match_all($pattern . 'suU', $part, $matches, PREG_SET_ORDER); foreach ($matches as &$set) { - foreach ($set as $i => $match) - if (is_numeric($i) /*&& $i != 0*/) + foreach ($set as $i => $match) { + if (is_numeric($i) /*&& $i != 0*/) { unset($set[$i]); + } + } $sets[] = $set; } @@ -769,8 +765,9 @@ class PhpDocController extends Controller protected function fixSentence($str) { // TODO fix word wrap - if ($str == '') + if ($str == '') { return ''; + } return strtoupper(substr($str, 0, 1)) . substr($str, 1) . ($str[strlen($str) - 1] != '.' ? '.' : ''); } diff --git a/build/controllers/ReleaseController.php b/build/controllers/ReleaseController.php index 06674a3..7158d5c 100644 --- a/build/controllers/ReleaseController.php +++ b/build/controllers/ReleaseController.php @@ -127,10 +127,9 @@ class ReleaseController extends Controller $w = $this->minWidth(array_keys($versions)); $this->stdout(str_repeat(' ', $w + 2) . "Current Version Next Version\n", Console::BOLD); foreach ($versions as $ext => $version) { - $this->stdout($ext . str_repeat(' ', $w + 3 - mb_strlen($ext)) . $version . ""); + $this->stdout($ext . str_repeat(' ', $w + 3 - mb_strlen($ext)) . $version . ''); $this->stdout(str_repeat(' ', 17 - mb_strlen($version)) . $nextVersions[$ext] . "\n"); } - } private function minWidth($a) @@ -219,7 +218,7 @@ class ReleaseController extends Controller $this->stdout("- are all new `@since` tags for this release version?\n"); } $this->stdout("- other issues with code changes?\n\n git diff -w $gitVersion.. ${gitDir}\n\n"); - $travisUrl = reset($what) === 'framework' ? '' : '-'.reset($what); + $travisUrl = reset($what) === 'framework' ? '' : '-' . reset($what); $this->stdout("- are unit tests passing on travis? https://travis-ci.org/yiisoft/yii2$travisUrl/builds\n"); $this->stdout("- also make sure the milestone on github is complete and no issues or PRs are left open.\n\n"); $this->printWhatUrls($what, $versions); @@ -266,15 +265,15 @@ class ReleaseController extends Controller $this->stdout("You are about to generate packages for the following things:\n\n"); foreach ($what as $ext) { if (strncmp('app-', $ext, 4) === 0) { - $this->stdout(" - "); + $this->stdout(' - '); $this->stdout(substr($ext, 4), Console::FG_RED); - $this->stdout(" application version "); + $this->stdout(' application version '); } elseif ($ext === 'framework') { - $this->stdout(" - Yii Framework version "); + $this->stdout(' - Yii Framework version '); } else { - $this->stdout(" - "); + $this->stdout(' - '); $this->stdout($ext, Console::FG_RED); - $this->stdout(" extension version "); + $this->stdout(' extension version '); } $this->stdout($versions[$ext], Console::BOLD); $this->stdout("\n"); @@ -323,9 +322,9 @@ class ReleaseController extends Controller $version = array_values($this->getNextVersions($this->getCurrentVersions($what), self::PATCH))[0]; $this->stdout('sorting CHANGELOG of '); $this->stdout(reset($what), Console::BOLD); - $this->stdout(" for version "); + $this->stdout(' for version '); $this->stdout($version, Console::BOLD); - $this->stdout("..."); + $this->stdout('...'); $this->resortChangelogs($what, $version); @@ -336,15 +335,15 @@ class ReleaseController extends Controller { foreach ($what as $ext) { if (strncmp('app-', $ext, 4) === 0) { - $this->stdout(" - "); + $this->stdout(' - '); $this->stdout(substr($ext, 4), Console::FG_RED); - $this->stdout(" application version "); + $this->stdout(' application version '); } elseif ($ext === 'framework') { - $this->stdout(" - Yii Framework version "); + $this->stdout(' - Yii Framework version '); } else { - $this->stdout(" - "); + $this->stdout(' - '); $this->stdout($ext, Console::FG_RED); - $this->stdout(" extension version "); + $this->stdout(' extension version '); } $this->stdout($newVersions[$ext], Console::BOLD); $this->stdout(", last release was {$versions[$ext]}\n"); @@ -375,7 +374,7 @@ class ReleaseController extends Controller foreach ($what as $w) { if (strncmp('app-', $w, 4) === 0) { if (!empty($limit) && !in_array('app', $limit)) { - throw new Exception("Only the following types are allowed: ".implode(', ', $limit)."\n"); + throw new Exception('Only the following types are allowed: ' . implode(', ', $limit) . "\n"); } if (!is_dir($appPath = "{$this->basePath}/apps/" . substr($w, 4))) { throw new Exception("Application path does not exist: \"{$appPath}\"\n"); @@ -385,7 +384,7 @@ class ReleaseController extends Controller } } elseif ($w === 'framework') { if (!empty($limit) && !in_array('framework', $limit)) { - throw new Exception("Only the following types are allowed: ".implode(', ', $limit)."\n"); + throw new Exception('Only the following types are allowed: ' . implode(', ', $limit) . "\n"); } if (!is_dir($fwPath = "{$this->basePath}/framework")) { throw new Exception("Framework path does not exist: \"{$this->basePath}/framework\"\n"); @@ -395,7 +394,7 @@ class ReleaseController extends Controller } } else { if (!empty($limit) && !in_array('ext', $limit)) { - throw new Exception("Only the following types are allowed: ".implode(', ', $limit)."\n"); + throw new Exception('Only the following types are allowed: ' . implode(', ', $limit) . "\n"); } if (!is_dir($extPath = "{$this->basePath}/extensions/$w")) { throw new Exception("Extension path for \"$w\" does not exist: \"{$this->basePath}/extensions/$w\"\n"); @@ -457,10 +456,10 @@ class ReleaseController extends Controller $this->stdout("\nIn the following you can check the above changes using git diff.\n\n"); do { - $this->runGit("git diff --color", $frameworkPath); + $this->runGit('git diff --color', $frameworkPath); $this->stdout("\n\n\nCheck whether the above diff is okay, if not you may change things as needed before continuing.\n"); $this->stdout("You may abort the program with Ctrl + C and reset the changes by running `git checkout -- .` in the repo.\n\n"); - } while (!$this->confirm("Type `yes` to continue, `no` to view git diff again. Continue?")); + } while (!$this->confirm('Type `yes` to continue, `no` to view git diff again. Continue?')); $this->stdout("\n\n"); $this->stdout(" **** RELEASE TIME! ****\n", Console::FG_YELLOW, Console::BOLD); @@ -471,13 +470,13 @@ class ReleaseController extends Controller $this->runGit("git commit -S -a -m \"release version $version\"", $frameworkPath); $this->runGit("git tag -s $version -m \"version $version\"", $frameworkPath); - $this->runGit("git push", $frameworkPath); - $this->runGit("git push --tags", $frameworkPath); + $this->runGit('git push', $frameworkPath); + $this->runGit('git push --tags', $frameworkPath); $this->stdout("\n\n"); - $this->stdout("CONGRATULATIONS! You have just released ", Console::FG_YELLOW, Console::BOLD); + $this->stdout('CONGRATULATIONS! You have just released ', Console::FG_YELLOW, Console::BOLD); $this->stdout('framework', Console::FG_RED, Console::BOLD); - $this->stdout(" version ", Console::FG_YELLOW, Console::BOLD); + $this->stdout(' version ', Console::FG_YELLOW, Console::BOLD); $this->stdout($version, Console::BOLD); $this->stdout("!\n\n", Console::FG_YELLOW, Console::BOLD); @@ -519,10 +518,10 @@ class ReleaseController extends Controller $this->stdout("\n"); - $this->runGit("git diff --color", $frameworkPath); + $this->runGit('git diff --color', $frameworkPath); $this->stdout("\n\n"); - $this->runGit("git commit -a -m \"prepare for next release\"", $frameworkPath); - $this->runGit("git push", $frameworkPath); + $this->runGit('git commit -a -m "prepare for next release"', $frameworkPath); + $this->runGit('git push', $frameworkPath); $this->stdout("\n\nDONE!", Console::FG_YELLOW, Console::BOLD); @@ -544,7 +543,6 @@ class ReleaseController extends Controller $this->stdout("- release applications: ./build/build release app-advanced\n"); $this->stdout("\n"); - } protected function releaseApplication($name, $path, $version) @@ -578,10 +576,10 @@ class ReleaseController extends Controller $this->stdout("\nIn the following you can check the above changes using git diff.\n\n"); do { - $this->runGit("git diff --color", $path); + $this->runGit('git diff --color', $path); $this->stdout("\n\n\nCheck whether the above diff is okay, if not you may change things as needed before continuing.\n"); $this->stdout("You may abort the program with Ctrl + C and reset the changes by running `git checkout -- .` in the repo.\n\n"); - } while (!$this->confirm("Type `yes` to continue, `no` to view git diff again. Continue?")); + } while (!$this->confirm('Type `yes` to continue, `no` to view git diff again. Continue?')); $this->stdout("\n\n"); $this->stdout(" **** RELEASE TIME! ****\n", Console::FG_YELLOW, Console::BOLD); @@ -592,13 +590,13 @@ class ReleaseController extends Controller $this->runGit("git commit -S -a -m \"release version $version\"", $path); $this->runGit("git tag -s $version -m \"version $version\"", $path); - $this->runGit("git push", $path); - $this->runGit("git push --tags", $path); + $this->runGit('git push', $path); + $this->runGit('git push --tags', $path); $this->stdout("\n\n"); - $this->stdout("CONGRATULATIONS! You have just released application ", Console::FG_YELLOW, Console::BOLD); + $this->stdout('CONGRATULATIONS! You have just released application ', Console::FG_YELLOW, Console::BOLD); $this->stdout($name, Console::FG_RED, Console::BOLD); - $this->stdout(" version ", Console::FG_YELLOW, Console::BOLD); + $this->stdout(' version ', Console::FG_YELLOW, Console::BOLD); $this->stdout($version, Console::BOLD); $this->stdout("!\n\n", Console::FG_YELLOW, Console::BOLD); @@ -613,10 +611,10 @@ class ReleaseController extends Controller $nextVersion = $this->getNextVersions(["app-$name" => $version], self::PATCH); // TODO support other versions $this->stdout("\n"); - $this->runGit("git diff --color", $path); + $this->runGit('git diff --color', $path); $this->stdout("\n\n"); - $this->runGit("git commit -a -m \"prepare for next release\"", $path); - $this->runGit("git push", $path); + $this->runGit('git commit -a -m "prepare for next release"', $path); + $this->runGit('git push', $path); $this->stdout("\n\nDONE!", Console::FG_YELLOW, Console::BOLD); @@ -696,10 +694,10 @@ class ReleaseController extends Controller $this->stdout("\nIn the following you can check the above changes using git diff.\n\n"); do { - $this->runGit("git diff --color", $path); + $this->runGit('git diff --color', $path); $this->stdout("\n\n\nCheck whether the above diff is okay, if not you may change things as needed before continuing.\n"); $this->stdout("You may abort the program with Ctrl + C and reset the changes by running `git checkout -- .` in the repo.\n\n"); - } while (!$this->confirm("Type `yes` to continue, `no` to view git diff again. Continue?")); + } while (!$this->confirm('Type `yes` to continue, `no` to view git diff again. Continue?')); $this->stdout("\n\n"); $this->stdout(" **** RELEASE TIME! ****\n", Console::FG_YELLOW, Console::BOLD); @@ -710,13 +708,13 @@ class ReleaseController extends Controller $this->runGit("git commit -S -a -m \"release version $version\"", $path); $this->runGit("git tag -s $version -m \"version $version\"", $path); - $this->runGit("git push", $path); - $this->runGit("git push --tags", $path); + $this->runGit('git push', $path); + $this->runGit('git push --tags', $path); $this->stdout("\n\n"); - $this->stdout("CONGRATULATIONS! You have just released extension ", Console::FG_YELLOW, Console::BOLD); + $this->stdout('CONGRATULATIONS! You have just released extension ', Console::FG_YELLOW, Console::BOLD); $this->stdout($name, Console::FG_RED, Console::BOLD); - $this->stdout(" version ", Console::FG_YELLOW, Console::BOLD); + $this->stdout(' version ', Console::FG_YELLOW, Console::BOLD); $this->stdout($version, Console::BOLD); $this->stdout("!\n\n", Console::FG_YELLOW, Console::BOLD); @@ -730,10 +728,10 @@ class ReleaseController extends Controller $this->stdout("done.\n", Console::FG_GREEN, Console::BOLD); $this->stdout("\n"); - $this->runGit("git diff --color", $path); + $this->runGit('git diff --color', $path); $this->stdout("\n\n"); - $this->runGit("git commit -a -m \"prepare for next release\"", $path); - $this->runGit("git push", $path); + $this->runGit('git commit -a -m "prepare for next release"', $path); + $this->runGit('git push', $path); $this->stdout("\n\nDONE!", Console::FG_YELLOW, Console::BOLD); @@ -815,7 +813,7 @@ class ReleaseController extends Controller $v = str_replace('\\-', '[\\- ]', preg_quote($version, '/')); $headline = $version . ' ' . date('F d, Y'); $this->sed( - '/'.$v.' under development\n(-+?)\n/', + '/' . $v . ' under development\n(-+?)\n/', $headline . "\n" . str_repeat('-', strlen($headline)) . "\n", $this->getChangelogs($what) ); @@ -862,11 +860,11 @@ class ReleaseController extends Controller $state = 'start'; foreach ($lines as $l => $line) { // starting from the changelogs headline - if (isset($lines[$l-2]) && strpos($lines[$l-2], $version) !== false && - isset($lines[$l-1]) && strncmp($lines[$l-1], '---', 3) === 0) { + if (isset($lines[$l - 2]) && strpos($lines[$l - 2], $version) !== false && + isset($lines[$l - 1]) && strncmp($lines[$l - 1], '---', 3) === 0) { $state = 'changelog'; } - if ($state === 'changelog' && isset($lines[$l+1]) && strncmp($lines[$l+1], '---', 3) === 0) { + if ($state === 'changelog' && isset($lines[$l + 1]) && strncmp($lines[$l + 1], '---', 3) === 0) { $state = 'end'; } // add continued lines to the last item to keep them together @@ -892,7 +890,7 @@ class ReleaseController extends Controller $changelog = array_filter($changelog); $i = 0; - ArrayHelper::multisort($changelog, function($line) use (&$i) { + ArrayHelper::multisort($changelog, function ($line) use (&$i) { if (preg_match('/^- (Chg|Enh|Bug|New)( #\d+(, #\d+)*)?: .+/', $line, $m)) { $o = ['Bug' => 'C', 'Enh' => 'D', 'Chg' => 'E', 'New' => 'F']; return $o[$m[1]] . ' ' . (!empty($m[2]) ? $m[2] : 'AAAA' . $i++); @@ -925,7 +923,7 @@ class ReleaseController extends Controller protected function getExtensionChangelogs($what) { - return array_filter(glob($this->basePath . '/extensions/*/CHANGELOG.md'), function($elem) use ($what) { + return array_filter(glob($this->basePath . '/extensions/*/CHANGELOG.md'), function ($elem) use ($what) { foreach ($what as $ext) { if (strpos($elem, "extensions/$ext/CHANGELOG.md") !== false) { return true; diff --git a/build/controllers/TranslationController.php b/build/controllers/TranslationController.php index 433c842..9adc9c9 100644 --- a/build/controllers/TranslationController.php +++ b/build/controllers/TranslationController.php @@ -113,7 +113,7 @@ class TranslationController extends Controller protected function getDiff($translatedFilePath, $sourceFilePath) { $lastTranslationHash = shell_exec('git log -1 --format=format:"%H" -- ' . $translatedFilePath); - return shell_exec('git diff ' . $lastTranslationHash.'..HEAD -- ' . $sourceFilePath); + return shell_exec('git diff ' . $lastTranslationHash . '..HEAD -- ' . $sourceFilePath); } /** diff --git a/build/controllers/Utf8Controller.php b/build/controllers/Utf8Controller.php index 4cf3cbd..76d4d18 100644 --- a/build/controllers/Utf8Controller.php +++ b/build/controllers/Utf8Controller.php @@ -40,14 +40,12 @@ class Utf8Controller extends Controller } foreach ($files as $file) { - $content = file_get_contents($file); $chars = preg_split('//u', $content, null, PREG_SPLIT_NO_EMPTY); $line = 1; $pos = 0; foreach ($chars as $c) { - $ord = $this->unicodeOrd($c); $pos++; @@ -57,7 +55,7 @@ class Utf8Controller extends Controller } if ($ord === false) { - $this->found("BROKEN UTF8", $c, $line, $pos, $file); + $this->found('BROKEN UTF8', $c, $line, $pos, $file); continue; } @@ -66,22 +64,20 @@ class Utf8Controller extends Controller || 0x2028 <= $ord && $ord <= 0x202E || 0x205f <= $ord && $ord <= 0x206F ) { - $this->found("UNSUPPORTED SPACE CHARACTER", $c, $line, $pos, $file); + $this->found('UNSUPPORTED SPACE CHARACTER', $c, $line, $pos, $file); continue; } if ($ord < 0x0020 && $ord != 0x000A && $ord != 0x0009 || 0x0080 <= $ord && $ord < 0x009F) { - $this->found("CONTROL CHARARCTER", $c, $line, $pos, $file); + $this->found('CONTROL CHARARCTER', $c, $line, $pos, $file); continue; } // if ($ord > 0x009F) { // $this->found("NON ASCII CHARARCTER", $c, $line, $pos, $file); // continue; // } - } } - } private $_foundFiles = []; @@ -95,7 +91,7 @@ class Utf8Controller extends Controller $hexcode = dechex($this->unicodeOrd($char)); $hexcode = str_repeat('0', max(4 - strlen($hexcode), 0)) . $hexcode; - + $this->stdout(" at $line:$pos FOUND $what: 0x$hexcode '$char' http://unicode-table.com/en/$hexcode/\n"); } @@ -109,20 +105,20 @@ class Utf8Controller extends Controller */ private function unicodeOrd($c) { - $h = ord($c{0}); + $h = ord($c[0]); if ($h <= 0x7F) { return $h; - } else if ($h < 0xC2) { + } elseif ($h < 0xC2) { return false; - } else if ($h <= 0xDF) { - return ($h & 0x1F) << 6 | (ord($c{1}) & 0x3F); - } else if ($h <= 0xEF) { - return ($h & 0x0F) << 12 | (ord($c{1}) & 0x3F) << 6 - | (ord($c{2}) & 0x3F); - } else if ($h <= 0xF4) { - return ($h & 0x0F) << 18 | (ord($c{1}) & 0x3F) << 12 - | (ord($c{2}) & 0x3F) << 6 - | (ord($c{3}) & 0x3F); + } elseif ($h <= 0xDF) { + return ($h & 0x1F) << 6 | (ord($c[1]) & 0x3F); + } elseif ($h <= 0xEF) { + return ($h & 0x0F) << 12 | (ord($c[1]) & 0x3F) << 6 + | (ord($c[2]) & 0x3F); + } elseif ($h <= 0xF4) { + return ($h & 0x0F) << 18 | (ord($c[1]) & 0x3F) << 12 + | (ord($c[2]) & 0x3F) << 6 + | (ord($c[3]) & 0x3F); } else { return false; } diff --git a/composer.json b/composer.json index 775c862..39f30b8 100644 --- a/composer.json +++ b/composer.json @@ -82,7 +82,8 @@ }, "require-dev": { "phpunit/phpunit": "~4.4", - "cebe/indent": "~1.0.2" + "cebe/indent": "~1.0.2", + "friendsofphp/php-cs-fixer": "~2.2.3" }, "repositories": [ { @@ -95,7 +96,8 @@ }, "autoload": { "psr-4": { - "yii\\": "framework/" + "yii\\": "framework/", + "yii\\cs\\": "cs/src/" } }, "config": { diff --git a/composer.lock b/composer.lock index 5e7bbfa..e1bd146 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", "This file is @generated automatically" ], - "content-hash": "d33a8eeb49ce13a2e319e70d8d4a2f67", + "content-hash": "e53ec45854ce009b7bc979db8ebc24cc", "packages": [ { "name": "bower-asset/jquery", @@ -335,6 +335,74 @@ "time": "2014-05-23T14:40:08+00:00" }, { + "name": "doctrine/annotations", + "version": "v1.2.7", + "source": { + "type": "git", + "url": "https://github.com/doctrine/annotations.git", + "reference": "f25c8aab83e0c3e976fd7d19875f198ccf2f7535" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/annotations/zipball/f25c8aab83e0c3e976fd7d19875f198ccf2f7535", + "reference": "f25c8aab83e0c3e976fd7d19875f198ccf2f7535", + "shasum": "" + }, + "require": { + "doctrine/lexer": "1.*", + "php": ">=5.3.2" + }, + "require-dev": { + "doctrine/cache": "1.*", + "phpunit/phpunit": "4.*" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.3.x-dev" + } + }, + "autoload": { + "psr-0": { + "Doctrine\\Common\\Annotations\\": "lib/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Roman Borschel", + "email": "roman@code-factory.org" + }, + { + "name": "Benjamin Eberlei", + "email": "kontakt@beberlei.de" + }, + { + "name": "Guilherme Blanco", + "email": "guilhermeblanco@gmail.com" + }, + { + "name": "Jonathan Wage", + "email": "jonwage@gmail.com" + }, + { + "name": "Johannes Schmitt", + "email": "schmittjoh@gmail.com" + } + ], + "description": "Docblock Annotations Parser", + "homepage": "http://www.doctrine-project.org", + "keywords": [ + "annotations", + "docblock", + "parser" + ], + "time": "2015-08-31T12:32:49+00:00" + }, + { "name": "doctrine/instantiator", "version": "1.0.5", "source": { @@ -389,6 +457,227 @@ "time": "2015-06-14T21:17:01+00:00" }, { + "name": "doctrine/lexer", + "version": "v1.0.1", + "source": { + "type": "git", + "url": "https://github.com/doctrine/lexer.git", + "reference": "83893c552fd2045dd78aef794c31e694c37c0b8c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/lexer/zipball/83893c552fd2045dd78aef794c31e694c37c0b8c", + "reference": "83893c552fd2045dd78aef794c31e694c37c0b8c", + "shasum": "" + }, + "require": { + "php": ">=5.3.2" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-0": { + "Doctrine\\Common\\Lexer\\": "lib/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Roman Borschel", + "email": "roman@code-factory.org" + }, + { + "name": "Guilherme Blanco", + "email": "guilhermeblanco@gmail.com" + }, + { + "name": "Johannes Schmitt", + "email": "schmittjoh@gmail.com" + } + ], + "description": "Base library for a lexer that can be used in Top-Down, Recursive Descent Parsers.", + "homepage": "http://www.doctrine-project.org", + "keywords": [ + "lexer", + "parser" + ], + "time": "2014-09-09T13:34:57+00:00" + }, + { + "name": "friendsofphp/php-cs-fixer", + "version": "v2.2.3", + "source": { + "type": "git", + "url": "https://github.com/FriendsOfPHP/PHP-CS-Fixer.git", + "reference": "8f33cf3da0da94b67b9cd696b2b9dda81c928f72" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/FriendsOfPHP/PHP-CS-Fixer/zipball/8f33cf3da0da94b67b9cd696b2b9dda81c928f72", + "reference": "8f33cf3da0da94b67b9cd696b2b9dda81c928f72", + "shasum": "" + }, + "require": { + "doctrine/annotations": "^1.2", + "ext-tokenizer": "*", + "php": "^5.3.6 || >=7.0 <7.2", + "sebastian/diff": "^1.4", + "symfony/console": "^2.4 || ^3.0", + "symfony/event-dispatcher": "^2.1 || ^3.0", + "symfony/filesystem": "^2.4 || ^3.0", + "symfony/finder": "^2.2 || ^3.0", + "symfony/options-resolver": "^2.6 || ^3.0", + "symfony/polyfill-php54": "^1.0", + "symfony/polyfill-php55": "^1.3", + "symfony/polyfill-php70": "^1.0", + "symfony/polyfill-xml": "^1.3", + "symfony/process": "^2.3 || ^3.0", + "symfony/stopwatch": "^2.5 || ^3.0" + }, + "conflict": { + "hhvm": "<3.18" + }, + "require-dev": { + "gecko-packages/gecko-php-unit": "^2.0", + "justinrainbow/json-schema": "^5.0", + "phpunit/phpunit": "^4.5 || ^5.0", + "satooshi/php-coveralls": "^1.0", + "symfony/phpunit-bridge": "^3.2.2" + }, + "suggest": { + "ext-mbstring": "For handling non-UTF8 characters in cache signature.", + "ext-xml": "For better performance.", + "symfony/polyfill-mbstring": "When enabling `ext-mbstring` is not possible." + }, + "bin": [ + "php-cs-fixer" + ], + "type": "application", + "extra": { + "branch-alias": { + "dev-master": "2.2-dev" + } + }, + "autoload": { + "psr-4": { + "PhpCsFixer\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Dariusz Rumiński", + "email": "dariusz.ruminski@gmail.com" + }, + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + } + ], + "description": "A tool to automatically fix PHP code style", + "time": "2017-04-25T20:39:28+00:00" + }, + { + "name": "ircmaxell/password-compat", + "version": "v1.0.4", + "source": { + "type": "git", + "url": "https://github.com/ircmaxell/password_compat.git", + "reference": "5c5cde8822a69545767f7c7f3058cb15ff84614c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ircmaxell/password_compat/zipball/5c5cde8822a69545767f7c7f3058cb15ff84614c", + "reference": "5c5cde8822a69545767f7c7f3058cb15ff84614c", + "shasum": "" + }, + "require-dev": { + "phpunit/phpunit": "4.*" + }, + "type": "library", + "autoload": { + "files": [ + "lib/password.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Anthony Ferrara", + "email": "ircmaxell@php.net", + "homepage": "http://blog.ircmaxell.com" + } + ], + "description": "A compatibility library for the proposed simplified password hashing algorithm: https://wiki.php.net/rfc/password_hash", + "homepage": "https://github.com/ircmaxell/password_compat", + "keywords": [ + "hashing", + "password" + ], + "time": "2014-11-20T16:49:30+00:00" + }, + { + "name": "paragonie/random_compat", + "version": "v2.0.10", + "source": { + "type": "git", + "url": "https://github.com/paragonie/random_compat.git", + "reference": "634bae8e911eefa89c1abfbf1b66da679ac8f54d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/paragonie/random_compat/zipball/634bae8e911eefa89c1abfbf1b66da679ac8f54d", + "reference": "634bae8e911eefa89c1abfbf1b66da679ac8f54d", + "shasum": "" + }, + "require": { + "php": ">=5.2.0" + }, + "require-dev": { + "phpunit/phpunit": "4.*|5.*" + }, + "suggest": { + "ext-libsodium": "Provides a modern crypto API that can be used to generate random bytes." + }, + "type": "library", + "autoload": { + "files": [ + "lib/random.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Paragon Initiative Enterprises", + "email": "security@paragonie.com", + "homepage": "https://paragonie.com" + } + ], + "description": "PHP 5.x polyfill for random_bytes() and random_int() from PHP 7", + "keywords": [ + "csprng", + "pseudorandom", + "random" + ], + "time": "2017-03-13T16:27:32+00:00" + }, + { "name": "phpdocumentor/reflection-docblock", "version": "2.0.4", "source": { @@ -872,6 +1161,53 @@ "time": "2015-10-02T06:51:40+00:00" }, { + "name": "psr/log", + "version": "1.0.2", + "source": { + "type": "git", + "url": "https://github.com/php-fig/log.git", + "reference": "4ebe3a8bf773a19edfe0a84b6585ba3d401b724d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/log/zipball/4ebe3a8bf773a19edfe0a84b6585ba3d401b724d", + "reference": "4ebe3a8bf773a19edfe0a84b6585ba3d401b724d", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Log\\": "Psr/Log/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for logging libraries", + "homepage": "https://github.com/php-fig/log", + "keywords": [ + "log", + "psr", + "psr-3" + ], + "time": "2016-10-10T12:19:37+00:00" + }, + { "name": "sebastian/comparator", "version": "1.2.2", "source": { @@ -1244,6 +1580,724 @@ "time": "2015-06-21T13:59:46+00:00" }, { + "name": "symfony/console", + "version": "v2.8.20", + "source": { + "type": "git", + "url": "https://github.com/symfony/console.git", + "reference": "2cfcbced8e39e2313ed4da8896fc8c59a56c0d7e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/console/zipball/2cfcbced8e39e2313ed4da8896fc8c59a56c0d7e", + "reference": "2cfcbced8e39e2313ed4da8896fc8c59a56c0d7e", + "shasum": "" + }, + "require": { + "php": ">=5.3.9", + "symfony/debug": "^2.7.2|~3.0.0", + "symfony/polyfill-mbstring": "~1.0" + }, + "require-dev": { + "psr/log": "~1.0", + "symfony/event-dispatcher": "~2.1|~3.0.0", + "symfony/process": "~2.1|~3.0.0" + }, + "suggest": { + "psr/log": "For using the console logger", + "symfony/event-dispatcher": "", + "symfony/process": "" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.8-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\Console\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony Console Component", + "homepage": "https://symfony.com", + "time": "2017-04-26T01:38:53+00:00" + }, + { + "name": "symfony/debug", + "version": "v2.8.20", + "source": { + "type": "git", + "url": "https://github.com/symfony/debug.git", + "reference": "344f50ce827413b3640bfcb1e37386a67d06ea1f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/debug/zipball/344f50ce827413b3640bfcb1e37386a67d06ea1f", + "reference": "344f50ce827413b3640bfcb1e37386a67d06ea1f", + "shasum": "" + }, + "require": { + "php": ">=5.3.9", + "psr/log": "~1.0" + }, + "conflict": { + "symfony/http-kernel": ">=2.3,<2.3.24|~2.4.0|>=2.5,<2.5.9|>=2.6,<2.6.2" + }, + "require-dev": { + "symfony/class-loader": "~2.2|~3.0.0", + "symfony/http-kernel": "~2.3.24|~2.5.9|^2.6.2|~3.0.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.8-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\Debug\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony Debug Component", + "homepage": "https://symfony.com", + "time": "2017-04-19T19:56:30+00:00" + }, + { + "name": "symfony/event-dispatcher", + "version": "v2.8.20", + "source": { + "type": "git", + "url": "https://github.com/symfony/event-dispatcher.git", + "reference": "7fc8e2b4118ff316550596357325dfd92a51f531" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/7fc8e2b4118ff316550596357325dfd92a51f531", + "reference": "7fc8e2b4118ff316550596357325dfd92a51f531", + "shasum": "" + }, + "require": { + "php": ">=5.3.9" + }, + "require-dev": { + "psr/log": "~1.0", + "symfony/config": "^2.0.5|~3.0.0", + "symfony/dependency-injection": "~2.6|~3.0.0", + "symfony/expression-language": "~2.6|~3.0.0", + "symfony/stopwatch": "~2.3|~3.0.0" + }, + "suggest": { + "symfony/dependency-injection": "", + "symfony/http-kernel": "" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.8-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\EventDispatcher\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony EventDispatcher Component", + "homepage": "https://symfony.com", + "time": "2017-04-26T16:56:54+00:00" + }, + { + "name": "symfony/filesystem", + "version": "v2.8.20", + "source": { + "type": "git", + "url": "https://github.com/symfony/filesystem.git", + "reference": "dc40154e26a0116995e4f2f0c71cb9c2fe0775a3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/filesystem/zipball/dc40154e26a0116995e4f2f0c71cb9c2fe0775a3", + "reference": "dc40154e26a0116995e4f2f0c71cb9c2fe0775a3", + "shasum": "" + }, + "require": { + "php": ">=5.3.9" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.8-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\Filesystem\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony Filesystem Component", + "homepage": "https://symfony.com", + "time": "2017-04-12T14:07:15+00:00" + }, + { + "name": "symfony/finder", + "version": "v2.8.20", + "source": { + "type": "git", + "url": "https://github.com/symfony/finder.git", + "reference": "16d55394b31547e4a8494551b85c9b9915545347" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/finder/zipball/16d55394b31547e4a8494551b85c9b9915545347", + "reference": "16d55394b31547e4a8494551b85c9b9915545347", + "shasum": "" + }, + "require": { + "php": ">=5.3.9" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.8-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\Finder\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony Finder Component", + "homepage": "https://symfony.com", + "time": "2017-04-12T14:07:15+00:00" + }, + { + "name": "symfony/options-resolver", + "version": "v2.8.20", + "source": { + "type": "git", + "url": "https://github.com/symfony/options-resolver.git", + "reference": "55bf349a3395afad81a369d57b3b99c373fbbdf5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/options-resolver/zipball/55bf349a3395afad81a369d57b3b99c373fbbdf5", + "reference": "55bf349a3395afad81a369d57b3b99c373fbbdf5", + "shasum": "" + }, + "require": { + "php": ">=5.3.9" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.8-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\OptionsResolver\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony OptionsResolver Component", + "homepage": "https://symfony.com", + "keywords": [ + "config", + "configuration", + "options" + ], + "time": "2017-04-12T14:07:15+00:00" + }, + { + "name": "symfony/polyfill-mbstring", + "version": "v1.3.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-mbstring.git", + "reference": "e79d363049d1c2128f133a2667e4f4190904f7f4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/e79d363049d1c2128f133a2667e4f4190904f7f4", + "reference": "e79d363049d1c2128f133a2667e4f4190904f7f4", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "suggest": { + "ext-mbstring": "For best performance" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.3-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Mbstring\\": "" + }, + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for the Mbstring extension", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "mbstring", + "polyfill", + "portable", + "shim" + ], + "time": "2016-11-14T01:06:16+00:00" + }, + { + "name": "symfony/polyfill-php54", + "version": "v1.3.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php54.git", + "reference": "90e085822963fdcc9d1c5b73deb3d2e5783b16a0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php54/zipball/90e085822963fdcc9d1c5b73deb3d2e5783b16a0", + "reference": "90e085822963fdcc9d1c5b73deb3d2e5783b16a0", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.3-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Php54\\": "" + }, + "files": [ + "bootstrap.php" + ], + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 5.4+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "time": "2016-11-14T01:06:16+00:00" + }, + { + "name": "symfony/polyfill-php55", + "version": "v1.3.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php55.git", + "reference": "03e3f0350bca2220e3623a0e340eef194405fc67" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php55/zipball/03e3f0350bca2220e3623a0e340eef194405fc67", + "reference": "03e3f0350bca2220e3623a0e340eef194405fc67", + "shasum": "" + }, + "require": { + "ircmaxell/password-compat": "~1.0", + "php": ">=5.3.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.3-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Php55\\": "" + }, + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 5.5+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "time": "2016-11-14T01:06:16+00:00" + }, + { + "name": "symfony/polyfill-php70", + "version": "v1.3.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php70.git", + "reference": "13ce343935f0f91ca89605a2f6ca6f5c2f3faac2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php70/zipball/13ce343935f0f91ca89605a2f6ca6f5c2f3faac2", + "reference": "13ce343935f0f91ca89605a2f6ca6f5c2f3faac2", + "shasum": "" + }, + "require": { + "paragonie/random_compat": "~1.0|~2.0", + "php": ">=5.3.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.3-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Php70\\": "" + }, + "files": [ + "bootstrap.php" + ], + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 7.0+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "time": "2016-11-14T01:06:16+00:00" + }, + { + "name": "symfony/polyfill-xml", + "version": "v1.3.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-xml.git", + "reference": "64b6a864f18ab4fddad49f5025f805f6781dfabd" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-xml/zipball/64b6a864f18ab4fddad49f5025f805f6781dfabd", + "reference": "64b6a864f18ab4fddad49f5025f805f6781dfabd", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "suggest": { + "ext-xml": "For best performance" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.3-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Xml\\": "" + }, + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for xml's utf8_encode and utf8_decode functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "time": "2016-11-14T01:06:16+00:00" + }, + { + "name": "symfony/process", + "version": "v2.8.20", + "source": { + "type": "git", + "url": "https://github.com/symfony/process.git", + "reference": "aff35fb3dee799c84a7313c576b72208b046ef8d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/process/zipball/aff35fb3dee799c84a7313c576b72208b046ef8d", + "reference": "aff35fb3dee799c84a7313c576b72208b046ef8d", + "shasum": "" + }, + "require": { + "php": ">=5.3.9" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.8-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\Process\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony Process Component", + "homepage": "https://symfony.com", + "time": "2017-04-12T14:07:15+00:00" + }, + { + "name": "symfony/stopwatch", + "version": "v2.8.20", + "source": { + "type": "git", + "url": "https://github.com/symfony/stopwatch.git", + "reference": "e02577b841394a78306d7b547701bb7bb705bad5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/stopwatch/zipball/e02577b841394a78306d7b547701bb7bb705bad5", + "reference": "e02577b841394a78306d7b547701bb7bb705bad5", + "shasum": "" + }, + "require": { + "php": ">=5.3.9" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.8-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\Stopwatch\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony Stopwatch Component", + "homepage": "https://symfony.com", + "time": "2017-04-12T14:07:15+00:00" + }, + { "name": "symfony/yaml", "version": "v2.8.16", "source": { diff --git a/cs/TODO.md b/cs/TODO.md new file mode 100644 index 0000000..7986205 --- /dev/null +++ b/cs/TODO.md @@ -0,0 +1 @@ +This should be moved to separate package, like `yii\yii2-cs`. diff --git a/cs/src/YiiConfig.php b/cs/src/YiiConfig.php new file mode 100644 index 0000000..4777805 --- /dev/null +++ b/cs/src/YiiConfig.php @@ -0,0 +1,174 @@ + + * @since 2.0.0 + */ +class YiiConfig extends Config +{ + /** + * {@inheritdoc} + */ + public function __construct($name = 'yii-cs-config') + { + parent::__construct($name); + + $this->setRiskyAllowed(true); + + $this->setRules([ + '@PSR2' => true, + 'array_syntax' => [ + 'syntax' => 'short', + ], + 'binary_operator_spaces' => [ + 'align_double_arrow' => false, + 'align_equals' => false, + ], + 'blank_line_after_opening_tag' => true, + 'cast_spaces' => true, + 'concat_space' => [ + 'spacing' => 'one', + ], + 'dir_constant' => true, + 'ereg_to_preg' => true, + 'function_typehint_space' => true, + 'hash_to_slash_comment' => true, +// 'heredoc_to_nowdoc' => true, // needs more discussion +// 'include' => true, // needs more discussion + 'is_null' => [ + 'use_yoda_style' => false, + ], + 'linebreak_after_opening_tag' => true, + 'lowercase_cast' => true, + 'magic_constant_casing' => true, +// 'mb_str_functions' => true, // needs more discussion +// 'method_separation' => true, // conflicts with current Yii style with double line between properties and methods + 'modernize_types_casting' => true, + 'native_function_casing' => true, + 'new_with_braces' => true, + 'no_alias_functions' => true, + 'no_blank_lines_after_class_opening' => true, + 'no_blank_lines_after_phpdoc' => true, + 'no_empty_comment' => true, + 'no_empty_phpdoc' => true, + 'no_empty_statement' => true, + 'no_extra_consecutive_blank_lines' => [ + 'tokens' => [ + 'break', + 'continue', +// 'extra', // conflicts with current Yii style with double line between properties and methods + 'return', + 'throw', + 'use', + 'use_trait', +// 'curly_brace_block', // breaks namespaces blocks + 'parenthesis_brace_block', + 'square_brace_block', + ], + ], + 'no_leading_import_slash' => true, + 'no_leading_namespace_whitespace' => true, + 'no_mixed_echo_print' => true, + 'no_multiline_whitespace_around_double_arrow' => true, + 'no_multiline_whitespace_before_semicolons' => true, + 'no_php4_constructor' => true, + 'no_short_bool_cast' => true, + 'no_singleline_whitespace_before_semicolons' => true, + 'no_spaces_around_offset' => true, + 'no_trailing_comma_in_list_call' => true, + 'no_trailing_comma_in_singleline_array' => true, + 'no_unneeded_control_parentheses' => true, + 'no_unused_imports' => true, +// 'no_useless_else' => true, // needs more discussion + 'no_useless_return' => true, + 'no_whitespace_before_comma_in_array' => true, + 'no_whitespace_in_blank_line' => true, +// 'non_printable_character' => true, // breaks Formatter::asCurrency() tests + 'normalize_index_brace' => true, + 'object_operator_without_whitespace' => true, +// 'ordered_class_elements' => [ // needs more discussion +// 'order' => [ +// 'use_trait', +// 'constant_public', +// 'constant_protected', +// 'constant_private', +// 'property_public', +// 'property_protected', +// 'property_private', +// 'construct', +// 'destruct', +// 'magic', +// ], +// ], + 'ordered_imports' => [ + 'sortAlgorithm' => 'alpha', + 'importsOrder' => [ + 'const', + 'function', + 'class', + ], + ], + 'php_unit_construct' => true, + 'php_unit_dedicate_assert' => true, + 'php_unit_fqcn_annotation' => true, +// 'php_unit_strict' => true, // needs more attention +// 'phpdoc_add_missing_param_annotation' => [ // needs more attention +// 'only_untyped' => false, +// ], + 'phpdoc_indent' => true, +// 'phpdoc_inline_tag' => true, // see https://github.com/yiisoft/yii2/issues/11635 + 'phpdoc_no_access' => true, + 'phpdoc_no_empty_return' => true, + 'phpdoc_no_package' => true, + 'phpdoc_no_useless_inheritdoc' => true, +// 'phpdoc_order', // may be useful, but should be configurable: https://github.com/FriendsOfPHP/PHP-CS-Fixer/issues/1602 + 'phpdoc_return_self_reference' => true, + 'phpdoc_scalar' => true, + 'phpdoc_single_line_var_spacing' => true, +// 'phpdoc_summary' => true, // needs more attention (summary should be separated by blank line from description) +// 'phpdoc_to_comment' => true, // breaks phpdoc for define('CONSTANT', $value); + 'phpdoc_trim' => true, +// 'phpdoc_types' => true, // conflicts with yii\base\Object typehits https://github.com/yiisoft/yii2/pull/12699 + 'phpdoc_var_without_name' => true, + 'protected_to_private' => true, + 'psr4' => true, + 'self_accessor' => true, + 'short_scalar_cast' => true, + 'single_blank_line_before_namespace' => true, + 'single_quote' => true, + 'standardize_not_equals' => true, + 'ternary_operator_spaces' => true, + 'trailing_comma_in_multiline_array' => true, + 'trim_array_spaces' => true, + 'unary_operator_spaces' => true, + 'whitespace_after_comma_in_array' => true, + ]); + } + + /** + * Merge current rules config with provided list of rules. + * + * @param array $rules + * @return $this + * @see setRules() + * @see ArrayHelper::merge() + */ + public function mergeRules(array $rules) + { + $this->setRules(ArrayHelper::merge($this->getRules(), $rules)); + + return $this; + } +} diff --git a/cs/src/YiisoftConfig.php b/cs/src/YiisoftConfig.php new file mode 100644 index 0000000..077c970 --- /dev/null +++ b/cs/src/YiisoftConfig.php @@ -0,0 +1,39 @@ + + * @since 2.0.0 + */ +final class YiisoftConfig extends YiiConfig +{ + /** + * {@inheritdoc} + */ + public function __construct() + { + parent::__construct('yiisoft-cs-config'); + + $header = <<
mergeRules([ + 'header_comment' => [ + 'header' => $header, + 'commentType' => 'PHPDoc', + 'separate' => 'bottom', + ], + ]); + } +} diff --git a/framework/BaseYii.php b/framework/BaseYii.php index e13c295..7e586f0 100644 --- a/framework/BaseYii.php +++ b/framework/BaseYii.php @@ -10,8 +10,8 @@ namespace yii; use yii\base\InvalidConfigException; use yii\base\InvalidParamException; use yii\base\UnknownClassException; -use yii\log\Logger; use yii\di\Container; +use yii\log\Logger; /** * Gets the application start timestamp. @@ -474,7 +474,7 @@ class BaseYii { return \Yii::t('yii', 'Powered by {yii}', [ 'yii' => '' . \Yii::t('yii', - 'Yii Framework') . '' + 'Yii Framework') . '', ]); } diff --git a/framework/Yii.php b/framework/Yii.php index 83cd858..6b787a6 100644 --- a/framework/Yii.php +++ b/framework/Yii.php @@ -1,7 +1,5 @@ state = self::STATE_BEFORE_REQUEST; $this->trigger(self::EVENT_BEFORE_REQUEST); @@ -388,12 +387,9 @@ abstract class Application extends Module $this->state = self::STATE_END; return $response->exitStatus; - } catch (ExitException $e) { - $this->end($e->statusCode, isset($response) ? $response : null); return $e->statusCode; - } } @@ -649,7 +645,7 @@ abstract class Application extends Module if ($this->state !== self::STATE_SENDING_RESPONSE && $this->state !== self::STATE_END) { $this->state = self::STATE_END; - $response = $response ? : $this->getResponse(); + $response = $response ?: $this->getResponse(); $response->send(); } diff --git a/framework/base/Component.php b/framework/base/Component.php index 2188084..3b2db8d 100644 --- a/framework/base/Component.php +++ b/framework/base/Component.php @@ -533,7 +533,7 @@ class Component extends Object $this->ensureBehaviors(); if (!empty($this->_events[$name])) { if ($event === null) { - $event = new Event; + $event = new Event(); } if ($event->sender === null) { $event->sender = $this; diff --git a/framework/base/ErrorHandler.php b/framework/base/ErrorHandler.php index 69e196a..8b74d56 100644 --- a/framework/base/ErrorHandler.php +++ b/framework/base/ErrorHandler.php @@ -133,7 +133,8 @@ abstract class ErrorHandler extends Component * @param \Exception $previousException Main exception processed in [[handleException()]]. * @since 2.0.11 */ - protected function handleFallbackExceptionMessage($exception, $previousException) { + protected function handleFallbackExceptionMessage($exception, $previousException) + { $msg = "An Error occurred while handling another error:\n"; $msg .= (string) $exception; $msg .= "\nPrevious exception:\n"; diff --git a/framework/base/Event.php b/framework/base/Event.php index 99dfe49..c7d61e2 100644 --- a/framework/base/Event.php +++ b/framework/base/Event.php @@ -190,7 +190,7 @@ class Event extends Object return; } if ($event === null) { - $event = new static; + $event = new static(); } $event->handled = false; $event->name = $name; @@ -214,7 +214,7 @@ class Event extends Object if (empty(self::$_events[$name][$class])) { continue; } - + foreach (self::$_events[$name][$class] as $handler) { $event->data = $handler[1]; call_user_func($handler[0], $event); diff --git a/framework/base/Model.php b/framework/base/Model.php index 621fddc..202e367 100644 --- a/framework/base/Model.php +++ b/framework/base/Model.php @@ -7,12 +7,12 @@ namespace yii\base; -use Yii; use ArrayAccess; -use ArrayObject; use ArrayIterator; -use ReflectionClass; +use ArrayObject; use IteratorAggregate; +use ReflectionClass; +use Yii; use yii\helpers\Inflector; use yii\validators\RequiredValidator; use yii\validators\Validator; @@ -372,7 +372,7 @@ class Model extends Component implements IteratorAggregate, ArrayAccess, Arrayab */ public function beforeValidate() { - $event = new ModelEvent; + $event = new ModelEvent(); $this->trigger(self::EVENT_BEFORE_VALIDATE, $event); return $event->isValid; @@ -439,7 +439,7 @@ class Model extends Component implements IteratorAggregate, ArrayAccess, Arrayab */ public function createValidators() { - $validators = new ArrayObject; + $validators = new ArrayObject(); foreach ($this->rules() as $rule) { if ($rule instanceof Validator) { $validators->append($rule); diff --git a/framework/base/Module.php b/framework/base/Module.php index 9820202..923e94d 100644 --- a/framework/base/Module.php +++ b/framework/base/Module.php @@ -415,7 +415,7 @@ class Module extends ServiceLocator } if (isset($this->_modules[$id])) { - if ($this->_modules[$id] instanceof Module) { + if ($this->_modules[$id] instanceof self) { return $this->_modules[$id]; } elseif ($load) { Yii::trace("Loading module: $id", __METHOD__); @@ -461,7 +461,7 @@ class Module extends ServiceLocator if ($loadedOnly) { $modules = []; foreach ($this->_modules as $module) { - if ($module instanceof Module) { + if ($module instanceof self) { $modules[] = $module; } } @@ -567,7 +567,7 @@ class Module extends ServiceLocator } if (strpos($route, '/') !== false) { - list ($id, $route) = explode('/', $route, 2); + list($id, $route) = explode('/', $route, 2); } else { $id = $route; $route = ''; @@ -629,7 +629,7 @@ class Module extends ServiceLocator } $className = str_replace(' ', '', ucwords(str_replace('-', ' ', $className))) . 'Controller'; - $className = ltrim($this->controllerNamespace . '\\' . str_replace('/', '\\', $prefix) . $className, '\\'); + $className = ltrim($this->controllerNamespace . '\\' . str_replace('/', '\\', $prefix) . $className, '\\'); if (strpos($className, '-') !== false || !class_exists($className)) { return null; } @@ -638,7 +638,7 @@ class Module extends ServiceLocator $controller = Yii::createObject($className, [$id, $this]); return get_class($controller) === $className ? $controller : null; } elseif (YII_DEBUG) { - throw new InvalidConfigException("Controller class must extend from \\yii\\base\\Controller."); + throw new InvalidConfigException('Controller class must extend from \\yii\\base\\Controller.'); } return null; } diff --git a/framework/base/Security.php b/framework/base/Security.php index 6f05681..48eda8e 100644 --- a/framework/base/Security.php +++ b/framework/base/Security.php @@ -7,8 +7,8 @@ namespace yii\base; -use yii\helpers\StringHelper; use Yii; +use yii\helpers\StringHelper; /** * Security provides a set of methods to handle common security-related tasks. @@ -610,7 +610,7 @@ class Security extends Component } if (function_exists('password_hash')) { - /** @noinspection PhpUndefinedConstantInspection */ + /* @noinspection PhpUndefinedConstantInspection */ return password_hash($password, PASSWORD_DEFAULT, ['cost' => $cost]); } @@ -680,7 +680,7 @@ class Security extends Component // Get a 20-byte random string $rand = $this->generateRandomKey(20); // Form the prefix that specifies Blowfish (bcrypt) algorithm and cost parameter. - $salt = sprintf("$2y$%02d$", $cost); + $salt = sprintf('$2y$%02d$', $cost); // Append the random salt data in the required base64 format. $salt .= str_replace('+', '.', substr(base64_encode($rand), 0, 22)); diff --git a/framework/base/Widget.php b/framework/base/Widget.php index b791391..2ae908d 100644 --- a/framework/base/Widget.php +++ b/framework/base/Widget.php @@ -7,8 +7,8 @@ namespace yii\base; -use Yii; use ReflectionClass; +use Yii; /** * Widget is the base class for widgets. diff --git a/framework/base/WidgetEvent.php b/framework/base/WidgetEvent.php index d8582ad..6ec5ae8 100644 --- a/framework/base/WidgetEvent.php +++ b/framework/base/WidgetEvent.php @@ -22,7 +22,7 @@ class WidgetEvent extends Event */ public $result; /** - * @var boolean whether to continue running the widget. Event handlers of + * @var bool whether to continue running the widget. Event handlers of * [[Widget::EVENT_BEFORE_RUN]] may set this property to decide whether * to continue running the current widget. */ diff --git a/framework/behaviors/AttributeTypecastBehavior.php b/framework/behaviors/AttributeTypecastBehavior.php index 0090e74..d664da8 100644 --- a/framework/behaviors/AttributeTypecastBehavior.php +++ b/framework/behaviors/AttributeTypecastBehavior.php @@ -280,7 +280,7 @@ class AttributeTypecastBehavior extends Behavior } if ($type !== null) { - foreach ((array)$validator->attributes as $attribute) { + foreach ((array) $validator->attributes as $attribute) { $attributeTypes[$attribute] = $type; } } diff --git a/framework/behaviors/SluggableBehavior.php b/framework/behaviors/SluggableBehavior.php index 57d35e3..7625584 100644 --- a/framework/behaviors/SluggableBehavior.php +++ b/framework/behaviors/SluggableBehavior.php @@ -7,12 +7,12 @@ namespace yii\behaviors; +use Yii; use yii\base\InvalidConfigException; use yii\db\BaseActiveRecord; use yii\helpers\ArrayHelper; use yii\helpers\Inflector; use yii\validators\UniqueValidator; -use Yii; /** * SluggableBehavior automatically fills the specified attribute with a value that can be used a slug in a URL. @@ -177,7 +177,7 @@ class SluggableBehavior extends AttributeBehavior return true; } - foreach ((array)$this->attribute as $attribute) { + foreach ((array) $this->attribute as $attribute) { if ($this->owner->isAttributeChanged($attribute)) { return true; } diff --git a/framework/caching/ArrayCache.php b/framework/caching/ArrayCache.php index 76fcb7a..e7de9d4 100644 --- a/framework/caching/ArrayCache.php +++ b/framework/caching/ArrayCache.php @@ -85,4 +85,4 @@ class ArrayCache extends Cache $this->_cache = []; return true; } -} \ No newline at end of file +} diff --git a/framework/caching/Cache.php b/framework/caching/Cache.php index e54c981..42e7139 100644 --- a/framework/caching/Cache.php +++ b/framework/caching/Cache.php @@ -73,7 +73,7 @@ abstract class Cache extends Component implements CacheInterface */ public $serializer; /** - * @var integer default duration in seconds before a cache entry will expire. Default value is 0, meaning infinity. + * @var int default duration in seconds before a cache entry will expire. Default value is 0, meaning infinity. * This value is used by [[set()]] if the duration is not explicitly given. * @since 2.0.11 */ diff --git a/framework/caching/CacheInterface.php b/framework/caching/CacheInterface.php index ac35484..4267240 100644 --- a/framework/caching/CacheInterface.php +++ b/framework/caching/CacheInterface.php @@ -1,4 +1,9 @@ buildKey($key); - $query = new Query; + $query = new Query(); $query->select(['COUNT(*)']) ->from($this->cacheTable) ->where('[[id]] = :id AND ([[expire]] = 0 OR [[expire]] >' . time() . ')', [':id' => $key]); @@ -125,7 +125,7 @@ class DbCache extends Cache */ protected function getValue($key) { - $query = new Query; + $query = new Query(); $query->select(['data']) ->from($this->cacheTable) ->where('[[id]] = :id AND ([[expire]] = 0 OR [[expire]] >' . time() . ')', [':id' => $key]); @@ -150,7 +150,7 @@ class DbCache extends Cache if (empty($keys)) { return []; } - $query = new Query; + $query = new Query(); $query->select(['id', 'data']) ->from($this->cacheTable) ->where(['id' => $keys]) diff --git a/framework/caching/MemCache.php b/framework/caching/MemCache.php index 6e69b40..7a5dac1 100644 --- a/framework/caching/MemCache.php +++ b/framework/caching/MemCache.php @@ -221,7 +221,7 @@ class MemCache extends Cache } if ($this->useMemcached) { - $this->_cache = $this->persistentId !== null ? new \Memcached($this->persistentId) : new \Memcached; + $this->_cache = $this->persistentId !== null ? new \Memcached($this->persistentId) : new \Memcached(); if ($this->username !== null || $this->password !== null) { $this->_cache->setOption(\Memcached::OPT_BINARY_PROTOCOL, true); $this->_cache->setSaslAuthData($this->username, $this->password); @@ -230,7 +230,7 @@ class MemCache extends Cache $this->_cache->setOptions($this->options); } } else { - $this->_cache = new \Memcache; + $this->_cache = new \Memcache(); } } diff --git a/framework/caching/migrations/m150909_153426_cache_init.php b/framework/caching/migrations/m150909_153426_cache_init.php index 4be6cbe..359390f 100644 --- a/framework/caching/migrations/m150909_153426_cache_init.php +++ b/framework/caching/migrations/m150909_153426_cache_init.php @@ -17,7 +17,6 @@ use yii\db\Migration; */ class m150909_153426_cache_init extends Migration { - /** * @throws yii\base\InvalidConfigException * @return DbCache diff --git a/framework/captcha/Captcha.php b/framework/captcha/Captcha.php index ba75f65..b1cc6e4 100644 --- a/framework/captcha/Captcha.php +++ b/framework/captcha/Captcha.php @@ -9,9 +9,9 @@ namespace yii\captcha; use Yii; use yii\base\InvalidConfigException; -use yii\helpers\Url; use yii\helpers\Html; use yii\helpers\Json; +use yii\helpers\Url; use yii\widgets\InputWidget; /** diff --git a/framework/console/Application.php b/framework/console/Application.php index ab096f5..758aafe 100644 --- a/framework/console/Application.php +++ b/framework/console/Application.php @@ -142,7 +142,7 @@ class Application extends \yii\base\Application */ public function handleRequest($request) { - list ($route, $params) = $request->resolve(); + list($route, $params) = $request->resolve(); $this->requestedRoute = $route; $result = $this->runAction($route, $params); if ($result instanceof Response) { @@ -178,7 +178,7 @@ class Application extends \yii\base\Application { try { $res = parent::runAction($route, $params); - return is_object($res) ? $res : (int)$res; + return is_object($res) ? $res : (int) $res; } catch (InvalidRouteException $e) { throw new UnknownCommandException($route, $this, 0, $e); } diff --git a/framework/console/Controller.php b/framework/console/Controller.php index 7cd4999..ad6ea6a 100644 --- a/framework/console/Controller.php +++ b/framework/console/Controller.php @@ -351,7 +351,7 @@ class Controller extends \yii\base\Controller public function optionAliases() { return [ - 'h' => 'help' + 'h' => 'help', ]; } diff --git a/framework/console/ErrorHandler.php b/framework/console/ErrorHandler.php index cf62613..c73c5a9 100644 --- a/framework/console/ErrorHandler.php +++ b/framework/console/ErrorHandler.php @@ -34,7 +34,7 @@ class ErrorHandler extends \yii\base\ErrorHandler $message = $this->formatMessage($exception->getName() . ': ') . $exception->command; $alternatives = $exception->getSuggestedAlternatives(); if (count($alternatives) === 1) { - $message .= "\n\nDid you mean \"" . reset($alternatives) . "\"?"; + $message .= "\n\nDid you mean \"" . reset($alternatives) . '"?'; } elseif (count($alternatives) > 1) { $message .= "\n\nDid you mean one of these?\n - " . implode("\n - ", $alternatives); } diff --git a/framework/console/UnknownCommandException.php b/framework/console/UnknownCommandException.php index c8ad38c..eeb9d75 100644 --- a/framework/console/UnknownCommandException.php +++ b/framework/console/UnknownCommandException.php @@ -124,14 +124,14 @@ class UnknownCommandException extends Exception } // calculate the Levenshtein distance between the unknown command and all available commands. - $distances = array_map(function($action) use ($command) { + $distances = array_map(function ($action) use ($command) { $action = strlen($action) > 255 ? substr($action, 0, 255) : $action; $command = strlen($command) > 255 ? substr($command, 0, 255) : $command; return levenshtein($action, $command); }, array_combine($actions, $actions)); // we assume a typo if the levensthein distance is no more than 3, i.e. 3 replacements needed - $relevantTypos = array_filter($distances, function($distance) { + $relevantTypos = array_filter($distances, function ($distance) { return $distance <= 3; }); asort($relevantTypos); diff --git a/framework/console/controllers/AssetController.php b/framework/console/controllers/AssetController.php index d16220a..dc63c7c 100644 --- a/framework/console/controllers/AssetController.php +++ b/framework/console/controllers/AssetController.php @@ -8,8 +8,8 @@ namespace yii\console\controllers; use Yii; -use yii\console\Exception; use yii\console\Controller; +use yii\console\Exception; use yii\helpers\Console; use yii\helpers\FileHelper; use yii\helpers\VarDumper; @@ -612,7 +612,7 @@ EOD; $inputFilePathPartsCount = count($inputFilePathParts); $outputFilePathParts = explode('/', $outputFilePath); $outputFilePathPartsCount = count($outputFilePathParts); - for ($i =0; $i < $inputFilePathPartsCount && $i < $outputFilePathPartsCount; $i++) { + for ($i = 0; $i < $inputFilePathPartsCount && $i < $outputFilePathPartsCount; $i++) { if ($inputFilePathParts[$i] == $outputFilePathParts[$i]) { $sharedPathParts[] = $inputFilePathParts[$i]; } else { @@ -766,7 +766,7 @@ EOD; */ private function isBundleExternal($bundle) { - return (empty($bundle->sourcePath) && empty($bundle->basePath)); + return empty($bundle->sourcePath) && empty($bundle->basePath); } /** diff --git a/framework/console/controllers/BaseMigrateController.php b/framework/console/controllers/BaseMigrateController.php index 5f79c00..25fec0b 100644 --- a/framework/console/controllers/BaseMigrateController.php +++ b/framework/console/controllers/BaseMigrateController.php @@ -9,11 +9,10 @@ namespace yii\console\controllers; use Yii; use yii\base\InvalidConfigException; -use yii\console\Exception; use yii\console\Controller; +use yii\console\Exception; use yii\helpers\Console; use yii\helpers\FileHelper; -use yii\helpers\StringHelper; /** * BaseMigrateController is the base class for migrate controllers. @@ -113,7 +112,7 @@ abstract class BaseMigrateController extends Controller } if (is_array($this->migrationPath)) { - foreach($this->migrationPath as $i => $path) { + foreach ($this->migrationPath as $i => $path) { $this->migrationPath[$i] = Yii::getAlias($path); } } elseif ($this->migrationPath !== null) { @@ -181,7 +180,7 @@ abstract class BaseMigrateController extends Controller if ($this->confirm('Apply the above ' . ($n === 1 ? 'migration' : 'migrations') . '?')) { foreach ($migrations as $migration) { if (!$this->migrateUp($migration)) { - $this->stdout("\n$applied from $n " . ($applied === 1 ? 'migration was' : 'migrations were') ." applied.\n", Console::FG_RED); + $this->stdout("\n$applied from $n " . ($applied === 1 ? 'migration was' : 'migrations were') . " applied.\n", Console::FG_RED); $this->stdout("\nMigration failed. The rest of the migrations are canceled.\n", Console::FG_RED); return self::EXIT_CODE_ERROR; @@ -189,7 +188,7 @@ abstract class BaseMigrateController extends Controller $applied++; } - $this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') ." applied.\n", Console::FG_GREEN); + $this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') . " applied.\n", Console::FG_GREEN); $this->stdout("\nMigrated up successfully.\n", Console::FG_GREEN); } } @@ -242,14 +241,14 @@ abstract class BaseMigrateController extends Controller if ($this->confirm('Revert the above ' . ($n === 1 ? 'migration' : 'migrations') . '?')) { foreach ($migrations as $migration) { if (!$this->migrateDown($migration)) { - $this->stdout("\n$reverted from $n " . ($reverted === 1 ? 'migration was' : 'migrations were') ." reverted.\n", Console::FG_RED); + $this->stdout("\n$reverted from $n " . ($reverted === 1 ? 'migration was' : 'migrations were') . " reverted.\n", Console::FG_RED); $this->stdout("\nMigration failed. The rest of the migrations are canceled.\n", Console::FG_RED); return self::EXIT_CODE_ERROR; } $reverted++; } - $this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') ." reverted.\n", Console::FG_GREEN); + $this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') . " reverted.\n", Console::FG_GREEN); $this->stdout("\nMigrated down successfully.\n", Console::FG_GREEN); } } @@ -315,7 +314,7 @@ abstract class BaseMigrateController extends Controller return self::EXIT_CODE_ERROR; } } - $this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') ." redone.\n", Console::FG_GREEN); + $this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') . " redone.\n", Console::FG_GREEN); $this->stdout("\nMigration redone successfully.\n", Console::FG_GREEN); } } @@ -735,7 +734,7 @@ abstract class BaseMigrateController extends Controller $class = trim($class, '\\'); if (strpos($class, '\\') === false) { if (is_array($this->migrationPath)) { - foreach($this->migrationPath as $path) { + foreach ($this->migrationPath as $path) { $file = $path . DIRECTORY_SEPARATOR . $class . '.php'; if (is_file($file)) { require_once($file); @@ -817,7 +816,7 @@ abstract class BaseMigrateController extends Controller $migrationPaths = []; if (is_array($this->migrationPath)) { - foreach($this->migrationPath as $path) { + foreach ($this->migrationPath as $path) { $migrationPaths[] = [$path, '']; } } elseif (!empty($this->migrationPath)) { diff --git a/framework/console/controllers/CacheController.php b/framework/console/controllers/CacheController.php index d5fc2b3..31d5383 100644 --- a/framework/console/controllers/CacheController.php +++ b/framework/console/controllers/CacheController.php @@ -11,8 +11,8 @@ use Yii; use yii\caching\ApcCache; use yii\caching\CacheInterface; use yii\console\Controller; -use yii\helpers\Console; use yii\console\Exception; +use yii\helpers\Console; /** * Allows you to flush cache. @@ -67,7 +67,6 @@ class CacheController extends Controller * # flushes caches specified by their id: "first", "second", "third" * yii cache/flush first second third * ``` - * */ public function actionFlush() { @@ -213,7 +212,6 @@ class CacheController extends Controller } /** - * * @param array $caches */ private function notifyFlushed($caches) @@ -221,7 +219,7 @@ class CacheController extends Controller $this->stdout("The following cache components were processed:\n\n", Console::FG_YELLOW); foreach ($caches as $cache) { - $this->stdout("\t* " . $cache['name'] .' (' . $cache['class'] . ')', Console::FG_GREEN); + $this->stdout("\t* " . $cache['name'] . ' (' . $cache['class'] . ')', Console::FG_GREEN); if (!$cache['is_flushed']) { $this->stdout(" - not flushed\n", Console::FG_RED); @@ -294,6 +292,6 @@ class CacheController extends Controller */ private function canBeFlushed($className) { - return !is_a($className, ApcCache::className(), true) || php_sapi_name() !== "cli"; + return !is_a($className, ApcCache::className(), true) || php_sapi_name() !== 'cli'; } } diff --git a/framework/console/controllers/FixtureController.php b/framework/console/controllers/FixtureController.php index 8355900..9ebfee6 100644 --- a/framework/console/controllers/FixtureController.php +++ b/framework/console/controllers/FixtureController.php @@ -68,7 +68,7 @@ class FixtureController extends Controller public function options($actionID) { return array_merge(parent::options($actionID), [ - 'namespace', 'globalFixtures' + 'namespace', 'globalFixtures', ]); } @@ -135,8 +135,8 @@ class FixtureController extends Controller if (!$foundFixtures) { throw new Exception( - "No files were found for: \"" . implode(', ', $fixturesInput) . "\".\n" . - "Check that files exist under fixtures path: \n\"" . $this->getFixturePath() . "\"." + 'No files were found for: "' . implode(', ', $fixturesInput) . "\".\n" . + "Check that files exist under fixtures path: \n\"" . $this->getFixturePath() . '".' ); } @@ -205,8 +205,8 @@ class FixtureController extends Controller if (!$foundFixtures) { throw new Exception( - "No files were found for: \"" . implode(', ', $fixturesInput) . "\".\n" . - "Check that files exist under fixtures path: \n\"" . $this->getFixturePath() . "\"." + 'No files were found for: "' . implode(', ', $fixturesInput) . "\".\n" . + "Check that files exist under fixtures path: \n\"" . $this->getFixturePath() . '".' ); } @@ -433,7 +433,7 @@ class FixtureController extends Controller $fixturesPath = FileHelper::normalizePath($this->getFixturePath()); $fullFixturePath = FileHelper::normalizePath($fullFixturePath); - $relativeName = substr($fullFixturePath, strlen($fixturesPath)+1); + $relativeName = substr($fullFixturePath, strlen($fixturesPath) + 1); $relativeDir = dirname($relativeName) === '.' ? '' : dirname($relativeName) . DIRECTORY_SEPARATOR; return $relativeDir . basename($fullFixturePath, 'Fixture.php'); diff --git a/framework/console/controllers/HelpController.php b/framework/console/controllers/HelpController.php index 6e8f6fb..e6649df 100644 --- a/framework/console/controllers/HelpController.php +++ b/framework/console/controllers/HelpController.php @@ -168,8 +168,6 @@ class HelpController extends Controller } $this->stdout("\n"); - - return; } /** @@ -372,14 +370,14 @@ class HelpController extends Controller $maxlen = 5; foreach ($actions as $action) { - $len = strlen($prefix.'/'.$action) + 2 + ($action === $controller->defaultAction ? 10 : 0); + $len = strlen($prefix . '/' . $action) + 2 + ($action === $controller->defaultAction ? 10 : 0); if ($maxlen < $len) { $maxlen = $len; } } foreach ($actions as $action) { - $this->stdout('- ' . $this->ansiFormat($prefix.'/'.$action, Console::FG_YELLOW)); - $len = strlen($prefix.'/'.$action) + 2; + $this->stdout('- ' . $this->ansiFormat($prefix . '/' . $action, Console::FG_YELLOW)); + $len = strlen($prefix . '/' . $action) + 2; if ($action === $controller->defaultAction) { $this->stdout(' (default)', Console::FG_GREEN); $len += 10; diff --git a/framework/console/controllers/MessageController.php b/framework/console/controllers/MessageController.php index 4cd436a..74b9192 100644 --- a/framework/console/controllers/MessageController.php +++ b/framework/console/controllers/MessageController.php @@ -363,13 +363,13 @@ EOD; protected function saveMessagesToDb($messages, $db, $sourceMessageTable, $messageTable, $removeUnused, $languages, $markUnused) { $currentMessages = []; - $rows = (new Query)->select(['id', 'category', 'message'])->from($sourceMessageTable)->all($db); + $rows = (new Query())->select(['id', 'category', 'message'])->from($sourceMessageTable)->all($db); foreach ($rows as $row) { $currentMessages[$row['category']][$row['id']] = $row['message']; } $currentLanguages = []; - $rows = (new Query)->select(['language'])->from($messageTable)->groupBy('language')->all($db); + $rows = (new Query())->select(['language'])->from($messageTable)->groupBy('language')->all($db); foreach ($rows as $row) { $currentLanguages[] = $row['language']; } @@ -422,7 +422,7 @@ EOD; if (!empty($missingLanguages)) { $updatedMessages = []; - $rows = (new Query)->select(['id', 'category', 'message'])->from($sourceMessageTable)->all($db); + $rows = (new Query())->select(['id', 'category', 'message'])->from($sourceMessageTable)->all($db); foreach ($rows as $row) { $updatedMessages[$row['category']][$row['id']] = $row['message']; } @@ -452,7 +452,7 @@ EOD; ->execute(); $this->stdout("deleted.\n"); } elseif ($markUnused) { - $rows = (new Query) + $rows = (new Query()) ->select(['id', 'message']) ->from($sourceMessageTable) ->where(['in', 'id', $obsolete]) @@ -482,7 +482,7 @@ EOD; */ protected function extractMessages($fileName, $translator, $ignoreCategories = []) { - $this->stdout("Extracting messages from "); + $this->stdout('Extracting messages from '); $this->stdout($fileName, Console::FG_CYAN); $this->stdout("...\n"); @@ -656,7 +656,7 @@ EOD; protected function saveMessagesToPHP($messages, $dirName, $overwrite, $removeUnused, $sort, $markUnused) { foreach ($messages as $category => $msgs) { - $file = str_replace("\\", '/', "$dirName/$category.php"); + $file = str_replace('\\', '/', "$dirName/$category.php"); $path = dirname($file); FileHelper::createDirectory($path); $msgs = array_values(array_unique($msgs)); @@ -777,7 +777,7 @@ EOD; */ protected function saveMessagesToPO($messages, $dirName, $overwrite, $removeUnused, $sort, $catalog, $markUnused) { - $file = str_replace("\\", '/', "$dirName/$catalog.po"); + $file = str_replace('\\', '/', "$dirName/$catalog.po"); FileHelper::createDirectory(dirname($file)); $this->stdout("Saving messages to $file...\n"); @@ -870,7 +870,7 @@ EOD; */ protected function saveMessagesToPOT($messages, $dirName, $catalog) { - $file = str_replace("\\", '/', "$dirName/$catalog.pot"); + $file = str_replace('\\', '/', "$dirName/$catalog.pot"); FileHelper::createDirectory(dirname($file)); $this->stdout("Saving messages to $file...\n"); diff --git a/framework/console/controllers/MigrateController.php b/framework/console/controllers/MigrateController.php index c6c9315..c234e35 100644 --- a/framework/console/controllers/MigrateController.php +++ b/framework/console/controllers/MigrateController.php @@ -220,7 +220,7 @@ class MigrateController extends BaseMigrateController } else { $row['canonicalVersion'] = $row['version']; } - $row['apply_time'] = (int)$row['apply_time']; + $row['apply_time'] = (int) $row['apply_time']; $history[] = $row; } diff --git a/framework/data/ActiveDataProvider.php b/framework/data/ActiveDataProvider.php index c971a48..6fd1b44 100644 --- a/framework/data/ActiveDataProvider.php +++ b/framework/data/ActiveDataProvider.php @@ -7,9 +7,9 @@ namespace yii\data; -use yii\db\ActiveQueryInterface; use yii\base\InvalidConfigException; use yii\base\Model; +use yii\db\ActiveQueryInterface; use yii\db\Connection; use yii\db\QueryInterface; use yii\di\Instance; @@ -177,7 +177,7 @@ class ActiveDataProvider extends BaseDataProvider parent::setSort($value); if (($sort = $this->getSort()) !== false && $this->query instanceof ActiveQueryInterface) { /* @var $model Model */ - $model = new $this->query->modelClass; + $model = new $this->query->modelClass(); if (empty($sort->attributes)) { foreach ($model->attributes() as $attribute) { $sort->attributes[$attribute] = [ diff --git a/framework/data/SqlDataProvider.php b/framework/data/SqlDataProvider.php index 0b894d3..a54bf5b 100644 --- a/framework/data/SqlDataProvider.php +++ b/framework/data/SqlDataProvider.php @@ -165,7 +165,7 @@ class SqlDataProvider extends BaseDataProvider { return (new Query([ 'from' => ['sub' => "({$this->sql})"], - 'params' => $this->params + 'params' => $this->params, ]))->count('*', $this->db); } } diff --git a/framework/db/ActiveQuery.php b/framework/db/ActiveQuery.php index d6dbb10..03f6ed2 100644 --- a/framework/db/ActiveQuery.php +++ b/framework/db/ActiveQuery.php @@ -315,7 +315,7 @@ class ActiveQuery extends Query implements ActiveQueryInterface } if ($this->sql === null) { - list ($sql, $params) = $db->getQueryBuilder()->build($this); + list($sql, $params) = $db->getQueryBuilder()->build($this); } else { $sql = $this->sql; $params = $this->params; @@ -339,7 +339,7 @@ class ActiveQuery extends Query implements ActiveQueryInterface return parent::queryScalar($selectExpression, $db); } - return (new Query)->select([$selectExpression]) + return (new Query())->select([$selectExpression]) ->from(['c' => "({$this->sql})"]) ->params($this->params) ->createCommand($db) @@ -412,7 +412,7 @@ class ActiveQuery extends Query implements ActiveQueryInterface list(, $relation, $alias) = $matches; $name = $relation; $callback = function ($query) use ($callback, $alias) { - /** @var $query ActiveQuery */ + /* @var $query ActiveQuery */ $query->alias($alias); if ($callback !== null) { call_user_func($callback, $query); @@ -435,9 +435,9 @@ class ActiveQuery extends Query implements ActiveQueryInterface $join = $this->join; $this->join = []; - $model = new $this->modelClass; + $model = new $this->modelClass(); foreach ($this->joinWith as $config) { - list ($with, $eagerLoading, $joinType) = $config; + list($with, $eagerLoading, $joinType) = $config; $this->joinWithRelations($model, $with, $joinType); if (is_array($eagerLoading)) { @@ -515,7 +515,7 @@ class ActiveQuery extends Query implements ActiveQueryInterface } else { $relation = $relations[$fullName]; } - $primaryModel = new $relation->modelClass; + $primaryModel = new $relation->modelClass(); $parent = $relation; $prefix = $fullName; $name = $childName; @@ -590,7 +590,7 @@ class ActiveQuery extends Query implements ActiveQueryInterface { $via = $child->via; $child->via = null; - if ($via instanceof ActiveQuery) { + if ($via instanceof self) { // via table $this->joinWithRelation($parent, $via, $joinType); $this->joinWithRelation($via, $child, $joinType); @@ -602,11 +602,10 @@ class ActiveQuery extends Query implements ActiveQueryInterface return; } - list ($parentTable, $parentAlias) = $parent->getTableNameAndAlias(); - list ($childTable, $childAlias) = $child->getTableNameAndAlias(); + list($parentTable, $parentAlias) = $parent->getTableNameAndAlias(); + list($childTable, $childAlias) = $child->getTableNameAndAlias(); if (!empty($child->link)) { - if (strpos($parentAlias, '{{') === false) { $parentAlias = '{{' . $parentAlias . '}}'; } @@ -750,7 +749,7 @@ class ActiveQuery extends Query implements ActiveQueryInterface */ public function viaTable($tableName, $link, callable $callable = null) { - $relation = new ActiveQuery(get_class($this->primaryModel), [ + $relation = new self(get_class($this->primaryModel), [ 'from' => [$tableName], 'link' => $link, 'multiple' => true, @@ -777,7 +776,7 @@ class ActiveQuery extends Query implements ActiveQueryInterface public function alias($alias) { if (empty($this->from) || count($this->from) < 2) { - list($tableName, ) = $this->getTableNameAndAlias(); + list($tableName) = $this->getTableNameAndAlias(); $this->from = [$alias => $tableName]; } else { $tableName = $this->getPrimaryTableName(); diff --git a/framework/db/ActiveQueryTrait.php b/framework/db/ActiveQueryTrait.php index d4046a3..7880dea 100644 --- a/framework/db/ActiveQueryTrait.php +++ b/framework/db/ActiveQueryTrait.php @@ -162,7 +162,7 @@ trait ActiveQueryTrait { $primaryModel = reset($models); if (!$primaryModel instanceof ActiveRecordInterface) { - $primaryModel = new $this->modelClass; + $primaryModel = new $this->modelClass(); } $relations = $this->normalizeRelations($primaryModel, $with); /* @var $relation ActiveQuery */ diff --git a/framework/db/ActiveRelationTrait.php b/framework/db/ActiveRelationTrait.php index 3a7ce71..dfe3a55 100644 --- a/framework/db/ActiveRelationTrait.php +++ b/framework/db/ActiveRelationTrait.php @@ -177,7 +177,7 @@ trait ActiveRelationTrait $relatedModel->populateRelation($this->inverseOf, $inverseRelation->multiple ? [$this->primaryModel] : $this->primaryModel); } else { if (!isset($inverseRelation)) { - $inverseRelation = (new $this->modelClass)->getRelation($this->inverseOf); + $inverseRelation = (new $this->modelClass())->getRelation($this->inverseOf); } $result[$i][$this->inverseOf] = $inverseRelation->multiple ? [$this->primaryModel] : $this->primaryModel; } @@ -298,7 +298,7 @@ trait ActiveRelationTrait } $model = reset($models); /* @var $relation ActiveQueryInterface|ActiveQuery */ - $relation = $model instanceof ActiveRecordInterface ? $model->getRelation($name) : (new $this->modelClass)->getRelation($name); + $relation = $model instanceof ActiveRecordInterface ? $model->getRelation($name) : (new $this->modelClass())->getRelation($name); if ($relation->multiple) { $buckets = $this->buildBuckets($primaryModels, $relation->link, null, null, false); diff --git a/framework/db/BaseActiveRecord.php b/framework/db/BaseActiveRecord.php index 05b95ab..9dcb5a9 100644 --- a/framework/db/BaseActiveRecord.php +++ b/framework/db/BaseActiveRecord.php @@ -7,14 +7,14 @@ namespace yii\db; -use yii\base\InvalidConfigException; use yii\base\Event; -use yii\base\Model; +use yii\base\InvalidCallException; +use yii\base\InvalidConfigException; use yii\base\InvalidParamException; +use yii\base\Model; use yii\base\ModelEvent; use yii\base\NotSupportedException; use yii\base\UnknownMethodException; -use yii\base\InvalidCallException; use yii\helpers\ArrayHelper; /** @@ -934,7 +934,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface */ public function beforeSave($insert) { - $event = new ModelEvent; + $event = new ModelEvent(); $this->trigger($insert ? self::EVENT_BEFORE_INSERT : self::EVENT_BEFORE_UPDATE, $event); return $event->isValid; @@ -986,7 +986,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface */ public function beforeDelete() { - $event = new ModelEvent; + $event = new ModelEvent(); $this->trigger(self::EVENT_BEFORE_DELETE, $event); return $event->isValid; @@ -1160,7 +1160,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface */ public static function instantiate($row) { - return new static; + return new static(); } /** @@ -1566,7 +1566,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface } catch (InvalidParamException $e) { return $this->generateAttributeLabel($attribute); } - $relatedModel = new $relation->modelClass; + $relatedModel = new $relation->modelClass(); } } @@ -1606,7 +1606,7 @@ abstract class BaseActiveRecord extends Model implements ActiveRecordInterface } catch (InvalidParamException $e) { return ''; } - $relatedModel = new $relation->modelClass; + $relatedModel = new $relation->modelClass(); } } diff --git a/framework/db/ColumnSchema.php b/framework/db/ColumnSchema.php index b2d0f19..dbec75e 100644 --- a/framework/db/ColumnSchema.php +++ b/framework/db/ColumnSchema.php @@ -137,7 +137,7 @@ class ColumnSchema extends Object // https://github.com/yiisoft/yii2/issues/9006 return (bool) $value && $value !== "\0"; case 'double': - return (double) $value; + return (float) $value; } return $value; diff --git a/framework/db/Command.php b/framework/db/Command.php index 7c451de..6034fa8 100644 --- a/framework/db/Command.php +++ b/framework/db/Command.php @@ -267,7 +267,7 @@ class Command extends Component } else { $this->pdoStatement->bindParam($name, $value, $dataType, $length, $driverOptions); } - $this->params[$name] =& $value; + $this->params[$name] = &$value; return $this; } diff --git a/framework/db/Query.php b/framework/db/Query.php index a97b655..832c21e 100644 --- a/framework/db/Query.php +++ b/framework/db/Query.php @@ -123,7 +123,7 @@ class Query extends Component implements QueryInterface if ($db === null) { $db = Yii::$app->getDb(); } - list ($sql, $params) = $db->getQueryBuilder()->build($this); + list($sql, $params) = $db->getQueryBuilder()->build($this); return $db->createCommand($sql, $params); } @@ -432,7 +432,7 @@ class Query extends Component implements QueryInterface return $command->queryScalar(); } else { - return (new Query)->select([$selectExpression]) + return (new self())->select([$selectExpression]) ->from(['c' => $this]) ->createCommand($db) ->queryScalar(); diff --git a/framework/db/QueryBuilder.php b/framework/db/QueryBuilder.php index 992bb53..9e7cfd1 100644 --- a/framework/db/QueryBuilder.php +++ b/framework/db/QueryBuilder.php @@ -225,7 +225,7 @@ class QueryBuilder extends \yii\base\Object foreach ($columns->select as $title => $field) { if (is_string($title)) { $names[] = $schema->quoteColumnName($title); - } else if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $field, $matches)) { + } elseif (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $field, $matches)) { $names[] = $schema->quoteColumnName($matches[2]); } else { $names[] = $schema->quoteColumnName($field); @@ -452,7 +452,7 @@ class QueryBuilder extends \yii\base\Object return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT ' . $this->db->quoteColumnName($name) . ' PRIMARY KEY (' - . implode(', ', $columns). ' )'; + . implode(', ', $columns) . ' )'; } /** @@ -648,7 +648,6 @@ class QueryBuilder extends \yii\base\Object */ public function addCommentOnColumn($table, $column, $comment) { - return 'COMMENT ON COLUMN ' . $this->db->quoteTableName($table) . '.' . $this->db->quoteColumnName($column) . ' IS ' . $this->db->quoteValue($comment); } @@ -829,7 +828,7 @@ class QueryBuilder extends \yii\base\Object throw new Exception('A join clause must be specified as an array of join type, join table, and optionally join condition.'); } // 0:join type, 1:join table, 2:on-condition (optional) - list ($joinType, $table) = $join; + list($joinType, $table) = $join; $tables = $this->quoteTableNames((array) $table, $params); $table = reset($tables); $joins[$i] = "$joinType $table"; diff --git a/framework/db/QueryTrait.php b/framework/db/QueryTrait.php index 932d28c..c5e1ecf 100644 --- a/framework/db/QueryTrait.php +++ b/framework/db/QueryTrait.php @@ -52,7 +52,7 @@ trait QueryTrait */ public $indexBy; /** - * @var boolean whether to emulate the actual query execution, returning empty or false results. + * @var bool whether to emulate the actual query execution, returning empty or false results. * @see emulateExecution() * @since 2.0.11 */ diff --git a/framework/db/Schema.php b/framework/db/Schema.php index 8b91241..5c71af8 100644 --- a/framework/db/Schema.php +++ b/framework/db/Schema.php @@ -8,9 +8,9 @@ namespace yii\db; use Yii; -use yii\base\Object; -use yii\base\NotSupportedException; use yii\base\InvalidCallException; +use yii\base\NotSupportedException; +use yii\base\Object; use yii\caching\CacheInterface; use yii\caching\TagDependency; @@ -511,7 +511,6 @@ abstract class Schema extends Object } return implode('.', $parts); - } /** @@ -631,7 +630,7 @@ abstract class Schema extends Object $exceptionClass = $class; } } - $message = $e->getMessage() . "\nThe SQL being executed was: $rawSql"; + $message = $e->getMessage() . "\nThe SQL being executed was: $rawSql"; $errorInfo = $e instanceof \PDOException ? $e->errorInfo : null; return new $exceptionClass($message, $errorInfo, (int) $e->getCode(), $e); } diff --git a/framework/db/SchemaBuilderTrait.php b/framework/db/SchemaBuilderTrait.php index 5b03c32..e7ff966 100644 --- a/framework/db/SchemaBuilderTrait.php +++ b/framework/db/SchemaBuilderTrait.php @@ -37,7 +37,7 @@ trait SchemaBuilderTrait /** * @return Connection the database connection to be used for schema building. */ - protected abstract function getDb(); + abstract protected function getDb(); /** * Creates a primary key column. diff --git a/framework/db/TableSchema.php b/framework/db/TableSchema.php index e13daab..e78e7be 100644 --- a/framework/db/TableSchema.php +++ b/framework/db/TableSchema.php @@ -7,8 +7,8 @@ namespace yii\db; -use yii\base\Object; use yii\base\InvalidParamException; +use yii\base\Object; /** * TableSchema represents the metadata of a database table. diff --git a/framework/db/cubrid/Schema.php b/framework/db/cubrid/Schema.php index dfea42e..39a9be2 100644 --- a/framework/db/cubrid/Schema.php +++ b/framework/db/cubrid/Schema.php @@ -7,9 +7,9 @@ namespace yii\db\cubrid; +use yii\db\ColumnSchema; use yii\db\Expression; use yii\db\TableSchema; -use yii\db\ColumnSchema; use yii\db\Transaction; /** diff --git a/framework/db/mssql/PDO.php b/framework/db/mssql/PDO.php index 6a776b2..196eaf5 100644 --- a/framework/db/mssql/PDO.php +++ b/framework/db/mssql/PDO.php @@ -76,7 +76,7 @@ class PDO extends \PDO return parent::getAttribute($attribute); } catch (\PDOException $e) { switch ($attribute) { - case PDO::ATTR_SERVER_VERSION: + case self::ATTR_SERVER_VERSION: return $this->query("SELECT CAST(SERVERPROPERTY('productversion') AS VARCHAR)")->fetchColumn(); default: throw $e; diff --git a/framework/db/mysql/Schema.php b/framework/db/mysql/Schema.php index 4ea23fa..b41ed37 100644 --- a/framework/db/mysql/Schema.php +++ b/framework/db/mysql/Schema.php @@ -7,9 +7,9 @@ namespace yii\db\mysql; +use yii\db\ColumnSchema; use yii\db\Expression; use yii\db\TableSchema; -use yii\db\ColumnSchema; /** * Schema is the class for retrieving metadata from a MySQL database (version 4.1.x and 5.x). @@ -92,7 +92,7 @@ class Schema extends \yii\db\Schema */ protected function loadTableSchema($name) { - $table = new TableSchema; + $table = new TableSchema(); $this->resolveTableNames($table, $name); if ($this->findColumns($table)) { diff --git a/framework/db/oci/QueryBuilder.php b/framework/db/oci/QueryBuilder.php index 3a5c813..d39696f 100644 --- a/framework/db/oci/QueryBuilder.php +++ b/framework/db/oci/QueryBuilder.php @@ -386,5 +386,4 @@ EOD; return $this->buildCondition(['AND', $condition], $params); } - } diff --git a/framework/db/oci/Schema.php b/framework/db/oci/Schema.php index 28d2b2f..7ab9c4c 100644 --- a/framework/db/oci/Schema.php +++ b/framework/db/oci/Schema.php @@ -172,7 +172,6 @@ SQL; */ protected function getTableSequenceName($tableName) { - $sequenceNameSql = <<size = trim($length) === '' ? null : (int)$length; - $column->precision = trim($precision) === '' ? null : (int)$precision; - $column->scale = trim($scale) === '' ? null : (int)$scale; + $column->size = trim($length) === '' ? null : (int) $length; + $column->precision = trim($precision) === '' ? null : (int) $precision; + $column->scale = trim($scale) === '' ? null : (int) $scale; } /** @@ -488,7 +487,7 @@ SQL; if (!empty($returnColumns)) { $columnSchemas = $tableSchema->columns; $returning = []; - foreach ((array)$returnColumns as $name) { + foreach ((array) $returnColumns as $name) { $phName = QueryBuilder::PARAM_PREFIX . (count($params) + count($returnParams)); $returnParams[$phName] = [ 'column' => $name, diff --git a/framework/db/pgsql/Schema.php b/framework/db/pgsql/Schema.php index 4831198..57f38f5 100644 --- a/framework/db/pgsql/Schema.php +++ b/framework/db/pgsql/Schema.php @@ -7,9 +7,9 @@ namespace yii\db\pgsql; +use yii\db\ColumnSchema; use yii\db\Expression; use yii\db\TableSchema; -use yii\db\ColumnSchema; use yii\db\ViewFinderTrait; /** @@ -434,7 +434,7 @@ SQL; if ($column->type === 'timestamp' && $column->defaultValue === 'now()') { $column->defaultValue = new Expression($column->defaultValue); } elseif ($column->type === 'boolean') { - $column->defaultValue = ($column->defaultValue === 'true'); + $column->defaultValue = ($column->defaultValue === 'true'); } elseif (stripos($column->dbType, 'bit') === 0 || stripos($column->dbType, 'varbit') === 0) { $column->defaultValue = bindec(trim($column->defaultValue, 'B\'')); } elseif (preg_match("/^'(.*?)'::/", $column->defaultValue, $matches)) { diff --git a/framework/db/sqlite/QueryBuilder.php b/framework/db/sqlite/QueryBuilder.php index 89b6bfb..491aeac 100644 --- a/framework/db/sqlite/QueryBuilder.php +++ b/framework/db/sqlite/QueryBuilder.php @@ -7,10 +7,9 @@ namespace yii\db\sqlite; -use yii\db\Connection; -use yii\db\Exception; use yii\base\InvalidParamException; use yii\base\NotSupportedException; +use yii\db\Connection; use yii\db\Expression; use yii\db\Query; @@ -166,7 +165,7 @@ class QueryBuilder extends \yii\db\QueryBuilder */ public function checkIntegrity($check = true, $schema = '', $table = '') { - return 'PRAGMA foreign_keys='.(int) $check; + return 'PRAGMA foreign_keys=' . (int) $check; } /** diff --git a/framework/db/sqlite/Schema.php b/framework/db/sqlite/Schema.php index 1b58c33..bd8299a 100644 --- a/framework/db/sqlite/Schema.php +++ b/framework/db/sqlite/Schema.php @@ -8,9 +8,9 @@ namespace yii\db\sqlite; use yii\base\NotSupportedException; +use yii\db\ColumnSchema; use yii\db\Expression; use yii\db\TableSchema; -use yii\db\ColumnSchema; use yii\db\Transaction; /** @@ -119,7 +119,7 @@ class Schema extends \yii\db\Schema */ protected function loadTableSchema($name) { - $table = new TableSchema; + $table = new TableSchema(); $table->name = $name; $table->fullName = $name; diff --git a/framework/di/Container.php b/framework/di/Container.php index 7726c93..2346fd5 100644 --- a/framework/di/Container.php +++ b/framework/di/Container.php @@ -330,7 +330,7 @@ class Container extends Component if (strpos($class, '\\') !== false) { $definition['class'] = $class; } else { - throw new InvalidConfigException("A class definition requires a \"class\" member."); + throw new InvalidConfigException('A class definition requires a "class" member.'); } } return $definition; @@ -361,7 +361,7 @@ class Container extends Component protected function build($class, $params, $config) { /* @var $reflection ReflectionClass */ - list ($reflection, $dependencies) = $this->getDependencies($class); + list($reflection, $dependencies) = $this->getDependencies($class); foreach ($params as $index => $param) { $dependencies[$index] = $param; @@ -546,7 +546,6 @@ class Container extends Component throw $e; } } - } } elseif ($associative && isset($params[$name])) { $args[] = $params[$name]; diff --git a/framework/di/Instance.php b/framework/di/Instance.php index 2300cc4..6b0823b 100644 --- a/framework/di/Instance.php +++ b/framework/di/Instance.php @@ -120,7 +120,7 @@ class Instance if ($type === null || $component instanceof $type) { return $component; } else { - throw new InvalidConfigException('Invalid data type: ' . $class .'. ' . $type . ' is expected.'); + 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/framework/di/NotInstantiableException.php b/framework/di/NotInstantiableException.php index 70898dd..e6f3e81 100644 --- a/framework/di/NotInstantiableException.php +++ b/framework/di/NotInstantiableException.php @@ -7,7 +7,7 @@ namespace yii\di; -use \yii\base\InvalidConfigException; +use yii\base\InvalidConfigException; /** * NotInstantiableException represents an exception caused by incorrect dependency injection container diff --git a/framework/di/ServiceLocator.php b/framework/di/ServiceLocator.php index 3bc8982..6fd064a 100644 --- a/framework/di/ServiceLocator.php +++ b/framework/di/ServiceLocator.php @@ -7,8 +7,8 @@ namespace yii\di; -use Yii; use Closure; +use Yii; use yii\base\Component; use yii\base\InvalidConfigException; diff --git a/framework/filters/AccessControl.php b/framework/filters/AccessControl.php index c228d66..eb02604 100644 --- a/framework/filters/AccessControl.php +++ b/framework/filters/AccessControl.php @@ -11,8 +11,8 @@ use Yii; use yii\base\Action; use yii\base\ActionFilter; use yii\di\Instance; -use yii\web\User; use yii\web\ForbiddenHttpException; +use yii\web\User; /** * AccessControl provides simple access control based on a set of rules. diff --git a/framework/filters/AccessRule.php b/framework/filters/AccessRule.php index 513a703..78b585e 100644 --- a/framework/filters/AccessRule.php +++ b/framework/filters/AccessRule.php @@ -8,12 +8,12 @@ namespace yii\filters; use Closure; -use yii\base\Component; use yii\base\Action; +use yii\base\Component; +use yii\base\Controller; use yii\base\InvalidConfigException; -use yii\web\User; use yii\web\Request; -use yii\base\Controller; +use yii\web\User; /** * This class represents an access rule defined by the [[AccessControl]] action filter diff --git a/framework/filters/ContentNegotiator.php b/framework/filters/ContentNegotiator.php index 86140bc..987ad55 100644 --- a/framework/filters/ContentNegotiator.php +++ b/framework/filters/ContentNegotiator.php @@ -11,8 +11,8 @@ use Yii; use yii\base\ActionFilter; use yii\base\BootstrapInterface; use yii\base\InvalidConfigException; -use yii\web\Response; use yii\web\Request; +use yii\web\Response; use yii\web\UnsupportedMediaTypeHttpException; /** @@ -151,8 +151,8 @@ class ContentNegotiator extends ActionFilter implements BootstrapInterface */ public function negotiate() { - $request = $this->request ? : Yii::$app->getRequest(); - $response = $this->response ? : Yii::$app->getResponse(); + $request = $this->request ?: Yii::$app->getRequest(); + $response = $this->response ?: Yii::$app->getResponse(); if (!empty($this->formats)) { $this->negotiateContentType($request, $response); } diff --git a/framework/filters/Cors.php b/framework/filters/Cors.php index d374f89..ce7b25e 100644 --- a/framework/filters/Cors.php +++ b/framework/filters/Cors.php @@ -196,7 +196,7 @@ class Cors extends ActionFilter if (in_array('*', $this->cors[$requestHeaderField])) { $responseHeaders[$responseHeaderField] = $this->headerize($requestHeaders[$requestHeaderField]); } else { - $requestedData = preg_split("/[\\s,]+/", $requestHeaders[$requestHeaderField], -1, PREG_SPLIT_NO_EMPTY); + $requestedData = preg_split('/[\\s,]+/', $requestHeaders[$requestHeaderField], -1, PREG_SPLIT_NO_EMPTY); $acceptedData = array_uintersect($requestedData, $this->cors[$requestHeaderField], 'strcasecmp'); if (!empty($acceptedData)) { $responseHeaders[$responseHeaderField] = implode(', ', $acceptedData); @@ -228,7 +228,7 @@ class Cors extends ActionFilter */ protected function headerize($string) { - $headers = preg_split("/[\\s,]+/", $string, -1, PREG_SPLIT_NO_EMPTY); + $headers = preg_split('/[\\s,]+/', $string, -1, PREG_SPLIT_NO_EMPTY); $headers = array_map(function ($element) { return str_replace(' ', '-', ucwords(strtolower(str_replace(['_', '-'], [' ', ' '], $element)))); }, $headers); diff --git a/framework/filters/HostControl.php b/framework/filters/HostControl.php index bbc9402..2d7a423 100644 --- a/framework/filters/HostControl.php +++ b/framework/filters/HostControl.php @@ -129,7 +129,7 @@ class HostControl extends ActionFilter } if (!is_array($allowedHosts) && !$allowedHosts instanceof \Traversable) { - $allowedHosts = (array)$allowedHosts; + $allowedHosts = (array) $allowedHosts; } $currentHost = Yii::$app->getRequest()->getHostName(); diff --git a/framework/filters/HttpCache.php b/framework/filters/HttpCache.php index 7732b20..00f384a 100644 --- a/framework/filters/HttpCache.php +++ b/framework/filters/HttpCache.php @@ -8,8 +8,8 @@ namespace yii\filters; use Yii; -use yii\base\ActionFilter; use yii\base\Action; +use yii\base\ActionFilter; /** * HttpCache implements client-side caching by utilizing the `Last-Modified` and `ETag` HTTP headers. @@ -206,7 +206,7 @@ class HttpCache extends ActionFilter */ protected function generateEtag($seed) { - $etag = '"' . rtrim(base64_encode(sha1($seed, true)), '=') . '"'; + $etag = '"' . rtrim(base64_encode(sha1($seed, true)), '=') . '"'; return $this->weakEtag ? 'W/' . $etag : $etag; } } diff --git a/framework/filters/PageCache.php b/framework/filters/PageCache.php index 605e10a..cff555f 100644 --- a/framework/filters/PageCache.php +++ b/framework/filters/PageCache.php @@ -249,7 +249,7 @@ class PageCache extends ActionFilter $data = [ 'cacheVersion' => 1, 'cacheData' => is_array($beforeCacheResponseResult) ? $beforeCacheResponseResult : null, - 'content' => ob_get_clean() + 'content' => ob_get_clean(), ]; if ($data['content'] === false || $data['content'] === '') { return; diff --git a/framework/filters/RateLimiter.php b/framework/filters/RateLimiter.php index 4feaff2..8e6f4fa 100644 --- a/framework/filters/RateLimiter.php +++ b/framework/filters/RateLimiter.php @@ -108,8 +108,8 @@ class RateLimiter extends ActionFilter { $current = time(); - list ($limit, $window) = $user->getRateLimit($request, $action); - list ($allowance, $timestamp) = $user->loadAllowance($request, $action); + list($limit, $window) = $user->getRateLimit($request, $action); + list($allowance, $timestamp) = $user->loadAllowance($request, $action); $allowance += (int) (($current - $timestamp) * $limit / $window); if ($allowance > $limit) { diff --git a/framework/filters/auth/AuthInterface.php b/framework/filters/auth/AuthInterface.php index f12518c..492d314 100644 --- a/framework/filters/auth/AuthInterface.php +++ b/framework/filters/auth/AuthInterface.php @@ -7,11 +7,11 @@ namespace yii\filters\auth; -use yii\web\User; +use yii\web\IdentityInterface; use yii\web\Request; use yii\web\Response; -use yii\web\IdentityInterface; use yii\web\UnauthorizedHttpException; +use yii\web\User; /** * AuthInterface is the interface that should be implemented by auth method classes. diff --git a/framework/filters/auth/AuthMethod.php b/framework/filters/auth/AuthMethod.php index b13f02e..fe8f25c 100644 --- a/framework/filters/auth/AuthMethod.php +++ b/framework/filters/auth/AuthMethod.php @@ -10,10 +10,10 @@ namespace yii\filters\auth; use Yii; use yii\base\Action; use yii\base\ActionFilter; -use yii\web\UnauthorizedHttpException; -use yii\web\User; use yii\web\Request; use yii\web\Response; +use yii\web\UnauthorizedHttpException; +use yii\web\User; /** * AuthMethod is a base class implementing the [[AuthInterface]] interface. @@ -51,12 +51,12 @@ abstract class AuthMethod extends ActionFilter implements AuthInterface */ public function beforeAction($action) { - $response = $this->response ? : Yii::$app->getResponse(); + $response = $this->response ?: Yii::$app->getResponse(); try { $identity = $this->authenticate( - $this->user ? : Yii::$app->getUser(), - $this->request ? : Yii::$app->getRequest(), + $this->user ?: Yii::$app->getUser(), + $this->request ?: Yii::$app->getRequest(), $response ); } catch (UnauthorizedHttpException $e) { diff --git a/framework/filters/auth/CompositeAuth.php b/framework/filters/auth/CompositeAuth.php index 0465723..3a532a4 100644 --- a/framework/filters/auth/CompositeAuth.php +++ b/framework/filters/auth/CompositeAuth.php @@ -85,7 +85,7 @@ class CompositeAuth extends AuthMethod public function challenge($response) { foreach ($this->authMethods as $method) { - /** @var $method AuthInterface */ + /* @var $method AuthInterface */ $method->challenge($response); } } diff --git a/framework/grid/DataColumn.php b/framework/grid/DataColumn.php index f3749e2..1466dbc 100644 --- a/framework/grid/DataColumn.php +++ b/framework/grid/DataColumn.php @@ -144,11 +144,11 @@ class DataColumn extends Column if ($this->label === null) { if ($provider instanceof ActiveDataProvider && $provider->query instanceof ActiveQueryInterface) { /* @var $model Model */ - $model = new $provider->query->modelClass; + $model = new $provider->query->modelClass(); $label = $model->getAttributeLabel($this->attribute); } elseif ($provider instanceof ArrayDataProvider && $provider->modelClass !== null) { /* @var $model Model */ - $model = new $provider->modelClass; + $model = new $provider->modelClass(); $label = $model->getAttributeLabel($this->attribute); } elseif ($this->grid->filterModel !== null && $this->grid->filterModel instanceof Model) { $label = $this->grid->filterModel->getAttributeLabel($this->attribute); diff --git a/framework/grid/GridView.php b/framework/grid/GridView.php index c6e0175..3e9d47a 100644 --- a/framework/grid/GridView.php +++ b/framework/grid/GridView.php @@ -7,15 +7,15 @@ namespace yii\grid; -use Yii; use Closure; -use yii\i18n\Formatter; +use Yii; use yii\base\InvalidConfigException; -use yii\helpers\Url; +use yii\base\Model; use yii\helpers\Html; use yii\helpers\Json; +use yii\helpers\Url; +use yii\i18n\Formatter; use yii\widgets\BaseListView; -use yii\base\Model; /** * The GridView widget is used to display data in a grid. @@ -529,7 +529,7 @@ class GridView extends BaseListView $column = $this->createDataColumn($column); } else { $column = Yii::createObject(array_merge([ - 'class' => $this->dataColumnClass ? : DataColumn::className(), + 'class' => $this->dataColumnClass ?: DataColumn::className(), 'grid' => $this, ], $column)); } @@ -554,7 +554,7 @@ class GridView extends BaseListView } return Yii::createObject([ - 'class' => $this->dataColumnClass ? : DataColumn::className(), + 'class' => $this->dataColumnClass ?: DataColumn::className(), 'grid' => $this, 'attribute' => $matches[1], 'format' => isset($matches[3]) ? $matches[3] : 'text', diff --git a/framework/helpers/BaseArrayHelper.php b/framework/helpers/BaseArrayHelper.php index 6b5186b..54ee6c4 100644 --- a/framework/helpers/BaseArrayHelper.php +++ b/framework/helpers/BaseArrayHelper.php @@ -194,7 +194,7 @@ class BaseArrayHelper $key = $lastKey; } - if (is_array($array) && (isset($array[$key]) || array_key_exists($key, $array)) ) { + if (is_array($array) && (isset($array[$key]) || array_key_exists($key, $array))) { return $array[$key]; } @@ -380,7 +380,7 @@ class BaseArrayHelper public static function index($array, $key, $groups = []) { $result = []; - $groups = (array)$groups; + $groups = (array) $groups; foreach ($array as $element) { $lastArray = &$result; diff --git a/framework/helpers/BaseConsole.php b/framework/helpers/BaseConsole.php index b42678e..626a544 100644 --- a/framework/helpers/BaseConsole.php +++ b/framework/helpers/BaseConsole.php @@ -20,36 +20,36 @@ use yii\console\Markdown as ConsoleMarkdown; class BaseConsole { // foreground color control codes - const FG_BLACK = 30; - const FG_RED = 31; - const FG_GREEN = 32; + const FG_BLACK = 30; + const FG_RED = 31; + const FG_GREEN = 32; const FG_YELLOW = 33; - const FG_BLUE = 34; + const FG_BLUE = 34; const FG_PURPLE = 35; - const FG_CYAN = 36; - const FG_GREY = 37; + const FG_CYAN = 36; + const FG_GREY = 37; // background color control codes - const BG_BLACK = 40; - const BG_RED = 41; - const BG_GREEN = 42; + const BG_BLACK = 40; + const BG_RED = 41; + const BG_GREEN = 42; const BG_YELLOW = 43; - const BG_BLUE = 44; + const BG_BLUE = 44; const BG_PURPLE = 45; - const BG_CYAN = 46; - const BG_GREY = 47; + const BG_CYAN = 46; + const BG_GREY = 47; // fonts style control codes - const RESET = 0; - const NORMAL = 0; - const BOLD = 1; - const ITALIC = 3; - const UNDERLINE = 4; - const BLINK = 5; - const NEGATIVE = 7; - const CONCEALED = 8; + const RESET = 0; + const NORMAL = 0; + const BOLD = 1; + const ITALIC = 3; + const UNDERLINE = 4; + const BLINK = 5; + const NEGATIVE = 7; + const CONCEALED = 8; const CROSSED_OUT = 9; - const FRAMED = 51; - const ENCIRCLED = 52; - const OVERLINED = 53; + const FRAMED = 51; + const ENCIRCLED = 52; + const OVERLINED = 53; /** @@ -357,31 +357,31 @@ class BaseConsole { $styleMap = [ // http://www.w3.org/TR/CSS2/syndata.html#value-def-color - self::FG_BLACK => ['color' => 'black'], - self::FG_BLUE => ['color' => 'blue'], - self::FG_CYAN => ['color' => 'aqua'], - self::FG_GREEN => ['color' => 'lime'], - self::FG_GREY => ['color' => 'silver'], + self::FG_BLACK => ['color' => 'black'], + self::FG_BLUE => ['color' => 'blue'], + self::FG_CYAN => ['color' => 'aqua'], + self::FG_GREEN => ['color' => 'lime'], + self::FG_GREY => ['color' => 'silver'], // http://meyerweb.com/eric/thoughts/2014/06/19/rebeccapurple/ // http://dev.w3.org/csswg/css-color/#valuedef-rebeccapurple - self::FG_PURPLE => ['color' => 'rebeccapurple'], - self::FG_RED => ['color' => 'red'], - self::FG_YELLOW => ['color' => 'yellow'], - self::BG_BLACK => ['background-color' => 'black'], - self::BG_BLUE => ['background-color' => 'blue'], - self::BG_CYAN => ['background-color' => 'aqua'], - self::BG_GREEN => ['background-color' => 'lime'], - self::BG_GREY => ['background-color' => 'silver'], - self::BG_PURPLE => ['background-color' => 'rebeccapurple'], - self::BG_RED => ['background-color' => 'red'], - self::BG_YELLOW => ['background-color' => 'yellow'], - self::BOLD => ['font-weight' => 'bold'], - self::ITALIC => ['font-style' => 'italic'], - self::UNDERLINE => ['text-decoration' => ['underline']], - self::OVERLINED => ['text-decoration' => ['overline']], + self::FG_PURPLE => ['color' => 'rebeccapurple'], + self::FG_RED => ['color' => 'red'], + self::FG_YELLOW => ['color' => 'yellow'], + self::BG_BLACK => ['background-color' => 'black'], + self::BG_BLUE => ['background-color' => 'blue'], + self::BG_CYAN => ['background-color' => 'aqua'], + self::BG_GREEN => ['background-color' => 'lime'], + self::BG_GREY => ['background-color' => 'silver'], + self::BG_PURPLE => ['background-color' => 'rebeccapurple'], + self::BG_RED => ['background-color' => 'red'], + self::BG_YELLOW => ['background-color' => 'yellow'], + self::BOLD => ['font-weight' => 'bold'], + self::ITALIC => ['font-style' => 'italic'], + self::UNDERLINE => ['text-decoration' => ['underline']], + self::OVERLINED => ['text-decoration' => ['overline']], self::CROSSED_OUT => ['text-decoration' => ['line-through']], - self::BLINK => ['text-decoration' => ['blink']], - self::CONCEALED => ['visibility' => 'hidden'], + self::BLINK => ['text-decoration' => ['blink']], + self::CONCEALED => ['visibility' => 'hidden'], ] + $styleMap; $tags = 0; @@ -561,7 +561,6 @@ class BaseConsole * * @param string $string String to escape * - * @access public * @return string */ public static function escape($string) @@ -624,12 +623,12 @@ class BaseConsole // Linux stty output if (preg_match('/rows\s+(\d+);\s*columns\s+(\d+);/mi', $stty, $matches)) { - return $size = [(int)$matches[2], (int)$matches[1]]; + return $size = [(int) $matches[2], (int) $matches[1]]; } // MacOS stty output if (preg_match('/(\d+)\s+rows;\s*(\d+)\s+columns;/mi', $stty, $matches)) { - return $size = [(int)$matches[2], (int)$matches[1]]; + return $size = [(int) $matches[2], (int) $matches[1]]; } } @@ -777,15 +776,15 @@ class BaseConsole { $options = ArrayHelper::merge( [ - 'required' => false, - 'default' => null, - 'pattern' => null, + 'required' => false, + 'default' => null, + 'pattern' => null, 'validator' => null, - 'error' => 'Invalid input.', + 'error' => 'Invalid input.', ], $options ); - $error = null; + $error = null; top: $input = $options['default'] diff --git a/framework/helpers/BaseFormatConverter.php b/framework/helpers/BaseFormatConverter.php index 0c1a6ca..32f1664 100644 --- a/framework/helpers/BaseFormatConverter.php +++ b/framework/helpers/BaseFormatConverter.php @@ -75,10 +75,10 @@ class BaseFormatConverter ]; private static $_icuShortFormats = [ - 'short' => 3, // IntlDateFormatter::SHORT, + 'short' => 3, // IntlDateFormatter::SHORT, 'medium' => 2, // IntlDateFormatter::MEDIUM, - 'long' => 1, // IntlDateFormatter::LONG, - 'full' => 0, // IntlDateFormatter::FULL, + 'long' => 1, // IntlDateFormatter::LONG, + 'full' => 0, // IntlDateFormatter::FULL, ]; @@ -125,19 +125,19 @@ class BaseFormatConverter if (preg_match_all('/(? '\\\'', // two single quotes produce one - 'G' => '', // era designator like (Anno Domini) + 'G' => '', // era designator like (Anno Domini) 'Y' => 'o', // 4digit year of "Week of Year" 'y' => 'Y', // 4digit year e.g. 2014 'yyyy' => 'Y', // 4digit year e.g. 2014 'yy' => 'y', // 2digit year number eg. 14 'u' => '', // extended year e.g. 4601 'U' => '', // cyclic year name, as in Chinese lunar calendar - 'r' => '', // related Gregorian year e.g. 1996 + 'r' => '', // related Gregorian year e.g. 1996 'Q' => '', // number of quarter 'QQ' => '', // number of quarter '02' 'QQQ' => '', // quarter 'Q2' @@ -152,7 +152,7 @@ class BaseFormatConverter 'MM' => 'm', // Numeric representation of a month, with leading zeros 'MMM' => 'M', // A short textual representation of a month, three letters 'MMMM' => 'F', // A full textual representation of a month, such as January or March - 'MMMMM' => '', // + 'MMMMM' => '', 'L' => 'n', // Stand alone month in year 'LL' => 'm', // Stand alone month in year 'LLL' => 'M', // Stand alone month in year @@ -205,7 +205,7 @@ class BaseFormatConverter 'z' => 'T', // Timezone abbreviation 'zz' => 'T', // Timezone abbreviation 'zzz' => 'T', // Timezone abbreviation - 'zzzz' => 'T', // Timzone full name, not supported by php but we fallback + 'zzzz' => 'T', // Timezone full name, not supported by php but we fallback 'Z' => 'O', // Difference to Greenwich time (GMT) in hours 'ZZ' => 'O', // Difference to Greenwich time (GMT) in hours 'ZZZ' => 'O', // Difference to Greenwich time (GMT) in hours @@ -225,8 +225,8 @@ class BaseFormatConverter 'XXXX' => '', // Time Zone: ISO8601 basic hms?, with Z, e.g. -0800, -075258, Z 'XXXXX' => '', // Time Zone: ISO8601 extended hms?, with Z, e.g. -08:00, -07:52:58, Z 'x' => '', // Time Zone: ISO8601 basic hm?, without Z for 0, e.g. -08, +0530 - 'xx' => 'O', // Time Zone: ISO8601 basic hm, without Z, e.g. -0800 - 'xxx' => 'P', // Time Zone: ISO8601 extended hm, without Z, e.g. -08:00 + 'xx' => 'O', // Time Zone: ISO8601 basic hm, without Z, e.g. -0800 + 'xxx' => 'P', // Time Zone: ISO8601 extended hm, without Z, e.g. -08:00 'xxxx' => '', // Time Zone: ISO8601 basic hms?, without Z, e.g. -0800, -075258 'xxxxx' => '', // Time Zone: ISO8601 extended hms?, without Z, e.g. -08:00, -07:52:58 ])); @@ -290,7 +290,7 @@ class BaseFormatConverter 'O' => 'xx', // Difference to Greenwich time (GMT) in hours, Example: +0200 'P' => 'xxx', // Difference to Greenwich time (GMT) with colon between hours and minutes, Example: +02:00 'T' => 'zzz', // Timezone abbreviation, Examples: EST, MDT ... - 'Z' => '', // Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. -43200 through 50400 + 'Z' => '', // Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. -43200 through 50400 // Full Date/Time 'c' => 'yyyy-MM-dd\'T\'HH:mm:ssxxx', // ISO 8601 date, e.g. 2004-02-12T15:19:21+00:00 'r' => 'eee, dd MMM yyyy HH:mm:ss xx', // RFC 2822 formatted date, Example: Thu, 21 Dec 2000 16:01:07 +0200 @@ -358,11 +358,11 @@ class BaseFormatConverter 'qqq' => '', // Stand Alone quarter 'Q2' 'qqqq' => '', // Stand Alone quarter '2nd quarter' 'qqqqq' => '', // number of Stand Alone quarter '2' - 'M' => 'm', // Numeric representation of a month, without leading zeros + 'M' => 'm', // Numeric representation of a month, without leading zeros 'MM' => 'mm', // Numeric representation of a month, with leading zeros 'MMM' => 'M', // A short textual representation of a month, three letters 'MMMM' => 'MM', // A full textual representation of a month, such as January or March - 'MMMMM' => '', // + 'MMMMM' => '', 'L' => 'm', // Stand alone month in year 'LL' => 'mm', // Stand alone month in year 'LLL' => 'M', // Stand alone month in year @@ -415,14 +415,14 @@ class BaseFormatConverter 'z' => '', // Timezone abbreviation 'zz' => '', // Timezone abbreviation 'zzz' => '', // Timezone abbreviation - 'zzzz' => '', // Timzone full name, not supported by php but we fallback + 'zzzz' => '', // Timezone full name, not supported by php but we fallback 'Z' => '', // Difference to Greenwich time (GMT) in hours 'ZZ' => '', // Difference to Greenwich time (GMT) in hours 'ZZZ' => '', // Difference to Greenwich time (GMT) in hours 'ZZZZ' => '', // Time Zone: long localized GMT (=OOOO) e.g. GMT-08:00 - 'ZZZZZ' => '', // TIme Zone: ISO8601 extended hms? (=XXXXX) + 'ZZZZZ' => '', // Time Zone: ISO8601 extended hms? (=XXXXX) 'O' => '', // Time Zone: short localized GMT e.g. GMT-8 - 'OOOO' => '', // Time Zone: long localized GMT (=ZZZZ) e.g. GMT-08:00 + 'OOOO' => '', // Time Zone: long localized GMT (=ZZZZ) e.g. GMT-08:00 'v' => '', // Time Zone: generic non-location (falls back first to VVVV and then to OOOO) using the ICU defined fallback here 'vvvv' => '', // Time Zone: generic non-location (falls back first to VVVV and then to OOOO) using the ICU defined fallback here 'V' => '', // Time Zone: short time zone ID diff --git a/framework/helpers/BaseHtml.php b/framework/helpers/BaseHtml.php index a9bc453..c5914b9 100644 --- a/framework/helpers/BaseHtml.php +++ b/framework/helpers/BaseHtml.php @@ -9,10 +9,10 @@ namespace yii\helpers; use Yii; use yii\base\InvalidParamException; +use yii\base\Model; use yii\db\ActiveRecordInterface; use yii\validators\StringValidator; use yii\web\Request; -use yii\base\Model; /** * BaseHtml provides concrete implementation for [[Html]]. diff --git a/framework/helpers/BaseJson.php b/framework/helpers/BaseJson.php index 28b2af3..eef9d0b 100644 --- a/framework/helpers/BaseJson.php +++ b/framework/helpers/BaseJson.php @@ -7,8 +7,8 @@ namespace yii\helpers; -use yii\base\InvalidParamException; use yii\base\Arrayable; +use yii\base\InvalidParamException; use yii\web\JsExpression; /** diff --git a/framework/helpers/BaseStringHelper.php b/framework/helpers/BaseStringHelper.php index 6e5eae3..12c9343 100644 --- a/framework/helpers/BaseStringHelper.php +++ b/framework/helpers/BaseStringHelper.php @@ -166,7 +166,7 @@ class BaseStringHelper ++$depth; } elseif ($token instanceof \HTMLPurifier_Token_Text && $totalCount <= $count) { //Text if (false === $encoding) { - preg_match('/^(\s*)/um', $token->data, $prefixSpace) ?: $prefixSpace = ['','']; + preg_match('/^(\s*)/um', $token->data, $prefixSpace) ?: $prefixSpace = ['', '']; $token->data = $prefixSpace[1] . self::truncateWords(ltrim($token->data), $count - $totalCount, ''); $currentCount = self::countWords($token->data); } else { @@ -176,7 +176,7 @@ class BaseStringHelper $totalCount += $currentCount; $truncated[] = $token; } elseif ($token instanceof \HTMLPurifier_Token_End) { //Tag ends - if ($token->name === $openTokens[$depth-1]) { + if ($token->name === $openTokens[$depth - 1]) { --$depth; unset($openTokens[$depth]); $truncated[] = $token; diff --git a/framework/i18n/DbMessageSource.php b/framework/i18n/DbMessageSource.php index e2c9cd1..5bfaece 100644 --- a/framework/i18n/DbMessageSource.php +++ b/framework/i18n/DbMessageSource.php @@ -10,11 +10,11 @@ namespace yii\i18n; use Yii; use yii\base\InvalidConfigException; use yii\caching\CacheInterface; +use yii\db\Connection; use yii\db\Expression; +use yii\db\Query; use yii\di\Instance; use yii\helpers\ArrayHelper; -use yii\db\Connection; -use yii\db\Query; /** * DbMessageSource extends [[MessageSource]] and represents a message source that stores translated @@ -183,7 +183,7 @@ class DbMessageSource extends MessageSource 't1.category' => $category, 't2.language' => $fallbackLanguage, ])->andWhere([ - 'NOT IN', 't2.id', (new Query())->select('[[id]]')->from($this->messageTable)->where(['language' => $language]) + 'NOT IN', 't2.id', (new Query())->select('[[id]]')->from($this->messageTable)->where(['language' => $language]), ]); } } diff --git a/framework/i18n/Formatter.php b/framework/i18n/Formatter.php index a3db2ac..11b6c0b 100644 --- a/framework/i18n/Formatter.php +++ b/framework/i18n/Formatter.php @@ -18,8 +18,8 @@ use yii\base\Component; use yii\base\InvalidConfigException; use yii\base\InvalidParamException; use yii\helpers\FormatConverter; -use yii\helpers\HtmlPurifier; use yii\helpers\Html; +use yii\helpers\HtmlPurifier; /** * Formatter provides a set of commonly used data formatting methods. @@ -577,10 +577,10 @@ class Formatter extends Component * @var array map of short format names to IntlDateFormatter constant values. */ private $_dateFormats = [ - 'short' => 3, // IntlDateFormatter::SHORT, + 'short' => 3, // IntlDateFormatter::SHORT, 'medium' => 2, // IntlDateFormatter::MEDIUM, - 'long' => 1, // IntlDateFormatter::LONG, - 'full' => 0, // IntlDateFormatter::FULL, + 'long' => 1, // IntlDateFormatter::LONG, + 'full' => 0, // IntlDateFormatter::FULL, ]; /** @@ -691,7 +691,7 @@ class Formatter extends Component } try { if (is_numeric($value)) { // process as unix timestamp, which is always in UTC - $timestamp = new DateTime('@' . (int)$value, new DateTimeZone('UTC')); + $timestamp = new DateTime('@' . (int) $value, new DateTimeZone('UTC')); return $checkDateTimeInfo ? [$timestamp, true, true] : $timestamp; } elseif (($timestamp = DateTime::createFromFormat('Y-m-d', $value, new DateTimeZone($this->defaultTimeZone))) !== false) { // try Y-m-d format (support invalid dates like 2012-13-01) return $checkDateTimeInfo ? [$timestamp, false, true] : $timestamp; @@ -705,7 +705,7 @@ class Formatter extends Component return [ $timestamp, !($info['hour'] === false && $info['minute'] === false && $info['second'] === false), - !($info['year'] === false && $info['month'] === false && $info['day'] === false) + !($info['year'] === false && $info['month'] === false && $info['day'] === false), ]; } else { return new DateTime($value, new DateTimeZone($this->defaultTimeZone)); @@ -872,7 +872,7 @@ class Formatter extends Component $valueDateTime = (new DateTime())->setTimestamp(abs($value)); $interval = $valueDateTime->diff($zeroDateTime); } elseif (strpos($value, 'P-') === 0) { - $interval = new DateInterval('P'.substr($value, 2)); + $interval = new DateInterval('P' . substr($value, 2)); $isNegative = true; } else { $interval = new DateInterval($value); diff --git a/framework/i18n/GettextMoFile.php b/framework/i18n/GettextMoFile.php index 4692bda..8aaf6be 100644 --- a/framework/i18n/GettextMoFile.php +++ b/framework/i18n/GettextMoFile.php @@ -111,7 +111,7 @@ class GettextMoFile extends GettextFile if ((!$context && $separatorPosition === false) || ($context && $separatorPosition !== false && strncmp($id, $context, $separatorPosition) === 0)) { if ($separatorPosition !== false) { - $id = substr($id, $separatorPosition+1); + $id = substr($id, $separatorPosition + 1); } $message = $this->readString($fileHandle, $targetLengths[$i], $targetOffsets[$i]); @@ -270,6 +270,6 @@ class GettextMoFile extends GettextFile */ protected function writeString($fileHandle, $string) { - return $this->writeBytes($fileHandle, $string. "\0"); + return $this->writeBytes($fileHandle, $string . "\0"); } } diff --git a/framework/i18n/GettextPoFile.php b/framework/i18n/GettextPoFile.php index 55770ec..d3473e2 100644 --- a/framework/i18n/GettextPoFile.php +++ b/framework/i18n/GettextPoFile.php @@ -66,7 +66,7 @@ class GettextPoFile extends GettextFile '"Language: ' . $language . '\n"', '"MIME-Version: 1.0\n"', '"Content-Type: text/plain; charset=' . Yii::$app->charset . '\n"', - '"Content-Transfer-Encoding: 8bit\n"' + '"Content-Transfer-Encoding: 8bit\n"', ]; $content = implode("\n", $headers) . "\n\n"; foreach ($messages as $id => $message) { diff --git a/framework/log/DbTarget.php b/framework/log/DbTarget.php index 0392f5e..9528815 100644 --- a/framework/log/DbTarget.php +++ b/framework/log/DbTarget.php @@ -8,8 +8,8 @@ namespace yii\log; use Yii; -use yii\db\Connection; use yii\base\InvalidConfigException; +use yii\db\Connection; use yii\di\Instance; use yii\helpers\VarDumper; diff --git a/framework/log/Logger.php b/framework/log/Logger.php index 87b48fc..7124b2f 100644 --- a/framework/log/Logger.php +++ b/framework/log/Logger.php @@ -279,9 +279,9 @@ class Logger extends Component $memory = isset($log[5]) ? $log[5] : 0; $log[6] = $i; $hash = md5(serialize($token)); - if ($level == Logger::LEVEL_PROFILE_BEGIN) { + if ($level == self::LEVEL_PROFILE_BEGIN) { $stack[$hash] = $log; - } elseif ($level == Logger::LEVEL_PROFILE_END) { + } elseif ($level == self::LEVEL_PROFILE_END) { if (isset($stack[$hash])) { $timings[$stack[$hash][6]] = [ 'info' => $stack[$hash][0], @@ -318,7 +318,7 @@ class Logger extends Component self::LEVEL_TRACE => 'trace', self::LEVEL_PROFILE_BEGIN => 'profile begin', self::LEVEL_PROFILE_END => 'profile end', - self::LEVEL_PROFILE => 'profile' + self::LEVEL_PROFILE => 'profile', ]; return isset($levels[$level]) ? $levels[$level] : 'unknown'; diff --git a/framework/mail/BaseMessage.php b/framework/mail/BaseMessage.php index 1a0c73e..973ba63 100644 --- a/framework/mail/BaseMessage.php +++ b/framework/mail/BaseMessage.php @@ -7,9 +7,9 @@ namespace yii\mail; +use Yii; use yii\base\ErrorHandler; use yii\base\Object; -use Yii; /** * BaseMessage serves as a base class that implements the [[send()]] method required by [[MessageInterface]]. diff --git a/framework/messages/bs/yii.php b/framework/messages/bs/yii.php index 695a595..810f89f 100644 --- a/framework/messages/bs/yii.php +++ b/framework/messages/bs/yii.php @@ -111,4 +111,4 @@ return [ '{nFormatted} {n, plural, =1{petabyte} other{petabytes}}' => '{nFormatted} {n, plural, =1{petabajt} other{petabajta}}', '{nFormatted} {n, plural, =1{tebibyte} other{tebibytes}}' => '{nFormatted} {n, plural, =1{tebibajt} other{tebibajta}}', '{nFormatted} {n, plural, =1{terabyte} other{terabytes}}' => '{nFormatted} {n, plural, =1{terabajt} other{terabajta}}', -]; \ No newline at end of file +]; diff --git a/framework/mutex/DbMutex.php b/framework/mutex/DbMutex.php index aa27005..b47188f 100644 --- a/framework/mutex/DbMutex.php +++ b/framework/mutex/DbMutex.php @@ -7,8 +7,8 @@ namespace yii\mutex; -use yii\db\Connection; use yii\base\InvalidConfigException; +use yii\db\Connection; use yii\di\Instance; /** diff --git a/framework/mutex/OracleMutex.php b/framework/mutex/OracleMutex.php index bf78add..52d5cf5 100644 --- a/framework/mutex/OracleMutex.php +++ b/framework/mutex/OracleMutex.php @@ -85,9 +85,9 @@ class OracleMutex extends DbMutex /** clean vars before using */ $releaseOnCommit = $this->releaseOnCommit ? 'TRUE' : 'FALSE'; - $timeout = abs((int)$timeout); + $timeout = abs((int) $timeout); - /** inside pl/sql scopes pdo binding not working correctly :( */ + // inside pl/sql scopes pdo binding not working correctly :( $this->db->createCommand( 'DECLARE handle VARCHAR2(128); @@ -100,7 +100,7 @@ END;', ->bindParam(':lockStatus', $lockStatus, PDO::PARAM_INT, 1) ->execute(); - return ($lockStatus === 0 || $lockStatus === '0'); + return $lockStatus === 0 || $lockStatus === '0'; } /** @@ -124,6 +124,6 @@ END;', ->bindParam(':result', $releaseStatus, PDO::PARAM_INT, 1) ->execute(); - return ($releaseStatus === 0 || $releaseStatus === '0'); + return $releaseStatus === 0 || $releaseStatus === '0'; } } diff --git a/framework/rbac/DbManager.php b/framework/rbac/DbManager.php index 4bffc4f..8a07a22 100644 --- a/framework/rbac/DbManager.php +++ b/framework/rbac/DbManager.php @@ -8,12 +8,12 @@ namespace yii\rbac; use Yii; +use yii\base\InvalidCallException; +use yii\base\InvalidParamException; use yii\caching\CacheInterface; use yii\db\Connection; -use yii\db\Query; use yii\db\Expression; -use yii\base\InvalidCallException; -use yii\base\InvalidParamException; +use yii\db\Query; use yii\di\Instance; /** @@ -204,7 +204,7 @@ class DbManager extends BaseManager return true; } - $query = new Query; + $query = new Query(); $parents = $query->select(['parent']) ->from($this->itemChildTable) ->where(['child' => $itemName]) @@ -231,7 +231,7 @@ class DbManager extends BaseManager return $this->items[$name]; } - $row = (new Query)->from($this->itemTable) + $row = (new Query())->from($this->itemTable) ->where(['name' => $name]) ->one($this->db); @@ -415,7 +415,7 @@ class DbManager extends BaseManager */ protected function getItems($type) { - $query = (new Query) + $query = (new Query()) ->from($this->itemTable) ->where(['type' => $type]); @@ -460,7 +460,7 @@ class DbManager extends BaseManager return []; } - $query = (new Query)->select('b.*') + $query = (new Query())->select('b.*') ->from(['a' => $this->assignmentTable, 'b' => $this->itemTable]) ->where('{{a}}.[[item_name]]={{b}}.[[name]]') ->andWhere(['a.user_id' => (string) $userId]) @@ -507,7 +507,7 @@ class DbManager extends BaseManager if (empty($result)) { return []; } - $query = (new Query)->from($this->itemTable)->where([ + $query = (new Query())->from($this->itemTable)->where([ 'type' => Item::TYPE_PERMISSION, 'name' => array_keys($result), ]); @@ -541,7 +541,7 @@ class DbManager extends BaseManager */ protected function getDirectPermissionsByUser($userId) { - $query = (new Query)->select('b.*') + $query = (new Query())->select('b.*') ->from(['a' => $this->assignmentTable, 'b' => $this->itemTable]) ->where('{{a}}.[[item_name]]={{b}}.[[name]]') ->andWhere(['a.user_id' => (string) $userId]) @@ -562,7 +562,7 @@ class DbManager extends BaseManager */ protected function getInheritedPermissionsByUser($userId) { - $query = (new Query)->select('item_name') + $query = (new Query())->select('item_name') ->from($this->assignmentTable) ->where(['user_id' => (string) $userId]); @@ -576,7 +576,7 @@ class DbManager extends BaseManager return []; } - $query = (new Query)->from($this->itemTable)->where([ + $query = (new Query())->from($this->itemTable)->where([ 'type' => Item::TYPE_PERMISSION, 'name' => array_keys($result), ]); @@ -594,7 +594,7 @@ class DbManager extends BaseManager */ protected function getChildrenList() { - $query = (new Query)->from($this->itemChildTable); + $query = (new Query())->from($this->itemChildTable); $parents = []; foreach ($query->all($this->db) as $row) { $parents[$row['parent']][] = $row['child']; @@ -627,7 +627,7 @@ class DbManager extends BaseManager return isset($this->rules[$name]) ? $this->rules[$name] : null; } - $row = (new Query)->select(['data']) + $row = (new Query())->select(['data']) ->from($this->ruleTable) ->where(['name' => $name]) ->one($this->db); @@ -639,7 +639,6 @@ class DbManager extends BaseManager $data = stream_get_contents($data); } return unserialize($data); - } /** @@ -651,13 +650,13 @@ class DbManager extends BaseManager return $this->rules; } - $query = (new Query)->from($this->ruleTable); + $query = (new Query())->from($this->ruleTable); $rules = []; foreach ($query->all($this->db) as $row) { $data = $row['data']; if (is_resource($data)) { - $data = stream_get_contents($data); + $data = stream_get_contents($data); } $rules[$row['name']] = unserialize($data); } @@ -674,7 +673,7 @@ class DbManager extends BaseManager return null; } - $row = (new Query)->from($this->assignmentTable) + $row = (new Query())->from($this->assignmentTable) ->where(['user_id' => (string) $userId, 'item_name' => $roleName]) ->one($this->db); @@ -698,7 +697,7 @@ class DbManager extends BaseManager return []; } - $query = (new Query) + $query = (new Query()) ->from($this->assignmentTable) ->where(['user_id' => (string) $userId]); @@ -782,7 +781,7 @@ class DbManager extends BaseManager */ public function hasChild($parent, $child) { - return (new Query) + return (new Query()) ->from($this->itemChildTable) ->where(['parent' => $parent->name, 'child' => $child->name]) ->one($this->db) !== false; @@ -793,7 +792,7 @@ class DbManager extends BaseManager */ public function getChildren($name) { - $query = (new Query) + $query = (new Query()) ->select(['name', 'type', 'description', 'rule_name', 'data', 'created_at', 'updated_at']) ->from([$this->itemTable, $this->itemChildTable]) ->where(['parent' => $name, 'name' => new Expression('[[child]]')]); @@ -909,7 +908,7 @@ class DbManager extends BaseManager protected function removeAllItems($type) { if (!$this->supportsCascadeUpdate()) { - $names = (new Query) + $names = (new Query()) ->select(['name']) ->from($this->itemTable) ->where(['type' => $type]) @@ -974,17 +973,17 @@ class DbManager extends BaseManager $data = $this->cache->get($this->cacheKey); if (is_array($data) && isset($data[0], $data[1], $data[2])) { - list ($this->items, $this->rules, $this->parents) = $data; + list($this->items, $this->rules, $this->parents) = $data; return; } - $query = (new Query)->from($this->itemTable); + $query = (new Query())->from($this->itemTable); $this->items = []; foreach ($query->all($this->db) as $row) { $this->items[$row['name']] = $this->populateItem($row); } - $query = (new Query)->from($this->ruleTable); + $query = (new Query())->from($this->ruleTable); $this->rules = []; foreach ($query->all($this->db) as $row) { $data = $row['data']; @@ -994,7 +993,7 @@ class DbManager extends BaseManager $this->rules[$row['name']] = unserialize($data); } - $query = (new Query)->from($this->itemChildTable); + $query = (new Query())->from($this->itemChildTable); $this->parents = []; foreach ($query->all($this->db) as $row) { if (isset($this->items[$row['child']])) { @@ -1018,7 +1017,7 @@ class DbManager extends BaseManager return []; } - return (new Query)->select('[[user_id]]') + return (new Query())->select('[[user_id]]') ->from($this->assignmentTable) ->where(['item_name' => $roleName])->column($this->db); } diff --git a/framework/rbac/PhpManager.php b/framework/rbac/PhpManager.php index 6b6b5ae..06bf0ef 100644 --- a/framework/rbac/PhpManager.php +++ b/framework/rbac/PhpManager.php @@ -7,9 +7,9 @@ namespace yii\rbac; +use Yii; use yii\base\InvalidCallException; use yii\base\InvalidParamException; -use Yii; use yii\helpers\VarDumper; /** @@ -701,7 +701,6 @@ class PhpManager extends BaseManager $this->saveItems(); return true; - } /** @@ -875,7 +874,7 @@ class PhpManager extends BaseManager foreach ($this->assignments as $userID => $assignments) { foreach ($assignments as $userAssignment) { if ($userAssignment->roleName === $roleName && $userAssignment->userId == $userID) { - $result[] = (string)$userID; + $result[] = (string) $userID; } } } diff --git a/framework/rbac/Role.php b/framework/rbac/Role.php index 233d1d6..ed084e9 100644 --- a/framework/rbac/Role.php +++ b/framework/rbac/Role.php @@ -8,7 +8,6 @@ namespace yii\rbac; /** - * * For more details and usage information on Role, see the [guide article on security authorization](guide:security-authorization). * * @author Qiang Xue diff --git a/framework/rbac/migrations/m140506_102106_rbac_init.php b/framework/rbac/migrations/m140506_102106_rbac_init.php index 9f9dff6..9c6d604 100644 --- a/framework/rbac/migrations/m140506_102106_rbac_init.php +++ b/framework/rbac/migrations/m140506_102106_rbac_init.php @@ -73,8 +73,8 @@ class m140506_102106_rbac_init extends \yii\db\Migration 'created_at' => $this->integer(), 'updated_at' => $this->integer(), 'PRIMARY KEY ([[name]])', - 'FOREIGN KEY ([[rule_name]]) REFERENCES ' . $authManager->ruleTable . ' ([[name]])'. - $this->buildFkClause('ON DELETE SET NULL', 'ON UPDATE CASCADE') + 'FOREIGN KEY ([[rule_name]]) REFERENCES ' . $authManager->ruleTable . ' ([[name]])' . + $this->buildFkClause('ON DELETE SET NULL', 'ON UPDATE CASCADE'), ], $tableOptions); $this->createIndex('idx-auth_item-type', $authManager->itemTable, 'type'); @@ -82,9 +82,9 @@ class m140506_102106_rbac_init extends \yii\db\Migration 'parent' => $this->string(64)->notNull(), 'child' => $this->string(64)->notNull(), 'PRIMARY KEY ([[parent]], [[child]])', - 'FOREIGN KEY ([[parent]]) REFERENCES ' . $authManager->itemTable . ' ([[name]])'. + 'FOREIGN KEY ([[parent]]) REFERENCES ' . $authManager->itemTable . ' ([[name]])' . $this->buildFkClause('ON DELETE CASCADE', 'ON UPDATE CASCADE'), - 'FOREIGN KEY ([[child]]) REFERENCES ' . $authManager->itemTable . ' ([[name]])'. + 'FOREIGN KEY ([[child]]) REFERENCES ' . $authManager->itemTable . ' ([[name]])' . $this->buildFkClause('ON DELETE CASCADE', 'ON UPDATE CASCADE'), ], $tableOptions); diff --git a/framework/requirements/requirements.php b/framework/requirements/requirements.php index cb14ec3..d515af7 100644 --- a/framework/requirements/requirements.php +++ b/framework/requirements/requirements.php @@ -1,10 +1,16 @@ 'PHP version', diff --git a/framework/requirements/views/console/index.php b/framework/requirements/views/console/index.php index 4bb042e..d1559b6 100644 --- a/framework/requirements/views/console/index.php +++ b/framework/requirements/views/console/index.php @@ -1,4 +1,10 @@ $requirement) { if ($requirement['condition']) { - echo $requirement['name'].": OK\n"; + echo $requirement['name'] . ": OK\n"; echo "\n"; } else { - echo $requirement['name'].': '.($requirement['mandatory'] ? 'FAILED!!!' : 'WARNING!!!')."\n"; - echo 'Required by: '.strip_tags($requirement['by'])."\n"; + echo $requirement['name'] . ': ' . ($requirement['mandatory'] ? 'FAILED!!!' : 'WARNING!!!') . "\n"; + echo 'Required by: ' . strip_tags($requirement['by']) . "\n"; $memo = strip_tags($requirement['memo']); if (!empty($memo)) { - echo 'Memo: '.strip_tags($requirement['memo'])."\n"; + echo 'Memo: ' . strip_tags($requirement['memo']) . "\n"; } echo "\n"; } } -$summaryString = 'Errors: '.$summary['errors'].' Warnings: '.$summary['warnings'].' Total checks: '.$summary['total']; -echo str_pad('', strlen($summaryString), '-')."\n"; +$summaryString = 'Errors: ' . $summary['errors'] . ' Warnings: ' . $summary['warnings'] . ' Total checks: ' . $summary['total']; +echo str_pad('', strlen($summaryString), '-') . "\n"; echo $summaryString; echo "\n\n"; diff --git a/framework/rest/Controller.php b/framework/rest/Controller.php index 92a0514..734b344 100644 --- a/framework/rest/Controller.php +++ b/framework/rest/Controller.php @@ -11,8 +11,8 @@ use Yii; use yii\filters\auth\CompositeAuth; use yii\filters\ContentNegotiator; use yii\filters\RateLimiter; -use yii\web\Response; use yii\filters\VerbFilter; +use yii\web\Response; /** * Controller is the base class for RESTful API controller classes. diff --git a/framework/rest/Serializer.php b/framework/rest/Serializer.php index 1602156..33e5637 100644 --- a/framework/rest/Serializer.php +++ b/framework/rest/Serializer.php @@ -255,7 +255,7 @@ class Serializer extends Component if ($this->request->getIsHead()) { return null; } else { - list ($fields, $expand) = $this->getRequestedFields(); + list($fields, $expand) = $this->getRequestedFields(); return $model->toArray($fields, $expand); } } @@ -286,7 +286,7 @@ class Serializer extends Component */ protected function serializeModels(array $models) { - list ($fields, $expand) = $this->getRequestedFields(); + list($fields, $expand) = $this->getRequestedFields(); foreach ($models as $i => $model) { if ($model instanceof Arrayable) { $models[$i] = $model->toArray($fields, $expand); diff --git a/framework/test/DbFixture.php b/framework/test/DbFixture.php index 7648acd..9de4d71 100644 --- a/framework/test/DbFixture.php +++ b/framework/test/DbFixture.php @@ -8,9 +8,9 @@ namespace yii\test; use Yii; +use yii\base\Object; use yii\db\Connection; use yii\di\Instance; -use yii\base\Object; /** * DbFixture is the base class for DB-related fixtures. diff --git a/framework/validators/DateValidator.php b/framework/validators/DateValidator.php index 871f522..04c1ac7 100644 --- a/framework/validators/DateValidator.php +++ b/framework/validators/DateValidator.php @@ -199,10 +199,10 @@ class DateValidator extends Validator * @var array map of short format names to IntlDateFormatter constant values. */ private $_dateFormats = [ - 'short' => 3, // IntlDateFormatter::SHORT, + 'short' => 3, // IntlDateFormatter::SHORT, 'medium' => 2, // IntlDateFormatter::MEDIUM, - 'long' => 1, // IntlDateFormatter::LONG, - 'full' => 0, // IntlDateFormatter::FULL, + 'long' => 1, // IntlDateFormatter::LONG, + 'full' => 0, // IntlDateFormatter::FULL, ]; diff --git a/framework/validators/EachValidator.php b/framework/validators/EachValidator.php index 15dd9f7..385e4f2 100644 --- a/framework/validators/EachValidator.php +++ b/framework/validators/EachValidator.php @@ -7,8 +7,8 @@ namespace yii\validators; -use yii\base\InvalidConfigException; use Yii; +use yii\base\InvalidConfigException; use yii\base\Model; /** diff --git a/framework/validators/EmailValidator.php b/framework/validators/EmailValidator.php index bf72754..bd613f6 100644 --- a/framework/validators/EmailValidator.php +++ b/framework/validators/EmailValidator.php @@ -9,8 +9,8 @@ namespace yii\validators; use Yii; use yii\base\InvalidConfigException; -use yii\web\JsExpression; use yii\helpers\Json; +use yii\web\JsExpression; /** * EmailValidator validates that the attribute value is a valid email address. @@ -130,7 +130,7 @@ class EmailValidator extends Validator 'message' => $this->formatMessage($this->message, [ 'attribute' => $model->getAttributeLabel($attribute), ]), - 'enableIDN' => (bool)$this->enableIDN, + 'enableIDN' => (bool) $this->enableIDN, ]; if ($this->skipOnEmpty) { $options['skipOnEmpty'] = 1; diff --git a/framework/validators/ExistValidator.php b/framework/validators/ExistValidator.php index 6e561fd..91b78b3 100644 --- a/framework/validators/ExistValidator.php +++ b/framework/validators/ExistValidator.php @@ -223,8 +223,8 @@ class ExistValidator extends Validator foreach ($conditions as $columnName => $columnValue) { $prefixedColumn = "{$alias}.[[" . preg_replace( '/^' . preg_quote($alias) . '\.(.*)$/', - "$1", - $columnName) . "]]"; + '$1', + $columnName) . ']]'; $prefixedConditions[$prefixedColumn] = $columnValue; } return $prefixedConditions; diff --git a/framework/validators/FileValidator.php b/framework/validators/FileValidator.php index 8018360..b679bdf 100644 --- a/framework/validators/FileValidator.php +++ b/framework/validators/FileValidator.php @@ -8,11 +8,11 @@ namespace yii\validators; use Yii; +use yii\helpers\FileHelper; use yii\helpers\Html; use yii\helpers\Json; use yii\web\JsExpression; use yii\web\UploadedFile; -use yii\helpers\FileHelper; /** * FileValidator verifies if an attribute is receiving a valid uploaded file. @@ -250,7 +250,7 @@ class FileValidator extends Validator ]; } elseif (!empty($this->extensions) && !$this->validateExtension($value)) { return [$this->wrongExtension, ['file' => $value->name, 'extensions' => implode(', ', $this->extensions)]]; - } elseif (!empty($this->mimeTypes) && !$this->validateMimeType($value)) { + } elseif (!empty($this->mimeTypes) && !$this->validateMimeType($value)) { return [$this->wrongMimeType, ['file' => $value->name, 'mimeTypes' => implode(', ', $this->mimeTypes)]]; } return null; @@ -353,7 +353,6 @@ class FileValidator extends Validator $extension = mb_strtolower($file->extension, 'UTF-8'); if ($this->checkExtensionByMimeType) { - $mimeType = FileHelper::getMimeType($file->tempName, null, false); if ($mimeType === null) { return false; diff --git a/framework/validators/IpValidator.php b/framework/validators/IpValidator.php index bfe84f7..89800b2 100644 --- a/framework/validators/IpValidator.php +++ b/framework/validators/IpValidator.php @@ -71,7 +71,6 @@ class IpValidator extends Validator * - `localhost`: `127.0.0.0/8', ::1` * - `documentation`: `192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24, 2001:db8::/32` * - `system`: `multicast, linklocal, localhost, documentation` - * */ public $networks = [ '*' => ['any'], diff --git a/framework/validators/NumberValidator.php b/framework/validators/NumberValidator.php index d5b4fb9..ca18d59 100644 --- a/framework/validators/NumberValidator.php +++ b/framework/validators/NumberValidator.php @@ -8,9 +8,9 @@ namespace yii\validators; use Yii; +use yii\helpers\Json; use yii\helpers\StringHelper; use yii\web\JsExpression; -use yii\helpers\Json; /** * NumberValidator validates that the attribute value is a number. diff --git a/framework/validators/RegularExpressionValidator.php b/framework/validators/RegularExpressionValidator.php index 7f17432..fab5c51 100644 --- a/framework/validators/RegularExpressionValidator.php +++ b/framework/validators/RegularExpressionValidator.php @@ -10,8 +10,8 @@ namespace yii\validators; use Yii; use yii\base\InvalidConfigException; use yii\helpers\Html; -use yii\web\JsExpression; use yii\helpers\Json; +use yii\web\JsExpression; /** * RegularExpressionValidator validates that the attribute value matches the specified [[pattern]]. diff --git a/framework/validators/UniqueValidator.php b/framework/validators/UniqueValidator.php index b834d6d..d4d1b61 100644 --- a/framework/validators/UniqueValidator.php +++ b/framework/validators/UniqueValidator.php @@ -10,8 +10,8 @@ namespace yii\validators; use Yii; use yii\base\Model; use yii\db\ActiveQuery; -use yii\db\ActiveRecord; use yii\db\ActiveQueryInterface; +use yii\db\ActiveRecord; use yii\db\ActiveRecordInterface; use yii\helpers\Inflector; @@ -75,7 +75,6 @@ class UniqueValidator extends Validator * * - `{attributes}`: the labels of the attributes being validated. * - `{values}`: the values of the attributes being validated. - * */ public $message; /** @@ -271,7 +270,7 @@ class UniqueValidator extends Validator } $this->addError($model, $attribute, $this->message, [ 'attributes' => Inflector::sentence($attributeCombo), - 'values' => implode('-', $valueCombo) + 'values' => implode('-', $valueCombo), ]); } @@ -291,8 +290,8 @@ class UniqueValidator extends Validator foreach ($conditions as $columnName => $columnValue) { $prefixedColumn = "{$alias}.[[" . preg_replace( '/^' . preg_quote($alias) . '\.(.*)$/', - "$1", - $columnName) . "]]"; + '$1', + $columnName) . ']]'; $prefixedConditions[$prefixedColumn] = $columnValue; } return $prefixedConditions; diff --git a/framework/validators/UrlValidator.php b/framework/validators/UrlValidator.php index 0c2151e..6f237a2 100644 --- a/framework/validators/UrlValidator.php +++ b/framework/validators/UrlValidator.php @@ -9,8 +9,8 @@ namespace yii\validators; use Yii; use yii\base\InvalidConfigException; -use yii\web\JsExpression; use yii\helpers\Json; +use yii\web\JsExpression; /** * UrlValidator validates that the attribute value is a valid http or https URL. diff --git a/framework/validators/Validator.php b/framework/validators/Validator.php index 0271687..b7f4458 100644 --- a/framework/validators/Validator.php +++ b/framework/validators/Validator.php @@ -460,7 +460,7 @@ class Validator extends Component */ public function getAttributeNames() { - return array_map(function($attribute) { + return array_map(function ($attribute) { return ltrim($attribute, '!'); }, $this->attributes); } diff --git a/framework/views/errorHandler/callStackItem.php b/framework/views/errorHandler/callStackItem.php index 6701ee4..04f8c88 100644 --- a/framework/views/errorHandler/callStackItem.php +++ b/framework/views/errorHandler/callStackItem.php @@ -10,19 +10,19 @@ /* @var $args array */ /* @var $handler \yii\web\ErrorHandler */ ?> -
  • . - htmlEncode($file); ?> + htmlEncode($file) : '' ?> - - + + - + addTypeLinks("$class::$method") : $handler->htmlEncode($method)) . '(' . $handler->argumentsToString($args) . ')' ?> diff --git a/framework/views/errorHandler/error.php b/framework/views/errorHandler/error.php index e85f09c..dc88e6b 100644 --- a/framework/views/errorHandler/error.php +++ b/framework/views/errorHandler/error.php @@ -80,14 +80,11 @@ if (method_exists($this, 'beginPage')) {
    - endBody(); // to allow injecting code into body (mostly by Yii Debug Toolbar) - } - ?> + + endBody() // to allow injecting code into body (mostly by Yii Debug Toolbar)?> + -endPage(); -} + + endPage() ?> + diff --git a/framework/views/errorHandler/exception.php b/framework/views/errorHandler/exception.php index 3eae788..6de9904 100644 --- a/framework/views/errorHandler/exception.php +++ b/framework/views/errorHandler/exception.php @@ -3,7 +3,9 @@ /* @var $exception \Exception */ /* @var $handler \yii\web\ErrorHandler */ ?> -beginPage(); ?> + + beginPage() ?> + @@ -370,9 +372,9 @@ body.mousedown pre {

    htmlEncode($exception->getMessage())) ?>

    - errorInfo)) { - echo '
    Error Info: ' . print_r($exception->errorInfo, true) . '
    '; - } ?> + errorInfo)): ?> +
    Error Info: errorInfo, true) ?>
    + renderPreviousExceptions($exception) ?>
    @@ -448,8 +450,12 @@ window.onload = function() { document.onmousedown = function() { document.getElementsByTagName('body')[0].classList.add('mousedown'); } document.onmouseup = function() { document.getElementsByTagName('body')[0].classList.remove('mousedown'); } - endBody(); // to allow injecting code into body (mostly by Yii Debug Toolbar) ?> + + endBody() // to allow injecting code into body (mostly by Yii Debug Toolbar)?> + -endPage(); ?> + + endPage() ?> + diff --git a/framework/views/errorHandler/previousException.php b/framework/views/errorHandler/previousException.php index 882246d..59e1451 100644 --- a/framework/views/errorHandler/previousException.php +++ b/framework/views/errorHandler/previousException.php @@ -6,8 +6,8 @@

    Caused by: - getExceptionName($exception); - if ($name !== null): ?> + getExceptionName($exception) ?> + htmlEncode($name) ?>addTypeLinks(get_class($exception)) ?> @@ -16,8 +16,8 @@

    htmlEncode($exception->getMessage())) ?>

    in getFile() ?> at line getLine() ?>

    - errorInfo)) { - echo '
    Error Info: ' . print_r($exception->errorInfo, true) . '
    '; - } ?> + errorInfo)): ?> +
    Error Info: errorInfo, true) ?>
    + renderPreviousExceptions($exception) ?>
    diff --git a/framework/web/Application.php b/framework/web/Application.php index 89728f1..a43090b 100644 --- a/framework/web/Application.php +++ b/framework/web/Application.php @@ -8,8 +8,8 @@ namespace yii\web; use Yii; -use yii\helpers\Url; use yii\base\InvalidRouteException; +use yii\helpers\Url; /** * Application is the base class for all web application classes. @@ -79,7 +79,7 @@ class Application extends \yii\base\Application { if (empty($this->catchAll)) { try { - list ($route, $params) = $request->resolve(); + list($route, $params) = $request->resolve(); } catch (UrlNormalizerRedirectException $e) { $url = $e->url; if (is_array($url)) { diff --git a/framework/web/AssetBundle.php b/framework/web/AssetBundle.php index 7d391e1..ce395bf 100644 --- a/framework/web/AssetBundle.php +++ b/framework/web/AssetBundle.php @@ -7,10 +7,10 @@ namespace yii\web; +use Yii; use yii\base\Object; use yii\helpers\ArrayHelper; use yii\helpers\Url; -use Yii; /** * AssetBundle represents a collection of asset files, such as CSS, JS, images. @@ -182,7 +182,7 @@ class AssetBundle extends Object public function publish($am) { if ($this->sourcePath !== null && !isset($this->basePath, $this->baseUrl)) { - list ($this->basePath, $this->baseUrl) = $am->publish($this->sourcePath, $this->publishOptions); + list($this->basePath, $this->baseUrl) = $am->publish($this->sourcePath, $this->publishOptions); } if (isset($this->basePath, $this->baseUrl) && ($converter = $am->getConverter()) !== null) { diff --git a/framework/web/AssetConverter.php b/framework/web/AssetConverter.php index 55e67d1..ad1e949 100644 --- a/framework/web/AssetConverter.php +++ b/framework/web/AssetConverter.php @@ -63,7 +63,7 @@ class AssetConverter extends Component implements AssetConverterInterface if ($pos !== false) { $ext = substr($asset, $pos + 1); if (isset($this->commands[$ext])) { - list ($ext, $command) = $this->commands[$ext]; + list($ext, $command) = $this->commands[$ext]; $result = substr($asset, 0, $pos + 1) . $ext; if ($this->forceConvert || @filemtime("$basePath/$result") < @filemtime("$basePath/$asset")) { $this->runCommand($command, $basePath, $asset, $result); diff --git a/framework/web/CompositeUrlRule.php b/framework/web/CompositeUrlRule.php index 97d0bdc..080e1a5 100644 --- a/framework/web/CompositeUrlRule.php +++ b/framework/web/CompositeUrlRule.php @@ -60,7 +60,7 @@ abstract class CompositeUrlRule extends Object implements UrlRuleInterface Yii::trace([ 'rule' => method_exists($rule, '__toString') ? $rule->__toString() : get_class($rule), 'match' => $result !== false, - 'parent' => self::className() + 'parent' => self::className(), ], __METHOD__); } if ($result !== false) { diff --git a/framework/web/CookieCollection.php b/framework/web/CookieCollection.php index 6a3dea3..bb2b739 100644 --- a/framework/web/CookieCollection.php +++ b/framework/web/CookieCollection.php @@ -7,8 +7,8 @@ namespace yii\web; -use Yii; use ArrayIterator; +use Yii; use yii\base\InvalidCallException; use yii\base\Object; diff --git a/framework/web/DbSession.php b/framework/web/DbSession.php index 072aca3..28cf074 100644 --- a/framework/web/DbSession.php +++ b/framework/web/DbSession.php @@ -8,9 +8,9 @@ namespace yii\web; use Yii; +use yii\base\InvalidConfigException; use yii\db\Connection; use yii\db\Query; -use yii\base\InvalidConfigException; use yii\di\Instance; /** @@ -165,7 +165,7 @@ class DbSession extends MultiFieldSession // exception must be caught in session write handler // http://us.php.net/manual/en/function.session-set-save-handler.php#refsect1-function.session-set-save-handler-notes try { - $query = new Query; + $query = new Query(); $exists = $query->select(['id']) ->from($this->sessionTable) ->where(['id' => $id]) diff --git a/framework/web/ErrorHandler.php b/framework/web/ErrorHandler.php index f01d6d0..c3dea6a 100644 --- a/framework/web/ErrorHandler.php +++ b/framework/web/ErrorHandler.php @@ -8,8 +8,8 @@ namespace yii\web; use Yii; -use yii\base\Exception; use yii\base\ErrorException; +use yii\base\Exception; use yii\base\UserException; use yii\helpers\VarDumper; @@ -191,7 +191,7 @@ class ErrorHandler extends \yii\base\ErrorHandler $url = null; $shouldGenerateLink = true; - if ($method !== null && substr_compare($method, '{closure}', -9) !== 0) { + if ($method !== null && substr_compare($method, '{closure}', -9) !== 0) { $reflection = new \ReflectionMethod($class, $method); $shouldGenerateLink = $reflection->isPublic() || $reflection->isProtected(); } @@ -419,8 +419,8 @@ class ErrorHandler extends \yii\base\ErrorHandler foreach ($args as $key => $value) { $count++; - if ($count>=5) { - if ($count>5) { + if ($count >= 5) { + if ($count > 5) { unset($args[$key]); } else { $args[$key] = '...'; diff --git a/framework/web/HeaderCollection.php b/framework/web/HeaderCollection.php index 163c408..2a616ef 100644 --- a/framework/web/HeaderCollection.php +++ b/framework/web/HeaderCollection.php @@ -7,9 +7,9 @@ namespace yii\web; +use ArrayIterator; use Yii; use yii\base\Object; -use ArrayIterator; /** * HeaderCollection is used by [[Response]] to maintain the currently registered HTTP headers. diff --git a/framework/web/MultiFieldSession.php b/framework/web/MultiFieldSession.php index c4083e4..dcb0d6d 100644 --- a/framework/web/MultiFieldSession.php +++ b/framework/web/MultiFieldSession.php @@ -130,7 +130,7 @@ abstract class MultiFieldSession extends Session $extraData = call_user_func($this->readCallback, $fields); if (!empty($extraData)) { session_decode($fields['data']); - $_SESSION = array_merge((array)$_SESSION, (array)$extraData); + $_SESSION = array_merge((array) $_SESSION, (array) $extraData); return session_encode(); } return $fields['data']; diff --git a/framework/web/MultipartFormDataParser.php b/framework/web/MultipartFormDataParser.php index 6fae328..ac1ffd8 100644 --- a/framework/web/MultipartFormDataParser.php +++ b/framework/web/MultipartFormDataParser.php @@ -141,7 +141,7 @@ class MultipartFormDataParser extends Object implements RequestParserInterface if (empty($bodyPart)) { continue; } - list($headers, $value) = preg_split("/\\R\\R/", $bodyPart, 2); + list($headers, $value) = preg_split('/\\R\\R/', $bodyPart, 2); $headers = $this->parseHeaders($headers); if (!isset($headers['content-disposition']['name'])) { @@ -202,7 +202,7 @@ class MultipartFormDataParser extends Object implements RequestParserInterface private function parseHeaders($headerContent) { $headers = []; - $headerParts = preg_split("/\\R/s", $headerContent, -1, PREG_SPLIT_NO_EMPTY); + $headerParts = preg_split('/\\R/s', $headerContent, -1, PREG_SPLIT_NO_EMPTY); foreach ($headerParts as $headerPart) { if (($separatorPos = strpos($headerPart, ':')) === false) { continue; @@ -278,7 +278,7 @@ class MultipartFormDataParser extends Object implements RequestParserInterface 'size', 'error', 'tmp_name', - 'tmp_resource' + 'tmp_resource', ]; $nameParts = preg_split('/\\]\\[|\\[/s', $name); @@ -290,7 +290,7 @@ class MultipartFormDataParser extends Object implements RequestParserInterface } } else { foreach ($fileInfoAttributes as $attribute) { - $files[$baseName][$attribute] = (array)$files[$baseName][$attribute]; + $files[$baseName][$attribute] = (array) $files[$baseName][$attribute]; } } diff --git a/framework/web/Request.php b/framework/web/Request.php index e374f6b..c6ce457 100644 --- a/framework/web/Request.php +++ b/framework/web/Request.php @@ -183,7 +183,7 @@ class Request extends \yii\base\Request { $result = Yii::$app->getUrlManager()->parseRequest($this); if ($result !== false) { - list ($route, $params) = $result; + list($route, $params) = $result; if ($this->_queryParams === null) { $_GET = $params + $_GET; // preserve numeric keys } else { @@ -203,7 +203,7 @@ class Request extends \yii\base\Request public function getHeaders() { if ($this->_headers === null) { - $this->_headers = new HeaderCollection; + $this->_headers = new HeaderCollection(); if (function_exists('getallheaders')) { $headers = getallheaders(); } elseif (function_exists('http_get_request_headers')) { @@ -407,7 +407,7 @@ class Request extends \yii\base\Request } elseif (isset($this->parsers['*'])) { $parser = Yii::createObject($this->parsers['*']); if (!($parser instanceof RequestParserInterface)) { - throw new InvalidConfigException("The fallback request parser is invalid. It must implement the yii\\web\\RequestParserInterface."); + throw new InvalidConfigException('The fallback request parser is invalid. It must implement the yii\\web\\RequestParserInterface.'); } $this->_bodyParams = $parser->parse($this->getRawBody(), $rawContentType); } elseif ($this->getMethod() === 'POST') { @@ -1153,9 +1153,9 @@ class Request extends \yii\base\Request ]; foreach ($params as $param) { if (strpos($param, '=') !== false) { - list ($key, $value) = explode('=', $param, 2); + list($key, $value) = explode('=', $param, 2); if ($key === 'q') { - $values['q'][2] = (double) $value; + $values['q'][2] = (float) $value; } else { $values[$key] = $value; } @@ -1226,10 +1226,11 @@ class Request extends \yii\base\Request foreach ($languages as $language) { $normalizedLanguage = str_replace('_', '-', strtolower($language)); - if ($normalizedLanguage === $acceptableLanguage || // en-us==en-us - strpos($acceptableLanguage, $normalizedLanguage . '-') === 0 || // en==en-us - strpos($normalizedLanguage, $acceptableLanguage . '-') === 0) { // en-us==en - + if ( + $normalizedLanguage === $acceptableLanguage // en-us==en-us + || strpos($acceptableLanguage, $normalizedLanguage . '-') === 0 // en==en-us + || strpos($normalizedLanguage, $acceptableLanguage . '-') === 0 // en-us==en + ) { return $language; } } diff --git a/framework/web/Response.php b/framework/web/Response.php index f643b7c..40deead 100644 --- a/framework/web/Response.php +++ b/framework/web/Response.php @@ -10,10 +10,10 @@ namespace yii\web; use Yii; use yii\base\InvalidConfigException; use yii\base\InvalidParamException; -use yii\helpers\Inflector; -use yii\helpers\Url; use yii\helpers\FileHelper; +use yii\helpers\Inflector; use yii\helpers\StringHelper; +use yii\helpers\Url; /** * The web Response class represents an HTTP response @@ -317,7 +317,7 @@ class Response extends \yii\base\Response public function getHeaders() { if ($this->_headers === null) { - $this->_headers = new HeaderCollection; + $this->_headers = new HeaderCollection(); } return $this->_headers; } @@ -396,7 +396,7 @@ class Response extends \yii\base\Response } foreach ($this->getCookies() as $cookie) { $value = $cookie->value; - if ($cookie->expire != 1 && isset($validationKey)) { + if ($cookie->expire != 1 && isset($validationKey)) { $value = Yii::$app->getSecurity()->hashData(serialize([$cookie->name, $value]), $validationKey); } setcookie($cookie->name, $value, $cookie->expire, $cookie->path, $cookie->domain, $cookie->secure, $cookie->httpOnly); @@ -418,7 +418,7 @@ class Response extends \yii\base\Response $chunkSize = 8 * 1024 * 1024; // 8MB per chunk if (is_array($this->stream)) { - list ($handle, $begin, $end) = $this->stream; + list($handle, $begin, $end) = $this->stream; fseek($handle, $begin); while (!feof($handle) && ($pos = ftell($handle)) <= $end) { if ($pos + $chunkSize > $end) { @@ -907,7 +907,7 @@ class Response extends \yii\base\Response public function getCookies() { if ($this->_cookies === null) { - $this->_cookies = new CookieCollection; + $this->_cookies = new CookieCollection(); } return $this->_cookies; } diff --git a/framework/web/Session.php b/framework/web/Session.php index 99c7fb3..2455888 100644 --- a/framework/web/Session.php +++ b/framework/web/Session.php @@ -561,7 +561,7 @@ class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Co public function getIterator() { $this->open(); - return new SessionIterator; + return new SessionIterator(); } /** diff --git a/framework/web/UploadedFile.php b/framework/web/UploadedFile.php index b3613e2..9ad1982 100644 --- a/framework/web/UploadedFile.php +++ b/framework/web/UploadedFile.php @@ -227,7 +227,7 @@ class UploadedFile extends Object foreach ($names as $i => $name) { self::loadFilesRecursive($key . '[' . $i . ']', $name, $tempNames[$i], $types[$i], $sizes[$i], $errors[$i]); } - } elseif ((int)$errors !== UPLOAD_ERR_NO_FILE) { + } elseif ((int) $errors !== UPLOAD_ERR_NO_FILE) { self::$_files[$key] = [ 'name' => $names, 'tempName' => $tempNames, diff --git a/framework/web/UrlNormalizer.php b/framework/web/UrlNormalizer.php index 712d356..739c0d6 100644 --- a/framework/web/UrlNormalizer.php +++ b/framework/web/UrlNormalizer.php @@ -8,8 +8,8 @@ namespace yii\web; use Yii; -use yii\base\Object; use yii\base\InvalidConfigException; +use yii\base\Object; /** * UrlNormalizer normalizes URLs for [[UrlManager]] and [[UrlRule]]. diff --git a/framework/web/UrlRule.php b/framework/web/UrlRule.php index 4c3c510..d66595b 100644 --- a/framework/web/UrlRule.php +++ b/framework/web/UrlRule.php @@ -385,7 +385,7 @@ class UrlRule extends Object implements UrlRuleInterface return false; } - $suffix = (string)($this->suffix === null ? $manager->suffix : $this->suffix); + $suffix = (string) ($this->suffix === null ? $manager->suffix : $this->suffix); $pathInfo = $request->getPathInfo(); $normalized = false; if ($this->hasNormalizer($manager)) { @@ -545,7 +545,8 @@ class UrlRule extends Object implements UrlRuleInterface * @see $createStatus * @since 2.0.12 */ - public function getCreateUrlStatus() { + public function getCreateUrlStatus() + { return $this->createStatus; } diff --git a/framework/web/User.php b/framework/web/User.php index d671d38..c483e81 100644 --- a/framework/web/User.php +++ b/framework/web/User.php @@ -558,7 +558,7 @@ class User extends Component } $data = json_decode($value, true); if (count($data) == 3) { - list ($id, $authKey, $duration) = $data; + list($id, $authKey, $duration) = $data; /* @var $class IdentityInterface */ $class = $this->identityClass; $identity = $class::findIdentity($id); diff --git a/framework/web/View.php b/framework/web/View.php index 3f09d09..ed8a9a1 100644 --- a/framework/web/View.php +++ b/framework/web/View.php @@ -8,9 +8,9 @@ namespace yii\web; use Yii; +use yii\base\InvalidConfigException; use yii\helpers\ArrayHelper; use yii\helpers\Html; -use yii\base\InvalidConfigException; /** * View represents a view object in the MVC pattern. @@ -411,7 +411,7 @@ class View extends \yii\base\View 'baseUrl' => '', 'css' => [strncmp($url, '//', 2) === 0 ? $url : ltrim($url, '/')], 'cssOptions' => $options, - 'depends' => (array)$depends, + 'depends' => (array) $depends, ]); $this->registerAssetBundle($key); } @@ -479,7 +479,7 @@ class View extends \yii\base\View 'baseUrl' => '', 'js' => [strncmp($url, '//', 2) === 0 ? $url : ltrim($url, '/')], 'jsOptions' => $options, - 'depends' => (array)$depends, + 'depends' => (array) $depends, ]); $this->registerAssetBundle($key); } diff --git a/framework/web/ViewAction.php b/framework/web/ViewAction.php index d4d2898..9a45954 100644 --- a/framework/web/ViewAction.php +++ b/framework/web/ViewAction.php @@ -80,9 +80,7 @@ class ViewAction extends Action if ($controllerLayout) { $this->controller->layout = $controllerLayout; } - } catch (ViewNotFoundException $e) { - if ($controllerLayout) { $this->controller->layout = $controllerLayout; } diff --git a/framework/web/XmlResponseFormatter.php b/framework/web/XmlResponseFormatter.php index c76b27d..326e649 100644 --- a/framework/web/XmlResponseFormatter.php +++ b/framework/web/XmlResponseFormatter.php @@ -9,8 +9,8 @@ namespace yii\web; use DOMDocument; use DOMElement; -use DOMText; use DOMException; +use DOMText; use yii\base\Arrayable; use yii\base\Component; use yii\helpers\StringHelper; diff --git a/framework/web/migrations/m160313_153426_session_init.php b/framework/web/migrations/m160313_153426_session_init.php index accbbf3..279ebf9 100644 --- a/framework/web/migrations/m160313_153426_session_init.php +++ b/framework/web/migrations/m160313_153426_session_init.php @@ -15,7 +15,6 @@ use yii\db\Migration; */ class m160313_153426_session_init extends Migration { - /** * @inheritdoc */ diff --git a/framework/widgets/ActiveField.php b/framework/widgets/ActiveField.php index 3030a2d..68d634c 100644 --- a/framework/widgets/ActiveField.php +++ b/framework/widgets/ActiveField.php @@ -10,9 +10,9 @@ namespace yii\widgets; use Yii; use yii\base\Component; use yii\base\ErrorHandler; +use yii\base\Model; use yii\helpers\ArrayHelper; use yii\helpers\Html; -use yii\base\Model; use yii\web\JsExpression; /** @@ -799,7 +799,7 @@ class ActiveField extends Component } if (!empty($validators)) { - $options['validate'] = new JsExpression("function (attribute, value, messages, deferred, \$form) {" . implode('', $validators) . '}'); + $options['validate'] = new JsExpression('function (attribute, value, messages, deferred, $form) {' . implode('', $validators) . '}'); } if ($this->addAriaAttributes === false) { @@ -857,7 +857,7 @@ class ActiveField extends Component { if ($this->addAriaAttributes) { if (!isset($options['aria-required']) && $this->model->isAttributeRequired($this->attribute)) { - $options['aria-required'] = 'true'; + $options['aria-required'] = 'true'; } if (!isset($options['aria-invalid'])) { if ($this->model->hasErrors($this->attribute)) { diff --git a/framework/widgets/ActiveForm.php b/framework/widgets/ActiveForm.php index a03e487..a65f04f 100644 --- a/framework/widgets/ActiveForm.php +++ b/framework/widgets/ActiveForm.php @@ -9,12 +9,12 @@ namespace yii\widgets; use Yii; use yii\base\InvalidCallException; -use yii\base\Widget; use yii\base\Model; +use yii\base\Widget; use yii\helpers\ArrayHelper; -use yii\helpers\Url; use yii\helpers\Html; use yii\helpers\Json; +use yii\helpers\Url; /** * ActiveForm is a widget that builds an interactive HTML form for one or multiple data models. diff --git a/framework/widgets/BaseListView.php b/framework/widgets/BaseListView.php index 4abff64..f300220 100644 --- a/framework/widgets/BaseListView.php +++ b/framework/widgets/BaseListView.php @@ -130,7 +130,7 @@ abstract class BaseListView extends Widget public function run() { if ($this->showOnEmpty || $this->dataProvider->getCount() > 0) { - $content = preg_replace_callback("/{\\w+}/", function ($matches) { + $content = preg_replace_callback('/{\\w+}/', function ($matches) { $content = $this->renderSection($matches[0]); return $content === false ? $matches[0] : $content; diff --git a/framework/widgets/Breadcrumbs.php b/framework/widgets/Breadcrumbs.php index 2dfe1d4..c26f6c6 100644 --- a/framework/widgets/Breadcrumbs.php +++ b/framework/widgets/Breadcrumbs.php @@ -8,8 +8,8 @@ namespace yii\widgets; use Yii; -use yii\base\Widget; use yii\base\InvalidConfigException; +use yii\base\Widget; use yii\helpers\ArrayHelper; use yii\helpers\Html; @@ -110,7 +110,6 @@ class Breadcrumbs extends Widget * 'encode' => false, * ] * ``` - * */ public $links = []; /** diff --git a/framework/widgets/DetailView.php b/framework/widgets/DetailView.php index 4cf8ad1..30dfa9e 100644 --- a/framework/widgets/DetailView.php +++ b/framework/widgets/DetailView.php @@ -9,13 +9,13 @@ namespace yii\widgets; use Yii; use yii\base\Arrayable; -use yii\i18n\Formatter; use yii\base\InvalidConfigException; use yii\base\Model; use yii\base\Widget; use yii\helpers\ArrayHelper; use yii\helpers\Html; use yii\helpers\Inflector; +use yii\i18n\Formatter; /** * DetailView displays the detail of a single data [[model]]. @@ -177,7 +177,7 @@ class DetailView extends Widget '{label}' => $attribute['label'], '{value}' => $this->formatter->format($attribute['value'], $attribute['format']), '{captionOptions}' => $captionOptions, - '{contentOptions}' => $contentOptions, + '{contentOptions}' => $contentOptions, ]); } else { return call_user_func($this->template, $attribute, $index, $this); diff --git a/framework/widgets/FragmentCache.php b/framework/widgets/FragmentCache.php index 875ac43..e7cd5d5 100644 --- a/framework/widgets/FragmentCache.php +++ b/framework/widgets/FragmentCache.php @@ -150,7 +150,7 @@ class FragmentCache extends Widget return $this->_content; } - list ($this->_content, $placeholders) = $data; + list($this->_content, $placeholders) = $data; if (!is_array($placeholders) || count($placeholders) === 0) { return $this->_content; } diff --git a/framework/widgets/InputWidget.php b/framework/widgets/InputWidget.php index f067502..f59b4ec 100644 --- a/framework/widgets/InputWidget.php +++ b/framework/widgets/InputWidget.php @@ -8,9 +8,9 @@ namespace yii\widgets; use Yii; -use yii\base\Widget; -use yii\base\Model; use yii\base\InvalidConfigException; +use yii\base\Model; +use yii\base\Widget; use yii\helpers\Html; /** diff --git a/framework/widgets/LinkPager.php b/framework/widgets/LinkPager.php index 52270d1..a7e5a2c 100644 --- a/framework/widgets/LinkPager.php +++ b/framework/widgets/LinkPager.php @@ -9,10 +9,10 @@ namespace yii\widgets; use Yii; use yii\base\InvalidConfigException; -use yii\helpers\Html; use yii\base\Widget; use yii\data\Pagination; use yii\helpers\ArrayHelper; +use yii\helpers\Html; /** * LinkPager displays a list of hyperlinks that lead to different pages of target. diff --git a/framework/widgets/MaskedInput.php b/framework/widgets/MaskedInput.php index 7fa7a2f..9c4bd40 100644 --- a/framework/widgets/MaskedInput.php +++ b/framework/widgets/MaskedInput.php @@ -156,8 +156,12 @@ class MaskedInput extends InputWidget { $options = $this->clientOptions; foreach ($options as $key => $value) { - if (!$value instanceof JsExpression && in_array($key, ['oncomplete', 'onincomplete', 'oncleared', 'onKeyUp', - 'onKeyDown', 'onBeforeMask', 'onBeforePaste', 'onUnMask', 'isComplete', 'determineActiveMasksetIndex'], true) + if ( + !$value instanceof JsExpression + && in_array($key, [ + 'oncomplete', 'onincomplete', 'oncleared', 'onKeyUp', 'onKeyDown', 'onBeforeMask', + 'onBeforePaste', 'onUnMask', 'isComplete', 'determineActiveMasksetIndex', + ], true) ) { $options[$key] = new JsExpression($value); } diff --git a/framework/widgets/MaskedInputAsset.php b/framework/widgets/MaskedInputAsset.php index 2325571..357c5e7 100644 --- a/framework/widgets/MaskedInputAsset.php +++ b/framework/widgets/MaskedInputAsset.php @@ -21,9 +21,9 @@ class MaskedInputAsset extends AssetBundle { public $sourcePath = '@bower/jquery.inputmask/dist'; public $js = [ - 'jquery.inputmask.bundle.js' + 'jquery.inputmask.bundle.js', ]; public $depends = [ - 'yii\web\YiiAsset' + 'yii\web\YiiAsset', ]; } diff --git a/framework/widgets/Menu.php b/framework/widgets/Menu.php index db678d4..9869650 100644 --- a/framework/widgets/Menu.php +++ b/framework/widgets/Menu.php @@ -11,8 +11,8 @@ use Closure; use Yii; use yii\base\Widget; use yii\helpers\ArrayHelper; -use yii\helpers\Url; use yii\helpers\Html; +use yii\helpers\Url; /** * Menu displays a multi-level menu using nested HTML lists. diff --git a/tests/IsOneOfAssert.php b/tests/IsOneOfAssert.php index 3ca85d2..3bd7ce0 100644 --- a/tests/IsOneOfAssert.php +++ b/tests/IsOneOfAssert.php @@ -1,4 +1,9 @@ $this->getVendorPath(), 'aliases' => [ '@bower' => '@vendor/bower-asset', - '@npm' => '@vendor/npm-asset', + '@npm' => '@vendor/npm-asset', ], 'components' => [ 'request' => [ @@ -78,7 +83,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase 'scriptFile' => __DIR__ . '/index.php', 'scriptUrl' => '/index.php', ], - ] + ], ], $config)); } diff --git a/tests/bootstrap.php b/tests/bootstrap.php index a1aebe7..db6bb10 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -1,4 +1,9 @@ does = 'meow'; } - } diff --git a/tests/data/ar/Customer.php b/tests/data/ar/Customer.php index a451dc3..216d6e1 100644 --- a/tests/data/ar/Customer.php +++ b/tests/data/ar/Customer.php @@ -1,4 +1,10 @@ does = 'bark'; } - } diff --git a/tests/data/ar/Item.php b/tests/data/ar/Item.php index 4b4977a..f2447c3 100644 --- a/tests/data/ar/Item.php +++ b/tests/data/ar/Item.php @@ -1,4 +1,9 @@ 'customer_id' + 0 => 'customer_id', ]; } } diff --git a/tests/data/ar/OrderItem.php b/tests/data/ar/OrderItem.php index 5a1492f..117abbe 100644 --- a/tests/data/ar/OrderItem.php +++ b/tests/data/ar/OrderItem.php @@ -1,4 +1,9 @@ hasOne(OrderItem::className(), ['item_id' => 'item_id', 'order_id' => 'order_id' ]) + return $this->hasOne(self::className(), ['item_id' => 'item_id', 'order_id' => 'order_id']) ->joinWith('item'); } public function getOrderItemCompositeNoJoin() { - return $this->hasOne(OrderItem::className(), ['item_id' => 'item_id', 'order_id' => 'order_id' ]); + return $this->hasOne(self::className(), ['item_id' => 'item_id', 'order_id' => 'order_id']); } } diff --git a/tests/data/ar/OrderItemWithNullFK.php b/tests/data/ar/OrderItemWithNullFK.php index 52cbc44..09c3494 100644 --- a/tests/data/ar/OrderItemWithNullFK.php +++ b/tests/data/ar/OrderItemWithNullFK.php @@ -1,4 +1,9 @@ + * @link http://www.yiiframework.com/ + * @copyright Copyright (c) 2008 Yii Software LLC + * @license http://www.yiiframework.com/license/ */ namespace yiiunit\data\ar; @@ -10,7 +12,6 @@ namespace yiiunit\data\ar; * * @property int $id * @property string $description - * */ class Profile extends ActiveRecord { diff --git a/tests/data/ar/Type.php b/tests/data/ar/Type.php index 0c5c69f..0b86110 100644 --- a/tests/data/ar/Type.php +++ b/tests/data/ar/Type.php @@ -1,4 +1,9 @@ 'Lennon'], [['lastName'], 'required'], [['underscore_style'], 'yii\captcha\CaptchaValidator'], - [['test'], 'required', 'when' => function($model) { return $model->firstName === 'cebe'; }], + [['test'], 'required', 'when' => function ($model) { return $model->firstName === 'cebe'; }], ]; } } diff --git a/tests/data/base/Speaker.php b/tests/data/base/Speaker.php index 5e80111..2bd3a65 100644 --- a/tests/data/base/Speaker.php +++ b/tests/data/base/Speaker.php @@ -1,4 +1,10 @@ * @since 2.0.11 @@ -17,4 +21,4 @@ class MockDependency extends Dependency { return $this->data; } -} \ No newline at end of file +} diff --git a/tests/data/config-docker.php b/tests/data/config-docker.php index 606f984..cef8189 100644 --- a/tests/data/config-docker.php +++ b/tests/data/config-docker.php @@ -1,4 +1,9 @@ [ 'cubrid' => [ @@ -56,4 +58,4 @@ if (is_file(__DIR__ . '/config.local.php')) { include(__DIR__ . '/config.local.php'); } -return $config; \ No newline at end of file +return $config; diff --git a/tests/data/config.php b/tests/data/config.php index 1072586..60cddd1 100644 --- a/tests/data/config.php +++ b/tests/data/config.php @@ -1,4 +1,9 @@ [ 'cubrid' => [ @@ -56,4 +58,4 @@ if (is_file(__DIR__ . '/config.local.php')) { include(__DIR__ . '/config.local.php'); } -return $config; \ No newline at end of file +return $config; diff --git a/tests/data/console/controllers/fixtures/FirstFixture.php b/tests/data/console/controllers/fixtures/FirstFixture.php index d97b542..49e3f68 100644 --- a/tests/data/console/controllers/fixtures/FirstFixture.php +++ b/tests/data/console/controllers/fixtures/FirstFixture.php @@ -1,4 +1,9 @@ 3, 'extensions' => ['png'], 'on' => 'validateMultipleFiles', 'checkExtensionByMimeType' => false], ['attr_image', 'file', 'extensions' => ['png'], 'on' => 'validateFile', 'checkExtensionByMimeType' => false], - ['!safe_attr', 'integer'] + ['!safe_attr', 'integer'], ]; } diff --git a/tests/data/validators/models/ValidatorTestMainModel.php b/tests/data/validators/models/ValidatorTestMainModel.php index 7031e3f..141fed2 100644 --- a/tests/data/validators/models/ValidatorTestMainModel.php +++ b/tests/data/validators/models/ValidatorTestMainModel.php @@ -1,4 +1,9 @@ Name: diff --git a/tests/data/views/errorHandler.php b/tests/data/views/errorHandler.php index 79e5566..0e34d61 100644 --- a/tests/data/views/errorHandler.php +++ b/tests/data/views/errorHandler.php @@ -1,12 +1,10 @@ Code: response->statusCode ?> Message: getMessage() ?> -Exception: \ No newline at end of file +Exception: diff --git a/tests/data/views/widgets/ListView/item.php b/tests/data/views/widgets/ListView/item.php index 5ac7564..f543715 100644 --- a/tests/data/views/widgets/ListView/item.php +++ b/tests/data/views/widgets/ListView/item.php @@ -1,10 +1,13 @@ className(); diff --git a/tests/framework/BaseYiiTest.php b/tests/framework/BaseYiiTest.php index 38df4fb..8216ed5 100644 --- a/tests/framework/BaseYiiTest.php +++ b/tests/framework/BaseYiiTest.php @@ -1,4 +1,10 @@ assertTrue(is_string(Yii::powered())); + $this->assertInternalType('string', Yii::powered()); } public function testCreateObjectCallable() @@ -70,19 +76,19 @@ class BaseYiiTest extends TestCase Yii::$container = new Container(); // Test passing in of normal params combined with DI params. - $this->assertTrue(Yii::createObject(function(Singer $singer, $a) { + $this->assertTrue(Yii::createObject(function (Singer $singer, $a) { return $a === 'a'; }, ['a'])); $singer = new Singer(); $singer->firstName = 'Bob'; - $this->assertTrue(Yii::createObject(function(Singer $singer, $a) { + $this->assertTrue(Yii::createObject(function (Singer $singer, $a) { return $singer->firstName === 'Bob'; }, [$singer, 'a'])); - $this->assertTrue(Yii::createObject(function(Singer $singer, $a = 3) { + $this->assertTrue(Yii::createObject(function (Singer $singer, $a = 3) { return true; })); } @@ -125,19 +131,19 @@ class BaseYiiTest extends TestCase [ $this->equalTo('warning message'), $this->equalTo(Logger::LEVEL_WARNING), - $this->equalTo('warning category') + $this->equalTo('warning category'), ], [$this->equalTo('trace message'), $this->equalTo(Logger::LEVEL_TRACE), $this->equalTo('trace category')], [$this->equalTo('error message'), $this->equalTo(Logger::LEVEL_ERROR), $this->equalTo('error category')], [ $this->equalTo('beginProfile message'), $this->equalTo(Logger::LEVEL_PROFILE_BEGIN), - $this->equalTo('beginProfile category') + $this->equalTo('beginProfile category'), ], [ $this->equalTo('endProfile message'), $this->equalTo(Logger::LEVEL_PROFILE_END), - $this->equalTo('endProfile category') + $this->equalTo('endProfile category'), ] ); diff --git a/tests/framework/ar/ActiveRecordTestTrait.php b/tests/framework/ar/ActiveRecordTestTrait.php index af014f4..2e76ba5 100644 --- a/tests/framework/ar/ActiveRecordTestTrait.php +++ b/tests/framework/ar/ActiveRecordTestTrait.php @@ -1,17 +1,17 @@ + * @link http://www.yiiframework.com/ + * @copyright Copyright (c) 2008 Yii Software LLC + * @license http://www.yiiframework.com/license/ */ namespace yiiunit\framework\ar; use yii\base\Event; use yii\db\BaseActiveRecord; -use yiiunit\TestCase; use yiiunit\data\ar\Customer; use yiiunit\data\ar\Order; +use yiiunit\TestCase; /** * This trait provides unit tests shared by the different AR implementations. @@ -151,7 +151,7 @@ trait ActiveRecordTestTrait /* @var $customerClass \yii\db\ActiveRecordInterface */ $customerClass = $this->getCustomerClass(); - $customer = new $customerClass; + $customer = new $customerClass(); $this->assertTrue($customer->hasAttribute('id')); $this->assertTrue($customer->hasAttribute('email')); $this->assertFalse($customer->hasAttribute(0)); @@ -369,7 +369,6 @@ trait ActiveRecordTestTrait $customer = $customerClass::find()->offset(3)->one(); $this->assertNull($customer); - } public function testFindComplexCondition() @@ -671,7 +670,7 @@ trait ActiveRecordTestTrait $this->assertCount(2, $customer->orders); // has many - $order = new $orderClass; + $order = new $orderClass(); $order->total = 100; $this->assertTrue($order->isNewRecord); $customer->link('orders', $order); @@ -682,7 +681,7 @@ trait ActiveRecordTestTrait $this->assertEquals(2, $order->customer_id); // belongs to - $order = new $orderClass; + $order = new $orderClass(); $order->total = 100; $this->assertTrue($order->isNewRecord); $customer = $customerClass::findOne(1); @@ -818,7 +817,7 @@ trait ActiveRecordTestTrait $this->assertCount(2, $order->booksWithNullFK); $orderItemCount = $orderItemsWithNullFKClass::find()->count(); $this->assertEquals(5, $itemClass::find()->count()); - $order->unlinkAll('booksWithNullFK',false); + $order->unlinkAll('booksWithNullFK', false); $this->afterSave(); $this->assertCount(0, $order->booksWithNullFK); $this->assertEquals(2, $orderItemsWithNullFKClass::find()->where(['AND', ['item_id' => [1, 2]], ['order_id' => null]])->count()); @@ -888,7 +887,7 @@ trait ActiveRecordTestTrait /* @var $customerClass \yii\db\ActiveRecordInterface */ $customerClass = $this->getCustomerClass(); /* @var $this TestCase|ActiveRecordTestTrait */ - $customer = new $customerClass; + $customer = new $customerClass(); $customer->email = 'user4@example.com'; $customer->name = 'user4'; $customer->address = 'address4'; @@ -912,7 +911,7 @@ trait ActiveRecordTestTrait /* @var $customerClass \yii\db\ActiveRecordInterface */ $customerClass = $this->getCustomerClass(); /* @var $this TestCase|ActiveRecordTestTrait */ - $customer = new $customerClass; + $customer = new $customerClass(); $customer->id = 1337; $customer->email = 'user1337@example.com'; $customer->name = 'user1337'; @@ -1261,12 +1260,10 @@ trait ActiveRecordTestTrait $this->assertFalse($customer->canSetProperty('orderItems')); try { - /* @var $itemClass \yii\db\ActiveRecordInterface */ $itemClass = $this->getItemClass(); $customer->orderItems = [new $itemClass()]; $this->fail('setter call above MUST throw Exception'); - } catch (\Exception $e) { // catch exception "Setting read-only property" $this->assertInstanceOf('yii\base\InvalidCallException', $e); @@ -1278,5 +1275,4 @@ trait ActiveRecordTestTrait $this->assertFalse($customer->canGetProperty('non_existing_property')); $this->assertFalse($customer->canSetProperty('non_existing_property')); } - } diff --git a/tests/framework/base/ActionFilterTest.php b/tests/framework/base/ActionFilterTest.php index 0b81ae3..0f86d9f 100644 --- a/tests/framework/base/ActionFilterTest.php +++ b/tests/framework/base/ActionFilterTest.php @@ -14,7 +14,6 @@ use yii\base\Controller; use yii\web\User; use yiiunit\TestCase; - /** * @group base */ @@ -243,4 +242,4 @@ class MockUser extends User { // do not call parent to avoid the need to mock configuration } -} \ No newline at end of file +} diff --git a/tests/framework/base/ApplicationTest.php b/tests/framework/base/ApplicationTest.php index 6071705..f3ce06c 100644 --- a/tests/framework/base/ApplicationTest.php +++ b/tests/framework/base/ApplicationTest.php @@ -1,4 +1,9 @@ mockApplication([ 'container' => [ 'definitions' => [ - Dispatcher::className() => DispatcherMock::className() - ] + Dispatcher::className() => DispatcherMock::className(), + ], ], - 'bootstrap' => ['log'] + 'bootstrap' => ['log'], ]); $this->assertInstanceOf(DispatcherMock::className(), Yii::$app->log); @@ -28,5 +33,4 @@ class ApplicationTest extends TestCase class DispatcherMock extends Dispatcher { - } diff --git a/tests/framework/base/BehaviorTest.php b/tests/framework/base/BehaviorTest.php index d923184..ecfeb23 100644 --- a/tests/framework/base/BehaviorTest.php +++ b/tests/framework/base/BehaviorTest.php @@ -1,4 +1,9 @@ on('click', 'yiiunit\framework\base\globalEventHandler2'); $component->on('click', [$this->component, 'myEventHandler']); $component->raiseEvent(); @@ -232,12 +238,12 @@ class ComponentTest extends TestCase public function testAttachBehavior() { - $component = new NewComponent; + $component = new NewComponent(); $this->assertFalse($component->hasProperty('p')); $this->assertFalse($component->behaviorCalled); $this->assertNull($component->getBehavior('a')); - $behavior = new NewBehavior; + $behavior = new NewBehavior(); $component->attachBehavior('a', $behavior); $this->assertSame($behavior, $component->getBehavior('a')); $this->assertTrue($component->hasProperty('p')); @@ -250,7 +256,7 @@ class ComponentTest extends TestCase $component->test(); $p = 'as b'; - $component = new NewComponent; + $component = new NewComponent(); $component->$p = ['class' => 'NewBehavior']; $this->assertSame($behavior, $component->getBehavior('a')); $this->assertTrue($component->hasProperty('p')); @@ -260,11 +266,11 @@ class ComponentTest extends TestCase public function testAttachBehaviors() { - $component = new NewComponent; + $component = new NewComponent(); $this->assertNull($component->getBehavior('a')); $this->assertNull($component->getBehavior('b')); - $behavior = new NewBehavior; + $behavior = new NewBehavior(); $component->attachBehaviors([ 'a' => $behavior, @@ -276,8 +282,8 @@ class ComponentTest extends TestCase public function testDetachBehavior() { - $component = new NewComponent; - $behavior = new NewBehavior; + $component = new NewComponent(); + $behavior = new NewBehavior(); $component->attachBehavior('a', $behavior); $this->assertSame($behavior, $component->getBehavior('a')); @@ -292,8 +298,8 @@ class ComponentTest extends TestCase public function testDetachBehaviors() { - $component = new NewComponent; - $behavior = new NewBehavior; + $component = new NewComponent(); + $behavior = new NewBehavior(); $component->attachBehavior('a', $behavior); $this->assertSame($behavior, $component->getBehavior('a')); @@ -316,7 +322,7 @@ class ComponentTest extends TestCase { $this->assertNull($this->component->getBehavior('a')); - $behavior = new NewBehavior; + $behavior = new NewBehavior(); $this->component->attachBehaviors([ 'a' => $behavior, ]); @@ -330,8 +336,8 @@ class ComponentTest extends TestCase $behaviorName = 'foo'; $this->assertNull($this->component->getBehavior($behaviorName)); $p = 'as ' . $behaviorName; - $this->component->$p = __NAMESPACE__ . '\NewBehavior'; - $this->assertSame(__NAMESPACE__ . '\NewBehavior', get_class($this->component->getBehavior($behaviorName))); + $this->component->$p = __NAMESPACE__ . '\NewBehavior'; + $this->assertSame(__NAMESPACE__ . '\NewBehavior', get_class($this->component->getBehavior($behaviorName))); } public function testWriteOnlyProperty() @@ -373,7 +379,7 @@ class NewComponent extends Component public function getObject() { if (!$this->_object) { - $this->_object = new self; + $this->_object = new self(); $this->_object->_text = 'object text'; } @@ -404,7 +410,7 @@ class NewComponent extends Component public function raiseEvent() { - $this->trigger('click', new Event); + $this->trigger('click', new Event()); } public function setWriteOnly() diff --git a/tests/framework/base/ControllerTest.php b/tests/framework/base/ControllerTest.php index fdf742e..9a6db54 100644 --- a/tests/framework/base/ControllerTest.php +++ b/tests/framework/base/ControllerTest.php @@ -1,4 +1,9 @@ action->uniqueId; return 'test2'; } -} \ No newline at end of file +} diff --git a/tests/framework/base/DynamicModelTest.php b/tests/framework/base/DynamicModelTest.php index d4ca339..8f03625 100644 --- a/tests/framework/base/DynamicModelTest.php +++ b/tests/framework/base/DynamicModelTest.php @@ -83,13 +83,13 @@ class DynamicModelTest extends TestCase $dynamic->defineAttribute('name'); $dynamic->defineAttribute('mobile'); // define rule - $dynamic->addRule(['name','mobile'], 'required'); + $dynamic->addRule(['name', 'mobile'], 'required'); // define your sample data $data = [ 'DynamicModel' => [ 'name' => $name = 'your name 2', 'mobile' => $mobile = 'my number mobile', - ] + ], ]; // load data $this->assertFalse($dynamic->load([])); diff --git a/tests/framework/base/EventTest.php b/tests/framework/base/EventTest.php index 3d9abcf..0f876ed 100644 --- a/tests/framework/base/EventTest.php +++ b/tests/framework/base/EventTest.php @@ -42,10 +42,10 @@ class EventTest extends TestCase $this->counter += 5; }); $this->assertEquals(0, $this->counter); - $post = new Post; + $post = new Post(); $post->save(); $this->assertEquals(4, $this->counter); - $user = new User; + $user = new User(); $user->save(); $this->assertEquals(7, $this->counter); $someClass = new SomeClass(); @@ -59,7 +59,7 @@ class EventTest extends TestCase public function testOff() { $handler = function ($event) { - $this->counter ++; + $this->counter++; }; $this->assertFalse(Event::hasHandlers(Post::className(), 'save')); Event::on(Post::className(), 'save', $handler); @@ -77,7 +77,7 @@ class EventTest extends TestCase $this->counter += 1; }); Event::on('yiiunit\framework\base\SomeInterface', SomeInterface::EVENT_SUPER_EVENT, function ($event) { - $this->counter ++; + $this->counter++; }); $this->assertTrue(Event::hasHandlers(Post::className(), 'save')); $this->assertFalse(Event::hasHandlers(ActiveRecord::className(), 'save')); diff --git a/tests/framework/base/ExposedSecurity.php b/tests/framework/base/ExposedSecurity.php index 431e123..db4408f 100644 --- a/tests/framework/base/ExposedSecurity.php +++ b/tests/framework/base/ExposedSecurity.php @@ -1,6 +1,11 @@ setScenario('test'); $this->assertTrue($speaker->isAttributeSafe('firstName')); - } public function testSafeScenarios() @@ -180,7 +184,7 @@ class ModelTest extends TestCase [['account_id', 'user_id'], 'required'], // only in create and update scenario [['user_id'], 'number', 'on' => ['create', 'update']], - [['email', 'name'], 'required', 'on' => 'create'] + [['email', 'name'], 'required', 'on' => 'create'], ]; $model->scenario = Model::SCENARIO_DEFAULT; $this->assertEquals(['account_id', 'user_id'], $model->safeAttributes()); @@ -236,7 +240,7 @@ class ModelTest extends TestCase $model = new RulesModel(); $model->rules = [ [['name', 'email'], 'required'], - [['!email'], 'safe'] + [['!email'], 'safe'], ]; $this->assertEquals(['name'], $model->safeAttributes()); $model->attributes = ['name' => 'mdmunir', 'email' => 'm2792684@mdm.com']; @@ -246,7 +250,7 @@ class ModelTest extends TestCase $model->rules = [ [['name', 'email'], 'required'], [['email'], 'email'], - [['!email'], 'safe', 'on' => 'update'] + [['!email'], 'safe', 'on' => 'update'], ]; $model->setScenario(RulesModel::SCENARIO_DEFAULT); $this->assertEquals(['name', 'email'], $model->safeAttributes()); @@ -325,7 +329,7 @@ class ModelTest extends TestCase $singer->clearErrors(); $errors = [ 'firstName' => ['Something is wrong!'], - 'lastName' => ['Another one!'] + 'lastName' => ['Another one!'], ]; $singer->addErrors($errors); $this->assertEquals($singer->getErrors(), $errors); @@ -333,7 +337,7 @@ class ModelTest extends TestCase $singer->clearErrors(); $errors = [ 'firstName' => ['Something is wrong!', 'Totally wrong!'], - 'lastName' => ['Another one!'] + 'lastName' => ['Another one!'], ]; $singer->addErrors($errors); $this->assertEquals($singer->getErrors(), $errors); @@ -341,7 +345,7 @@ class ModelTest extends TestCase $singer->clearErrors(); $errors = [ 'firstName' => ['Something is wrong!', 'Totally wrong!'], - 'lastName' => ['Another one!', 'Totally wrong!'] + 'lastName' => ['Another one!', 'Totally wrong!'], ]; $singer->addErrors($errors); $this->assertEquals($singer->getErrors(), $errors); @@ -488,4 +492,4 @@ class WriteOnlyModel extends Model { $this->passwordHash = $pw; } -} \ No newline at end of file +} diff --git a/tests/framework/base/ModuleTest.php b/tests/framework/base/ModuleTest.php index c2348c1..d00988e 100644 --- a/tests/framework/base/ModuleTest.php +++ b/tests/framework/base/ModuleTest.php @@ -1,4 +1,9 @@ assertEquals('yiiunit\framework\base\controllers', $module->controllerNamespace); - $this->assertEquals(__DIR__ . DIRECTORY_SEPARATOR . 'controllers', str_replace(['/','\\'], DIRECTORY_SEPARATOR , $module->controllerPath)); + $this->assertEquals(__DIR__ . DIRECTORY_SEPARATOR . 'controllers', str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $module->controllerPath)); } public function testSetupVersion() @@ -32,7 +37,7 @@ class ModuleTest extends TestCase $module->setVersion($version); $this->assertEquals($version, $module->getVersion()); - $module->setVersion(function($module) { + $module->setVersion(function ($module) { /* @var $module TestModule */ return 'version.' . $module->getUniqueId(); }); @@ -99,4 +104,4 @@ class ModuleTestController extends Controller { ModuleTest::$actionRuns[] = $this->action->uniqueId; } -} \ No newline at end of file +} diff --git a/tests/framework/base/ObjectTest.php b/tests/framework/base/ObjectTest.php index 10320f9..d02acae 100644 --- a/tests/framework/base/ObjectTest.php +++ b/tests/framework/base/ObjectTest.php @@ -1,4 +1,10 @@ mockApplication(); - $this->object = new NewObject; + $this->object = new NewObject(); } protected function tearDown() @@ -94,7 +100,8 @@ class ObjectTest extends TestCase $this->assertEmpty($this->object->Text); $this->assertFalse(isset($this->object->unknownProperty)); - $this->assertTrue(empty($this->object->unknownProperty)); + $isEmpty = empty($this->object->unknownProperty); + $this->assertTrue($isEmpty); } public function testUnset() @@ -175,7 +182,7 @@ class NewObject extends Object public function getObject() { if (!$this->_object) { - $this->_object = new self; + $this->_object = new self(); $this->_object->_text = 'object text'; } @@ -194,5 +201,7 @@ class NewObject extends Object return $this->_items; } - public function setWriteOnly() {} + public function setWriteOnly() + { + } } diff --git a/tests/framework/base/SecurityTest.php b/tests/framework/base/SecurityTest.php index c872f43..0c18514 100644 --- a/tests/framework/base/SecurityTest.php +++ b/tests/framework/base/SecurityTest.php @@ -13,8 +13,8 @@ namespace yii\base { * * This function overrides function_exists from the root namespace in yii\base. */ - function function_exists($name) { - + function function_exists($name) + { if (isset(\yiiunit\framework\base\SecurityTest::$functions[$name])) { return \yiiunit\framework\base\SecurityTest::$functions[$name]; } @@ -26,13 +26,15 @@ namespace yii\base { * * This function overrides fopen and fread from the root namespace in yii\base. */ - function fopen($filename, $mode) { + function fopen($filename, $mode) + { if (\yiiunit\framework\base\SecurityTest::$fopen !== null) { return \yiiunit\framework\base\SecurityTest::$fopen; } return \fopen($filename, $mode); } - function fread($handle, $length) { + function fread($handle, $length) + { if (\yiiunit\framework\base\SecurityTest::$fread !== null) { return \yiiunit\framework\base\SecurityTest::$fread; } @@ -41,7 +43,6 @@ namespace yii\base { } return \fread($handle, $length); } - } // closing namespace yii\base; namespace yiiunit\framework\base { @@ -863,11 +864,11 @@ TEXT; public function randomKeyInvalidInputs() { return [ - [ 0 ], - [ -1 ], - [ '0' ], - [ '34' ], - [ [] ], + [0], + [-1], + ['0'], + ['34'], + [[]], ]; } @@ -885,7 +886,7 @@ TEXT; */ public function testRandomKeyNoOptions() { - static::$functions = ['random_bytes' => false, 'openssl_random_pseudo_bytes' => false, 'mcrypt_create_iv' => false ]; + static::$functions = ['random_bytes' => false, 'openssl_random_pseudo_bytes' => false, 'mcrypt_create_iv' => false]; static::$fopen = false; $this->expectException('yii\base\Exception'); $this->expectExceptionMessage('Unable to generate a random key'); @@ -898,7 +899,7 @@ TEXT; */ public function testRandomKeyFreadFailure() { - static::$functions = ['random_bytes' => false, 'openssl_random_pseudo_bytes' => false, 'mcrypt_create_iv' => false ]; + static::$functions = ['random_bytes' => false, 'openssl_random_pseudo_bytes' => false, 'mcrypt_create_iv' => false]; static::$fread = false; $this->expectException('yii\base\Exception'); $this->expectExceptionMessage('Unable to generate a random key'); @@ -912,14 +913,14 @@ TEXT; public function randomKeyVariants() { return [ - [ ['random_bytes' => true, 'openssl_random_pseudo_bytes' => true, 'mcrypt_create_iv' => true ] ], - [ ['random_bytes' => true, 'openssl_random_pseudo_bytes' => true, 'mcrypt_create_iv' => false ] ], - [ ['random_bytes' => true, 'openssl_random_pseudo_bytes' => false, 'mcrypt_create_iv' => true ] ], - [ ['random_bytes' => true, 'openssl_random_pseudo_bytes' => false, 'mcrypt_create_iv' => false ] ], - [ ['random_bytes' => false, 'openssl_random_pseudo_bytes' => true, 'mcrypt_create_iv' => true ] ], - [ ['random_bytes' => false, 'openssl_random_pseudo_bytes' => true, 'mcrypt_create_iv' => false ] ], - [ ['random_bytes' => false, 'openssl_random_pseudo_bytes' => false, 'mcrypt_create_iv' => true ] ], - [ ['random_bytes' => false, 'openssl_random_pseudo_bytes' => false, 'mcrypt_create_iv' => false ] ], + [['random_bytes' => true, 'openssl_random_pseudo_bytes' => true, 'mcrypt_create_iv' => true]], + [['random_bytes' => true, 'openssl_random_pseudo_bytes' => true, 'mcrypt_create_iv' => false]], + [['random_bytes' => true, 'openssl_random_pseudo_bytes' => false, 'mcrypt_create_iv' => true]], + [['random_bytes' => true, 'openssl_random_pseudo_bytes' => false, 'mcrypt_create_iv' => false]], + [['random_bytes' => false, 'openssl_random_pseudo_bytes' => true, 'mcrypt_create_iv' => true]], + [['random_bytes' => false, 'openssl_random_pseudo_bytes' => true, 'mcrypt_create_iv' => false]], + [['random_bytes' => false, 'openssl_random_pseudo_bytes' => false, 'mcrypt_create_iv' => true]], + [['random_bytes' => false, 'openssl_random_pseudo_bytes' => false, 'mcrypt_create_iv' => false]], ]; } @@ -934,7 +935,7 @@ TEXT; } } // there is no /dev/urandom on windows so we expect this to fail - if (DIRECTORY_SEPARATOR === '\\' && $functions['random_bytes'] === false && $functions['openssl_random_pseudo_bytes'] === false && $functions['mcrypt_create_iv'] === false ) { + if (DIRECTORY_SEPARATOR === '\\' && $functions['random_bytes'] === false && $functions['openssl_random_pseudo_bytes'] === false && $functions['mcrypt_create_iv'] === false) { $this->expectException('yii\base\Exception'); $this->expectExceptionMessage('Unable to generate a random key'); } @@ -998,10 +999,10 @@ TEXT; $tests = [ "function_exists('random_bytes')", "defined('OPENSSL_VERSION_TEXT') ? OPENSSL_VERSION_TEXT : null", - "PHP_VERSION_ID", - "PHP_OS", + 'PHP_VERSION_ID', + 'PHP_OS', "function_exists('mcrypt_create_iv') ? bin2hex(mcrypt_create_iv(4, MCRYPT_DEV_URANDOM)) : null", - "DIRECTORY_SEPARATOR", + 'DIRECTORY_SEPARATOR', "ini_get('open_basedir')", ]; if (DIRECTORY_SEPARATOR === '/') { @@ -1045,7 +1046,7 @@ TEXT; 'salt', 1, 20, - '0c60c80f961f0e71f3a9b524af6012062fe037a6' + '0c60c80f961f0e71f3a9b524af6012062fe037a6', ], [ 'sha1', @@ -1053,7 +1054,7 @@ TEXT; 'salt', 2, 20, - 'ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957' + 'ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957', ], [ 'sha1', @@ -1061,7 +1062,7 @@ TEXT; 'salt', 4096, 20, - '4b007901b765489abead49d926f721d065a429c1' + '4b007901b765489abead49d926f721d065a429c1', ], [ 'sha1', @@ -1069,7 +1070,7 @@ TEXT; 'salt', 16777216, 20, - 'eefe3d61cd4da4e4e9945b3d6ba2158c2634e984' + 'eefe3d61cd4da4e4e9945b3d6ba2158c2634e984', ], [ 'sha1', @@ -1077,7 +1078,7 @@ TEXT; 'saltSALTsaltSALTsaltSALTsaltSALTsalt', 4096, 25, - '3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038' + '3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038', ], [ 'sha1', @@ -1085,7 +1086,7 @@ TEXT; "sa\0lt", 4096, 16, - '56fa6aa75548099dcc37d7f03425e0c3' + '56fa6aa75548099dcc37d7f03425e0c3', ], [ 'sha256', @@ -1093,7 +1094,7 @@ TEXT; 'salt', 1, 20, - '120fb6cffcf8b32c43e7225256c4f837a86548c9' + '120fb6cffcf8b32c43e7225256c4f837a86548c9', ], [ 'sha256', @@ -1101,7 +1102,7 @@ TEXT; "sa\0lt", 4096, 32, - '89b69d0516f829893c696226650a86878c029ac13ee276509d5ae58b6466a724' + '89b69d0516f829893c696226650a86878c029ac13ee276509d5ae58b6466a724', ], [ 'sha256', @@ -1109,7 +1110,7 @@ TEXT; 'saltSALTsaltSALTsaltSALTsaltSALTsalt', 4096, 40, - '348c89dbcbd32b2f32d814b8116e84cf2b17347ebc1800181c4e2a1fb8dd53e1c635518c7dac47e9' + '348c89dbcbd32b2f32d814b8116e84cf2b17347ebc1800181c4e2a1fb8dd53e1c635518c7dac47e9', ], ]; } @@ -1197,7 +1198,7 @@ TEXT; 'L' => 42, 'PRK' => '2adccada18779e7c2077ad2eb19d3f3e731385dd', 'OKM' => '2c91117204d745f3500d636a62f64f0ab3bae548aa53d423b0d1f27ebba6f5e5673a081d70cce7acfc48', - ] + ], ]; } @@ -1221,26 +1222,26 @@ TEXT; public function dataProviderCompareStrings() { return [ - ["", ""], - [false, ""], - [null, ""], - [0, ""], - [0.00, ""], - ["", null], - ["", false], - ["", 0], - ["", "\0"], - ["\0", ""], + ['', ''], + [false, ''], + [null, ''], + [0, ''], + [0.00, ''], + ['', null], + ['', false], + ['', 0], + ['', "\0"], + ["\0", ''], ["\0", "\0"], - ["0", "\0"], + ['0', "\0"], [0, "\0"], - ["user", "User"], - ["password", "password"], - ["password", "passwordpassword"], - ["password1", "password"], - ["password", "password2"], - ["", "password"], - ["password", ""], + ['user', 'User'], + ['password', 'password'], + ['password', 'passwordpassword'], + ['password1', 'password'], + ['password', 'password2'], + ['', 'password'], + ['password', ''], ]; } @@ -1282,15 +1283,14 @@ TEXT; /** * @return array */ - public function maskProvider() { + public function maskProvider() + { return [ ['1'], ['SimpleToken'], ['Token with special characters: %d1 5"'], - ['Token with UTF8 character: †'] + ['Token with UTF8 character: †'], ]; } } - } // closing namespace yiiunit\framework\base; - diff --git a/tests/framework/base/ThemeTest.php b/tests/framework/base/ThemeTest.php index 942bd16..006f516 100644 --- a/tests/framework/base/ThemeTest.php +++ b/tests/framework/base/ThemeTest.php @@ -1,10 +1,15 @@ assertEquals($obInitialLevel, ob_get_level()); } -} \ No newline at end of file +} diff --git a/tests/framework/base/fixtures/themes/basic/views/site/index.php b/tests/framework/base/fixtures/themes/basic/views/site/index.php index b3d9bbc..d63e9ec 100644 --- a/tests/framework/base/fixtures/themes/basic/views/site/index.php +++ b/tests/framework/base/fixtures/themes/basic/views/site/index.php @@ -1 +1,6 @@ [ 'class' => '\yii\db\Connection', 'dsn' => 'sqlite::memory:', - ] - ] + ], + ], ]); $columns = [ @@ -96,8 +101,7 @@ class AttributeBehaviorTest extends TestCase $preserveNonEmptyValues, $name, $alias - ) - { + ) { $model = new ActiveRecordWithAttributeBehavior(); $model->attributeBehavior->preserveNonEmptyValues = $preserveNonEmptyValues; $model->name = $name; @@ -111,7 +115,7 @@ class AttributeBehaviorTest extends TestCase /** * Test Active Record class with [[AttributeBehavior]] behavior attached. * - * @property integer $id + * @property int $id * @property string $name * @property string $alias * diff --git a/tests/framework/behaviors/AttributeTypecastBehaviorTest.php b/tests/framework/behaviors/AttributeTypecastBehaviorTest.php index 2de622f..4c57d60 100644 --- a/tests/framework/behaviors/AttributeTypecastBehaviorTest.php +++ b/tests/framework/behaviors/AttributeTypecastBehaviorTest.php @@ -1,12 +1,17 @@ [ 'class' => '\yii\db\Connection', 'dsn' => 'sqlite::memory:', - ] - ] + ], + ], ]); $columns = [ diff --git a/tests/framework/behaviors/BlameableBehaviorTest.php b/tests/framework/behaviors/BlameableBehaviorTest.php index f69fc05..b049d5d 100644 --- a/tests/framework/behaviors/BlameableBehaviorTest.php +++ b/tests/framework/behaviors/BlameableBehaviorTest.php @@ -1,13 +1,18 @@ [ 'class' => 'yiiunit\framework\behaviors\UserMock', - ] - ] + ], + ], ]); $columns = [ @@ -131,9 +136,9 @@ class BlameableBehaviorTest extends TestCase 'class' => BlameableBehavior::className(), 'attributes' => [ BaseActiveRecord::EVENT_BEFORE_VALIDATE => 'created_by', - BaseActiveRecord::EVENT_BEFORE_INSERT => ['created_by', 'updated_by'] - ] - ] + BaseActiveRecord::EVENT_BEFORE_INSERT => ['created_by', 'updated_by'], + ], + ], ]); $model->name = __METHOD__; @@ -149,7 +154,6 @@ class BlameableBehaviorTest extends TestCase $this->assertEquals(20, $model->created_by); $this->assertEquals(20, $model->updated_by); } - } /** diff --git a/tests/framework/behaviors/SluggableBehaviorTest.php b/tests/framework/behaviors/SluggableBehaviorTest.php index b119e37..6fae292 100644 --- a/tests/framework/behaviors/SluggableBehaviorTest.php +++ b/tests/framework/behaviors/SluggableBehaviorTest.php @@ -1,12 +1,17 @@ [ 'class' => '\yii\db\Connection', 'dsn' => 'sqlite::memory:', - ] - ] + ], + ], ]); $columns = [ @@ -139,7 +144,7 @@ class SluggableBehaviorTest extends TestCase $model->save(); $model = new ActiveRecordSluggableUnique(); - $model->sluggable->uniqueSlugGenerator = function($baseSlug, $iteration) {return $baseSlug . '-callback';}; + $model->sluggable->uniqueSlugGenerator = function ($baseSlug, $iteration) {return $baseSlug . '-callback';}; $model->name = $name; $model->save(); @@ -269,4 +274,4 @@ class ActiveRecordSluggableUnique extends ActiveRecordSluggable ], ]; } -} \ No newline at end of file +} diff --git a/tests/framework/behaviors/TimestampBehaviorTest.php b/tests/framework/behaviors/TimestampBehaviorTest.php index 5732a1f..0afdfc7 100644 --- a/tests/framework/behaviors/TimestampBehaviorTest.php +++ b/tests/framework/behaviors/TimestampBehaviorTest.php @@ -1,13 +1,18 @@ [ 'class' => '\yii\db\Connection', 'dsn' => 'sqlite::memory:', - ] - ] + ], + ], ]); $columns = [ @@ -188,7 +193,7 @@ class TimestampBehaviorTest extends TestCase $this->assertEquals($enforcedTime, $model->created_at, 'Create time has been set on update!'); $this->assertEquals(date('Y'), $model->updated_at); } - + public function testTouchingNewRecordGeneratesException() { ActiveRecordTimestamp::$behaviors = [ @@ -196,14 +201,14 @@ class TimestampBehaviorTest extends TestCase 'class' => TimestampBehavior::className(), 'value' => new Expression("strftime('%Y')"), ], - ]; + ]; $model = new ActiveRecordTimestamp(); - + $this->expectException('yii\base\InvalidCallException'); - + $model->touch('created_at'); } - + public function testTouchingNotNewRecord() { ActiveRecordTimestamp::$behaviors = [ @@ -218,7 +223,7 @@ class TimestampBehaviorTest extends TestCase $model->updated_at = $enforcedTime; $model->save(false); $expectedCreatedAt = new Expression("strftime('%Y')"); - + $model->touch('created_at'); $this->assertEquals($expectedCreatedAt, $model->created_at); diff --git a/tests/framework/caching/ApcCacheTest.php b/tests/framework/caching/ApcCacheTest.php index 126471c..80b5dfb 100644 --- a/tests/framework/caching/ApcCacheTest.php +++ b/tests/framework/caching/ApcCacheTest.php @@ -1,4 +1,10 @@ markTestSkipped("APC not installed. Skipping."); + if (!extension_loaded('apc')) { + $this->markTestSkipped('APC not installed. Skipping.'); } elseif ('cli' === PHP_SAPI && !ini_get('apc.enable_cli')) { - $this->markTestSkipped("APC cli is not enabled. Skipping."); + $this->markTestSkipped('APC cli is not enabled. Skipping.'); } - if (!ini_get("apc.enabled") || !ini_get("apc.enable_cli")) { - $this->markTestSkipped("APC is installed but not enabled. Skipping."); + if (!ini_get('apc.enabled') || !ini_get('apc.enable_cli')) { + $this->markTestSkipped('APC is installed but not enabled. Skipping.'); } if ($this->_cacheInstance === null) { @@ -36,11 +42,11 @@ class ApcCacheTest extends CacheTestCase public function testExpire() { - $this->markTestSkipped("APC keys are expiring only on the next request."); + $this->markTestSkipped('APC keys are expiring only on the next request.'); } public function testExpireAdd() { - $this->markTestSkipped("APC keys are expiring only on the next request."); + $this->markTestSkipped('APC keys are expiring only on the next request.'); } } diff --git a/tests/framework/caching/ArrayCacheTest.php b/tests/framework/caching/ArrayCacheTest.php index 5ec7d73..e6359e5 100644 --- a/tests/framework/caching/ArrayCacheTest.php +++ b/tests/framework/caching/ArrayCacheTest.php @@ -1,4 +1,9 @@ getConnection()->createCommand(" + $this->getConnection()->createCommand(' CREATE TABLE IF NOT EXISTS cache ( id char(128) NOT NULL, expire int(11) DEFAULT NULL, @@ -30,7 +35,7 @@ class DbCacheTest extends CacheTestCase PRIMARY KEY (id), KEY expire (expire) ); - ")->execute(); + ')->execute(); } /** @@ -42,7 +47,7 @@ class DbCacheTest extends CacheTestCase if ($this->_connection === null) { $databases = self::getParam('databases'); $params = $databases['mysql']; - $db = new \yii\db\Connection; + $db = new \yii\db\Connection(); $db->dsn = $params['dsn']; $db->username = $params['username']; $db->password = $params['password']; diff --git a/tests/framework/caching/DbDependencyTest.php b/tests/framework/caching/DbDependencyTest.php index 8dd1868..95c1cf9 100644 --- a/tests/framework/caching/DbDependencyTest.php +++ b/tests/framework/caching/DbDependencyTest.php @@ -1,4 +1,9 @@ assertTrue($dependency->isChanged($cache)); } -} \ No newline at end of file +} diff --git a/tests/framework/caching/DbQueryDependencyTest.php b/tests/framework/caching/DbQueryDependencyTest.php index 4f8a323..c66aa31 100644 --- a/tests/framework/caching/DbQueryDependencyTest.php +++ b/tests/framework/caching/DbQueryDependencyTest.php @@ -1,4 +1,9 @@ assertTrue($dependency->isChanged($cache)); } -} \ No newline at end of file +} diff --git a/tests/framework/caching/DependencyTest.php b/tests/framework/caching/DependencyTest.php index 48c7491..255c804 100644 --- a/tests/framework/caching/DependencyTest.php +++ b/tests/framework/caching/DependencyTest.php @@ -1,4 +1,9 @@ isChanged($cache); $this->assertTrue($result); } -} \ No newline at end of file +} diff --git a/tests/framework/caching/FileCacheTest.php b/tests/framework/caching/FileCacheTest.php index 1c7e183..7129c88 100644 --- a/tests/framework/caching/FileCacheTest.php +++ b/tests/framework/caching/FileCacheTest.php @@ -1,4 +1,10 @@ markTestSkipped("memcache not installed. Skipping."); + if (!extension_loaded('memcache')) { + $this->markTestSkipped('memcache not installed. Skipping.'); } // check whether memcached is running and skip tests if not. diff --git a/tests/framework/caching/MemCachedTest.php b/tests/framework/caching/MemCachedTest.php index 56a5570..05682f3 100644 --- a/tests/framework/caching/MemCachedTest.php +++ b/tests/framework/caching/MemCachedTest.php @@ -1,4 +1,10 @@ markTestSkipped("memcached not installed. Skipping."); + if (!extension_loaded('memcached')) { + $this->markTestSkipped('memcached not installed. Skipping.'); } // check whether memcached is running and skip tests if not. diff --git a/tests/framework/caching/TagDependencyTest.php b/tests/framework/caching/TagDependencyTest.php index 8b61b27..b56c91b 100644 --- a/tests/framework/caching/TagDependencyTest.php +++ b/tests/framework/caching/TagDependencyTest.php @@ -1,9 +1,15 @@ markTestSkipped("Wincache not installed. Skipping."); + $this->markTestSkipped('Wincache not installed. Skipping.'); } if (!ini_get('wincache.ucenabled')) { - $this->markTestSkipped("Wincache user cache disabled. Skipping."); + $this->markTestSkipped('Wincache user cache disabled. Skipping.'); } if ($this->_cacheInstance === null) { diff --git a/tests/framework/caching/XCacheTest.php b/tests/framework/caching/XCacheTest.php index ca2b79c..6702829 100644 --- a/tests/framework/caching/XCacheTest.php +++ b/tests/framework/caching/XCacheTest.php @@ -1,4 +1,10 @@ markTestSkipped("XCache not installed. Skipping."); + if (!function_exists('xcache_isset')) { + $this->markTestSkipped('XCache not installed. Skipping.'); } if ($this->_cacheInstance === null) { diff --git a/tests/framework/caching/ZendDataCacheTest.php b/tests/framework/caching/ZendDataCacheTest.php index 63c0d10..86b5bf1 100644 --- a/tests/framework/caching/ZendDataCacheTest.php +++ b/tests/framework/caching/ZendDataCacheTest.php @@ -1,4 +1,10 @@ markTestSkipped("Zend Data cache not installed. Skipping."); + if (!function_exists('zend_shm_cache_store')) { + $this->markTestSkipped('Zend Data cache not installed. Skipping.'); } if ($this->_cacheInstance === null) { diff --git a/tests/framework/console/ControllerTest.php b/tests/framework/console/ControllerTest.php index cc6a698..f9855f6 100644 --- a/tests/framework/console/ControllerTest.php +++ b/tests/framework/console/ControllerTest.php @@ -85,13 +85,13 @@ class ControllerTest extends TestCase $response = $this->runRequest('fake/status'); $this->assertResponseStatus(0, $response); - $response = $this->runRequest('fake/status', (string)$status); + $response = $this->runRequest('fake/status', (string) $status); $this->assertResponseStatus($status, $response); $response = $this->runRequest('fake/response'); $this->assertResponseStatus(0, $response); - $response = $this->runRequest('fake/response', (string)$status); + $response = $this->runRequest('fake/response', (string) $status); $this->assertResponseStatus($status, $response); } @@ -139,11 +139,11 @@ class ControllerTest extends TestCase * @see #10372 */ public function testHelpSkipsTypeHintedArguments() - { - $controller = new FakeController('fake', Yii::$app); - $help = $controller->getActionArgsHelp($controller->createAction('with-complex-type-hint')); + { + $controller = new FakeController('fake', Yii::$app); + $help = $controller->getActionArgsHelp($controller->createAction('with-complex-type-hint')); - $this->assertArrayNotHasKey('typedArgument', $help); - $this->assertArrayHasKey('simpleArgument', $help); - } + $this->assertArrayNotHasKey('typedArgument', $help); + $this->assertArrayHasKey('simpleArgument', $help); + } } diff --git a/tests/framework/console/FakeController.php b/tests/framework/console/FakeController.php index 2fc6ab1..7ca0d55 100644 --- a/tests/framework/console/FakeController.php +++ b/tests/framework/console/FakeController.php @@ -37,7 +37,7 @@ class FakeController extends Controller return array_merge(parent::options($actionID), [ 'test', 'testArray', - 'alias' + 'alias', ]); } @@ -46,7 +46,7 @@ class FakeController extends Controller return [ 't' => 'test', 'ta' => 'testArray', - 'a' => 'alias' + 'a' => 'alias', ]; } @@ -84,7 +84,8 @@ class FakeController extends Controller return $this->testArray; } - public function actionWithComplexTypeHint(self $typedArgument, $simpleArgument) { + public function actionWithComplexTypeHint(self $typedArgument, $simpleArgument) + { return $simpleArgument; } @@ -96,7 +97,7 @@ class FakeController extends Controller public function actionResponse($status = 0) { $response = new Response(); - $response->exitStatus = (int)$status; + $response->exitStatus = (int) $status; return $response; } } diff --git a/tests/framework/console/FakeHelpController.php b/tests/framework/console/FakeHelpController.php index 32876d6..9b0ea50 100644 --- a/tests/framework/console/FakeHelpController.php +++ b/tests/framework/console/FakeHelpController.php @@ -1,4 +1,9 @@ [], 'exception' => [ '\yii\console\Exception', - 'Parameter "0" is not valid' + 'Parameter "0" is not valid', ], ], ]; diff --git a/tests/framework/console/UnkownCommandExceptionTest.php b/tests/framework/console/UnkownCommandExceptionTest.php index 88897ed..6d743ec 100644 --- a/tests/framework/console/UnkownCommandExceptionTest.php +++ b/tests/framework/console/UnkownCommandExceptionTest.php @@ -8,7 +8,6 @@ namespace yiiunit\framework\console; use Yii; -use yii\console\Application; use yii\console\UnknownCommandException; use yiiunit\TestCase; diff --git a/tests/framework/console/controllers/AssetControllerTest.php b/tests/framework/console/controllers/AssetControllerTest.php index 9e3026b..15aa565 100644 --- a/tests/framework/console/controllers/AssetControllerTest.php +++ b/tests/framework/console/controllers/AssetControllerTest.php @@ -1,14 +1,19 @@ runAssetControllerAction('template', [$configFileName]); $this->assertFileExists($configFileName, 'Unable to create config file template!'); $config = require($configFileName); - $this->assertTrue(is_array($config), 'Invalid config created!'); + $this->assertInternalType('array', $config, 'Invalid config created!'); } public function testActionCompress() @@ -275,9 +280,9 @@ EOL; 'js/test_alert.js' => "function test() { alert('Test message'); }", - 'js/test_sum_ab.js' => "function sumAB(a, b) { + 'js/test_sum_ab.js' => 'function sumAB(a, b) { return a + b; - }", + }', ]; $this->createAssetSourceFiles($jsFiles); $assetBundleClassName = $this->declareAssetBundleClass([ @@ -286,7 +291,7 @@ EOL; ]); $bundles = [ - $assetBundleClassName + $assetBundleClassName, ]; $bundleFile = $this->testFilePath . DIRECTORY_SEPARATOR . 'bundle.php'; @@ -299,7 +304,7 @@ EOL; // Then : $this->assertFileExists($bundleFile, 'Unable to create output bundle file!'); $compressedBundleConfig = require($bundleFile); - $this->assertTrue(is_array($compressedBundleConfig), 'Output bundle file has incorrect format!'); + $this->assertInternalType('array', $compressedBundleConfig, 'Output bundle file has incorrect format!'); $this->assertCount(2, $compressedBundleConfig, 'Output bundle config contains wrong bundle count!'); $this->assertArrayHasKey($assetBundleClassName, $compressedBundleConfig, 'Source bundle is lost!'); @@ -339,7 +344,7 @@ EOL; '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js', ], 'css' => [ - '//ajax.googleapis.com/css/libs/jquery/2.1.1/jquery.ui.min.css' + '//ajax.googleapis.com/css/libs/jquery/2.1.1/jquery.ui.min.css', ], ]; $externalAssetBundleClassName = $this->declareAssetBundleClass($externalAssetConfig); @@ -362,11 +367,11 @@ EOL; 'css' => array_keys($cssFiles), 'js' => array_keys($jsFiles), 'depends' => [ - $externalAssetBundleClassName + $externalAssetBundleClassName, ], ]); $bundles = [ - $regularAssetBundleClassName + $regularAssetBundleClassName, ]; $bundleFile = $this->testFilePath . DIRECTORY_SEPARATOR . 'bundle.php'; @@ -379,7 +384,7 @@ EOL; // Then : $this->assertFileExists($bundleFile, 'Unable to create output bundle file!'); $compressedBundleConfig = require($bundleFile); - $this->assertTrue(is_array($compressedBundleConfig), 'Output bundle file has incorrect format!'); + $this->assertInternalType('array', $compressedBundleConfig, 'Output bundle file has incorrect format!'); $this->assertArrayHasKey($externalAssetBundleClassName, $compressedBundleConfig, 'External bundle is lost!'); $compressedExternalAssetConfig = $compressedBundleConfig[$externalAssetBundleClassName]; @@ -404,33 +409,33 @@ EOL; 'namespace' => $namespace, 'class' => 'AssetStart', 'depends' => [ - $namespace . '\AssetA' + $namespace . '\AssetA', ], ]); $this->declareAssetBundleClass([ 'namespace' => $namespace, 'class' => 'AssetA', 'depends' => [ - $namespace . '\AssetB' + $namespace . '\AssetB', ], ]); $this->declareAssetBundleClass([ 'namespace' => $namespace, 'class' => 'AssetB', 'depends' => [ - $namespace . '\AssetC' + $namespace . '\AssetC', ], ]); $this->declareAssetBundleClass([ 'namespace' => $namespace, 'class' => 'AssetC', 'depends' => [ - $namespace . '\AssetA' + $namespace . '\AssetA', ], ]); $bundles = [ - $namespace . '\AssetStart' + $namespace . '\AssetStart', ]; $bundleFile = $this->testFilePath . DIRECTORY_SEPARATOR . 'bundle.php'; @@ -542,10 +547,10 @@ EOL; '.published-relative-dir-class {background-image: url(../img/same_relative_dir.png);}', ], [ - "img {clip-path: url(#xxx)}", + 'img {clip-path: url(#xxx)}', '/test/base/path/css', '/test/base/path/assets/output', - "img {clip-path: url(#xxx)}", + 'img {clip-path: url(#xxx)}', ], ]; } @@ -645,14 +650,14 @@ EOL; ]); $bundles = [ - $assetBundleClassName + $assetBundleClassName, ]; $bundleFile = $this->testFilePath . DIRECTORY_SEPARATOR . 'bundle.php'; // Keep source : $configFile = $this->testFilePath . DIRECTORY_SEPARATOR . 'config_no_source_delete.php'; $this->createCompressConfigFile($configFile, $bundles, [ - 'deleteSource' => false + 'deleteSource' => false, ]); $this->runAssetControllerAction('compress', [$configFile, $bundleFile]); @@ -660,7 +665,7 @@ EOL; $files = FileHelper::findFiles($this->testAssetsBasePath, [ 'only' => [ 'test_body.css', - 'test_alert.js' + 'test_alert.js', ], ]); $this->assertNotEmpty($files); @@ -668,7 +673,7 @@ EOL; // Delete source : $configFile = $this->testFilePath . DIRECTORY_SEPARATOR . 'config_source_delete.php'; $this->createCompressConfigFile($configFile, $bundles, [ - 'deleteSource' => true + 'deleteSource' => true, ]); $this->runAssetControllerAction('compress', [$configFile, $bundleFile]); @@ -676,7 +681,7 @@ EOL; $files = FileHelper::findFiles($this->testAssetsBasePath, [ 'only' => [ 'test_body.css', - 'test_alert.js' + 'test_alert.js', ], ]); $this->assertEmpty($files); @@ -712,7 +717,7 @@ EOL; ]); $bundles = [ - $assetBundleClassName + $assetBundleClassName, ]; $bundleFile = $this->testFilePath . DIRECTORY_SEPARATOR . 'bundle_override_as_external.php'; @@ -723,10 +728,10 @@ EOL; 'basePath' => null, 'baseUrl' => null, 'css' => [ - '//some.cdn.com/js/override_external.css' + '//some.cdn.com/js/override_external.css', ], 'js' => [ - '//some.cdn.com/js/override_external.js' + '//some.cdn.com/js/override_external.js', ], ]; $this->createCompressConfigFile($configFile, $bundles, [ @@ -734,7 +739,7 @@ EOL; 'bundles' => [ $assetBundleClassName => $assetBundleOverrideConfig, ], - ] + ], ]); $this->runAssetControllerAction('compress', [$configFile, $bundleFile]); @@ -752,4 +757,4 @@ EOL; class AssetControllerMock extends AssetController { use StdOutBufferControllerTrait; -} \ No newline at end of file +} diff --git a/tests/framework/console/controllers/BaseMessageControllerTest.php b/tests/framework/console/controllers/BaseMessageControllerTest.php index 1b7251d..417e36c 100644 --- a/tests/framework/console/controllers/BaseMessageControllerTest.php +++ b/tests/framework/console/controllers/BaseMessageControllerTest.php @@ -1,11 +1,17 @@ _cacheController = Yii::createObject([ 'class' => 'yiiunit\framework\console\controllers\SilencedCacheController', 'interactive' => false, - ],[null, null]); //id and module are null + ], [null, null]); //id and module are null $databases = self::getParam('databases'); $config = $databases[$this->driverName]; @@ -77,8 +81,8 @@ class CacheControllerTest extends TestCase $this->_cacheController->actionFlush('firstCache'); - $this->assertFalse(Yii::$app->firstCache->get('firstKey'),'first cache data should be flushed'); - $this->assertFalse(Yii::$app->firstCache->get('secondKey'),'first cache data should be flushed'); + $this->assertFalse(Yii::$app->firstCache->get('firstKey'), 'first cache data should be flushed'); + $this->assertFalse(Yii::$app->firstCache->get('secondKey'), 'first cache data should be flushed'); $this->assertEquals('thirdValue', Yii::$app->secondCache->get('thirdKey'), 'second cache data should not be flushed'); } @@ -98,7 +102,6 @@ class CacheControllerTest extends TestCase $this->_cacheController->actionFlushSchema('db'); $cacheSchema = $schema->getTableSchemas('', false); $this->assertEquals($noCacheSchemas, $cacheSchema, 'Schema cache should be flushed.'); - } public function testFlushBoth() @@ -109,8 +112,8 @@ class CacheControllerTest extends TestCase $this->_cacheController->actionFlush('firstCache', 'secondCache'); - $this->assertFalse(Yii::$app->firstCache->get('firstKey'),'first cache data should be flushed'); - $this->assertFalse(Yii::$app->firstCache->get('secondKey'),'first cache data should be flushed'); + $this->assertFalse(Yii::$app->firstCache->get('firstKey'), 'first cache data should be flushed'); + $this->assertFalse(Yii::$app->firstCache->get('secondKey'), 'first cache data should be flushed'); $this->assertFalse(Yii::$app->secondCache->get('thirdKey'), 'second cache data should be flushed'); } @@ -138,8 +141,7 @@ class CacheControllerTest extends TestCase $this->_cacheController->actionFlushAll(); - $this->assertFalse(Yii::$app->firstCache->get('firstKey'),'first cache data should be flushed'); + $this->assertFalse(Yii::$app->firstCache->get('firstKey'), 'first cache data should be flushed'); $this->assertFalse(Yii::$app->secondCache->get('thirdKey'), 'second cache data should be flushed'); } - } diff --git a/tests/framework/console/controllers/DbMessageControllerTest.php b/tests/framework/console/controllers/DbMessageControllerTest.php index f999598..c2a4665 100644 --- a/tests/framework/console/controllers/DbMessageControllerTest.php +++ b/tests/framework/console/controllers/DbMessageControllerTest.php @@ -1,4 +1,10 @@ runAction($route, $params); - echo "Result is " . $result; + echo 'Result is ' . $result; if ($result !== \yii\console\Controller::EXIT_CODE_NORMAL) { ob_end_flush(); } else { @@ -84,7 +90,7 @@ class DbMessageControllerTest extends BaseMessageControllerTest public static function getConnection() { if (static::$db == null) { - $db = new Connection; + $db = new Connection(); $db->dsn = static::$database['dsn']; if (isset(static::$database['username'])) { $db->username = static::$database['username']; @@ -111,7 +117,7 @@ class DbMessageControllerTest extends BaseMessageControllerTest 'languages' => [$this->language], 'sourcePath' => $this->sourcePath, 'overwrite' => true, - 'db' => static::$db + 'db' => static::$db, ]; } @@ -127,12 +133,12 @@ class DbMessageControllerTest extends BaseMessageControllerTest foreach ($messages as $source => $translation) { $lastPk = static::$db->schema->insert('source_message', [ 'category' => $category, - 'message' => $source + 'message' => $source, ]); static::$db->createCommand()->insert('message', [ 'id' => $lastPk['id'], 'language' => $this->language, - 'translation' => $translation + 'translation' => $translation, ])->execute(); } } diff --git a/tests/framework/console/controllers/EchoMigrateController.php b/tests/framework/console/controllers/EchoMigrateController.php index 9e362bd..eec267f 100644 --- a/tests/framework/console/controllers/EchoMigrateController.php +++ b/tests/framework/console/controllers/EchoMigrateController.php @@ -1,4 +1,10 @@ _fixtureController->globalFixtures = [ - '\yiiunit\data\console\controllers\fixtures\Global' + '\yiiunit\data\console\controllers\fixtures\Global', ]; $this->_fixtureController->actionLoad(['First']); @@ -56,7 +60,7 @@ class FixtureControllerTest extends TestCase public function testUnloadGlobalFixture() { $this->_fixtureController->globalFixtures = [ - '\yiiunit\data\console\controllers\fixtures\Global' + '\yiiunit\data\console\controllers\fixtures\Global', ]; FixtureStorage::$globalFixturesData[] = 'some seeded global fixture data'; @@ -209,7 +213,6 @@ class FixtureControllerTest extends TestCase class FixtureConsoledController extends FixtureController { - public function stdout($string) { } diff --git a/tests/framework/console/controllers/HelpControllerTest.php b/tests/framework/console/controllers/HelpControllerTest.php index b175b90..4d4ea40 100644 --- a/tests/framework/console/controllers/HelpControllerTest.php +++ b/tests/framework/console/controllers/HelpControllerTest.php @@ -1,8 +1,14 @@ assertContains('--port, -p: int (defaults to 8080)', $result); $this->assertContains('--router, -r: string', $result); } - - } diff --git a/tests/framework/console/controllers/MigrateControllerTest.php b/tests/framework/console/controllers/MigrateControllerTest.php index f22f5a1..ef05458 100644 --- a/tests/framework/console/controllers/MigrateControllerTest.php +++ b/tests/framework/console/controllers/MigrateControllerTest.php @@ -1,4 +1,9 @@ 'title:string(10):notNull:unique:defaultValue("test"), body:text:notNull, price:money(11,2):notNull, - parenthesis_in_comment:string(255):notNull:comment(\'Name of set (RU)\')' + parenthesis_in_comment:string(255):notNull:comment(\'Name of set (RU)\')', ]); $this->assertCommandCreatedFile('create_title_pk', $migrationName, $table, [ @@ -132,7 +137,7 @@ class MigrateControllerTest extends TestCase $this->assertCommandCreatedFile('drop_products_from_store_table', 'drop_' . $table . '_table', $table); } // @see https://github.com/yiisoft/yii2/issues/11461 - $this->assertCommandCreatedFile('create_title_with_comma_default_values', 'create_test_table', 'test', [ + $this->assertCommandCreatedFile('create_title_with_comma_default_values', 'create_test_table', 'test', [ 'fields' => 'title:string(10):notNull:unique:defaultValue(",te,st"), body:text:notNull:defaultValue(",test"), test:custom(11,2,"s"):notNull', @@ -151,7 +156,7 @@ class MigrateControllerTest extends TestCase $this->assertCommandCreatedFile('drop_test', $migrationName, $table); $this->assertCommandCreatedFile('drop_fields', $migrationName, $table, [ - 'fields' => 'body:text:notNull,price:money(11,2)' + 'fields' => 'body:text:notNull,price:money(11,2)', ]); } @@ -174,7 +179,7 @@ class MigrateControllerTest extends TestCase 'fields' => 'title:string(10):notNull, body:text:notNull, price:money(11,2):notNull, - created_at:dateTime' + created_at:dateTime', ]); $this->assertCommandCreatedFile('add_columns_fk', $migrationName, $table, [ @@ -209,7 +214,7 @@ class MigrateControllerTest extends TestCase $this->assertCommandCreatedFile('drop_columns_test', $migrationName, $table, [ 'fields' => 'title:string(10):notNull,body:text:notNull, price:money(11,2):notNull, - created_at:dateTime' + created_at:dateTime', ]); } } @@ -235,7 +240,7 @@ class MigrateControllerTest extends TestCase { $controllerConfig = [ 'migrationPath' => null, - 'migrationNamespaces' => [$this->migrationNamespace] + 'migrationNamespaces' => [$this->migrationNamespace], ]; $this->runMigrateControllerAction('history', [], $controllerConfig); @@ -283,4 +288,4 @@ class MigrateControllerTest extends TestCase array_keys($rows) ); } -} \ No newline at end of file +} diff --git a/tests/framework/console/controllers/MigrateControllerTestTrait.php b/tests/framework/console/controllers/MigrateControllerTestTrait.php index 39fef0c..b95160f 100644 --- a/tests/framework/console/controllers/MigrateControllerTestTrait.php +++ b/tests/framework/console/controllers/MigrateControllerTestTrait.php @@ -1,4 +1,9 @@ assertTrue($success, $message); } @@ -341,7 +346,7 @@ CODE; $migrationName = 'testDefaultNamespace'; $this->runMigrateControllerAction('create', [$migrationName], [ 'migrationPath' => null, - 'migrationNamespaces' => [$this->migrationNamespace] + 'migrationNamespaces' => [$this->migrationNamespace], ]); $files = FileHelper::findFiles($this->migrationPath); $fileContent = file_get_contents($files[0]); @@ -353,7 +358,7 @@ CODE; $migrationName = 'test_namespace_specify'; $this->runMigrateControllerAction('create', [$this->migrationNamespace . '\\' . $migrationName], [ 'migrationPath' => $this->migrationPath, - 'migrationNamespaces' => [$this->migrationNamespace] + 'migrationNamespaces' => [$this->migrationNamespace], ]); $files = FileHelper::findFiles($this->migrationPath); $fileContent = file_get_contents($files[0]); @@ -364,7 +369,7 @@ CODE; $migrationName = 'test_no_namespace'; $this->runMigrateControllerAction('create', [$migrationName], [ 'migrationPath' => $this->migrationPath, - 'migrationNamespaces' => [$this->migrationNamespace] + 'migrationNamespaces' => [$this->migrationNamespace], ]); $files = FileHelper::findFiles($this->migrationPath); $fileContent = file_get_contents($files[0]); @@ -381,7 +386,7 @@ CODE; $this->runMigrateControllerAction('up', [], [ 'migrationPath' => null, - 'migrationNamespaces' => [$this->migrationNamespace] + 'migrationNamespaces' => [$this->migrationNamespace], ]); $this->assertMigrationHistory([ @@ -402,7 +407,7 @@ CODE; $controllerConfig = [ 'migrationPath' => null, - 'migrationNamespaces' => [$this->migrationNamespace] + 'migrationNamespaces' => [$this->migrationNamespace], ]; $this->runMigrateControllerAction('up', [], $controllerConfig); $this->runMigrateControllerAction('down', [1], $controllerConfig); @@ -421,7 +426,7 @@ CODE; { $controllerConfig = [ 'migrationPath' => null, - 'migrationNamespaces' => [$this->migrationNamespace] + 'migrationNamespaces' => [$this->migrationNamespace], ]; $output = $this->runMigrateControllerAction('history', [], $controllerConfig); @@ -443,7 +448,7 @@ CODE; { $controllerConfig = [ 'migrationPath' => null, - 'migrationNamespaces' => [$this->migrationNamespace] + 'migrationNamespaces' => [$this->migrationNamespace], ]; $version = '010101000001'; @@ -461,7 +466,7 @@ CODE; { $controllerConfig = [ 'migrationPath' => null, - 'migrationNamespaces' => [$this->migrationNamespace] + 'migrationNamespaces' => [$this->migrationNamespace], ]; $version = '020202000020'; @@ -481,7 +486,7 @@ CODE; FileHelper::createDirectory(Yii::getAlias('@yiiunit/runtime/extension_migrations')); $controllerConfig = [ 'migrationPath' => [$appPath = '@yiiunit/runtime/app_migrations', $extensionPath = '@yiiunit/runtime/extension_migrations'], - 'migrationNamespaces' => [$this->migrationNamespace] + 'migrationNamespaces' => [$this->migrationNamespace], ]; $this->createMigration('app_migration1', '010101_000001', $appPath); @@ -579,8 +584,8 @@ CODE; 'm010101_000002_ext_migration1', 'm010101_000003_app_migration2', $this->migrationNamespace . '\\M010101000004NsMigration', - 'm*_app_migration3' + 'm*_app_migration3', ]); - $this->assertCount(1, FileHelper::findFiles(Yii::getAlias($appPath), ['only'=> ['m*_app_migration3.php']])); + $this->assertCount(1, FileHelper::findFiles(Yii::getAlias($appPath), ['only' => ['m*_app_migration3.php']])); } } diff --git a/tests/framework/console/controllers/PHPMessageControllerTest.php b/tests/framework/console/controllers/PHPMessageControllerTest.php index 36c4357..4c74d60 100644 --- a/tests/framework/console/controllers/PHPMessageControllerTest.php +++ b/tests/framework/console/controllers/PHPMessageControllerTest.php @@ -1,6 +1,11 @@ stdOutBuffer = ''; return $result; } -} \ No newline at end of file +} diff --git a/tests/framework/data/ActiveDataProviderTest.php b/tests/framework/data/ActiveDataProviderTest.php index 024ef39..b496dcb 100644 --- a/tests/framework/data/ActiveDataProviderTest.php +++ b/tests/framework/data/ActiveDataProviderTest.php @@ -13,9 +13,9 @@ use yii\db\Query; use yiiunit\data\ar\ActiveRecord; use yiiunit\data\ar\Customer; use yiiunit\data\ar\Item; +use yiiunit\data\ar\Order; use yiiunit\framework\db\DatabaseTestCase; use yiiunit\framework\db\UnqueryableQueryMock; -use yiiunit\data\ar\Order; /** * @author Qiang Xue @@ -48,7 +48,7 @@ abstract class ActiveDataProviderTest extends DatabaseTestCase 'query' => Order::find(), 'pagination' => [ 'pageSize' => 2, - ] + ], ]); $orders = $provider->getModels(); $this->assertCount(2, $orders); @@ -71,7 +71,7 @@ abstract class ActiveDataProviderTest extends DatabaseTestCase 'query' => $customer->getOrders(), 'pagination' => [ 'pageSize' => 1, - ] + ], ]); $orders = $provider->getModels(); $this->assertCount(1, $orders); @@ -95,7 +95,7 @@ abstract class ActiveDataProviderTest extends DatabaseTestCase 'query' => $order->getItems(), 'pagination' => [ 'pageSize' => 2, - ] + ], ]); $items = $provider->getModels(); $this->assertCount(2, $items); @@ -117,7 +117,7 @@ abstract class ActiveDataProviderTest extends DatabaseTestCase 'query' => $order->getBooks(), 'pagination' => [ 'pageSize' => 1, - ] + ], ]); $items = $provider->getModels(); $this->assertCount(1, $items); @@ -125,23 +125,23 @@ abstract class ActiveDataProviderTest extends DatabaseTestCase public function testQuery() { - $query = new Query; + $query = new Query(); $provider = new ActiveDataProvider([ 'db' => $this->getConnection(), 'query' => $query->from('order')->orderBy('id'), ]); $orders = $provider->getModels(); $this->assertCount(3, $orders); - $this->assertTrue(is_array($orders[0])); + $this->assertInternalType('array', $orders[0]); $this->assertEquals([0, 1, 2], $provider->getKeys()); - $query = new Query; + $query = new Query(); $provider = new ActiveDataProvider([ 'db' => $this->getConnection(), 'query' => $query->from('order'), 'pagination' => [ 'pageSize' => 2, - ] + ], ]); $orders = $provider->getModels(); $this->assertCount(2, $orders); @@ -149,7 +149,7 @@ abstract class ActiveDataProviderTest extends DatabaseTestCase public function testRefresh() { - $query = new Query; + $query = new Query(); $provider = new ActiveDataProvider([ 'db' => $this->getConnection(), 'query' => $query->from('order')->orderBy('id'), @@ -164,7 +164,7 @@ abstract class ActiveDataProviderTest extends DatabaseTestCase public function testPaginationBeforeModels() { - $query = new Query; + $query = new Query(); $provider = new ActiveDataProvider([ 'db' => $this->getConnection(), 'query' => $query->from('order')->orderBy('id'), @@ -182,7 +182,7 @@ abstract class ActiveDataProviderTest extends DatabaseTestCase public function testDoesNotPerformQueryWhenHasNoModels() { - $query = new UnqueryableQueryMock; + $query = new UnqueryableQueryMock(); $provider = new ActiveDataProvider([ 'db' => $this->getConnection(), 'query' => $query->from('order')->where('0=1'), diff --git a/tests/framework/data/ArrayDataProviderTest.php b/tests/framework/data/ArrayDataProviderTest.php index e883784..3d74535 100644 --- a/tests/framework/data/ArrayDataProviderTest.php +++ b/tests/framework/data/ArrayDataProviderTest.php @@ -1,4 +1,9 @@ 'zero'], - ['name' => 'one'] + ['name' => 'one'], ]; $dataProvider = new ArrayDataProvider(['allModels' => $simpleArray]); $this->assertEquals($simpleArray, $dataProvider->getModels()); @@ -43,7 +48,7 @@ class ArrayDataProviderTest extends TestCase ], 'defaultOrder' => [ 'sort' => SORT_ASC, - ] + ], ], ] ); @@ -55,7 +60,7 @@ class ArrayDataProviderTest extends TestCase { $simpleArray = [ ['innerArray' => ['sortField' => 1]], - ['innerArray' => ['sortField' => 0]] + ['innerArray' => ['sortField' => 0]], ]; $dataProvider = new ArrayDataProvider( [ @@ -71,13 +76,13 @@ class ArrayDataProviderTest extends TestCase ], 'defaultOrder' => [ 'sort' => SORT_ASC, - ] + ], ], ] ); $sortedArray = [ ['innerArray' => ['sortField' => 0]], - ['innerArray' => ['sortField' => 1]] + ['innerArray' => ['sortField' => 1]], ]; $this->assertEquals($sortedArray, $dataProvider->getModels()); } @@ -86,44 +91,44 @@ class ArrayDataProviderTest extends TestCase { // source data $unsortedProjects = [ - ['title'=>'Zabbix', 'license'=>'GPL'], - ['title'=>'munin', 'license'=>'GPL'], - ['title'=>'Arch Linux', 'license'=>'GPL'], - ['title'=>'Nagios', 'license'=>'GPL'], - ['title'=>'zend framework', 'license'=>'BSD'], - ['title'=>'Zope', 'license'=>'ZPL'], - ['title'=>'active-record', 'license'=>false], - ['title'=>'ActiveState', 'license'=>false], - ['title'=>'mach', 'license'=>false], - ['title'=>'MySQL', 'license'=>'GPL'], - ['title'=>'mssql', 'license'=>'EULA'], - ['title'=>'Master-Master', 'license'=>false], - ['title'=>'Zend Engine', 'license'=>false], - ['title'=>'Mageia Linux', 'license'=>'GNU GPL'], - ['title'=>'nginx', 'license'=>'BSD'], - ['title'=>'Mozilla Firefox', 'license'=>'MPL'], + ['title' => 'Zabbix', 'license' => 'GPL'], + ['title' => 'munin', 'license' => 'GPL'], + ['title' => 'Arch Linux', 'license' => 'GPL'], + ['title' => 'Nagios', 'license' => 'GPL'], + ['title' => 'zend framework', 'license' => 'BSD'], + ['title' => 'Zope', 'license' => 'ZPL'], + ['title' => 'active-record', 'license' => false], + ['title' => 'ActiveState', 'license' => false], + ['title' => 'mach', 'license' => false], + ['title' => 'MySQL', 'license' => 'GPL'], + ['title' => 'mssql', 'license' => 'EULA'], + ['title' => 'Master-Master', 'license' => false], + ['title' => 'Zend Engine', 'license' => false], + ['title' => 'Mageia Linux', 'license' => 'GNU GPL'], + ['title' => 'nginx', 'license' => 'BSD'], + ['title' => 'Mozilla Firefox', 'license' => 'MPL'], ]; // expected data $sortedProjects = [ // upper cased titles - ['title'=>'ActiveState', 'license'=>false], - ['title'=>'Arch Linux', 'license'=>'GPL'], - ['title'=>'Mageia Linux', 'license'=>'GNU GPL'], - ['title'=>'Master-Master', 'license'=>false], - ['title'=>'Mozilla Firefox', 'license'=>'MPL'], - ['title'=>'MySQL', 'license'=>'GPL'], - ['title'=>'Nagios', 'license'=>'GPL'], - ['title'=>'Zabbix', 'license'=>'GPL'], - ['title'=>'Zend Engine', 'license'=>false], - ['title'=>'Zope', 'license'=>'ZPL'], + ['title' => 'ActiveState', 'license' => false], + ['title' => 'Arch Linux', 'license' => 'GPL'], + ['title' => 'Mageia Linux', 'license' => 'GNU GPL'], + ['title' => 'Master-Master', 'license' => false], + ['title' => 'Mozilla Firefox', 'license' => 'MPL'], + ['title' => 'MySQL', 'license' => 'GPL'], + ['title' => 'Nagios', 'license' => 'GPL'], + ['title' => 'Zabbix', 'license' => 'GPL'], + ['title' => 'Zend Engine', 'license' => false], + ['title' => 'Zope', 'license' => 'ZPL'], // lower cased titles - ['title'=>'active-record', 'license'=>false], - ['title'=>'mach', 'license'=>false], - ['title'=>'mssql', 'license'=>'EULA'], - ['title'=>'munin', 'license'=>'GPL'], - ['title'=>'nginx', 'license'=>'BSD'], - ['title'=>'zend framework', 'license'=>'BSD'], + ['title' => 'active-record', 'license' => false], + ['title' => 'mach', 'license' => false], + ['title' => 'mssql', 'license' => 'EULA'], + ['title' => 'munin', 'license' => 'GPL'], + ['title' => 'nginx', 'license' => 'BSD'], + ['title' => 'zend framework', 'license' => 'BSD'], ]; $dataProvider = new ArrayDataProvider( @@ -140,7 +145,7 @@ class ArrayDataProviderTest extends TestCase ], 'defaultOrder' => [ 'sort' => SORT_ASC, - ] + ], ], 'pagination' => [ 'pageSize' => 100500, diff --git a/tests/framework/data/BaseDataProviderTest.php b/tests/framework/data/BaseDataProviderTest.php index 2c1827e..d59b5e0 100644 --- a/tests/framework/data/BaseDataProviderTest.php +++ b/tests/framework/data/BaseDataProviderTest.php @@ -1,9 +1,14 @@ assertNull((new ConcreteDataProvider())->id); $this->assertNotNull((new ConcreteDataProvider())->id); } - } /** diff --git a/tests/framework/data/PaginationTest.php b/tests/framework/data/PaginationTest.php index a410b38..85951ff 100644 --- a/tests/framework/data/PaginationTest.php +++ b/tests/framework/data/PaginationTest.php @@ -1,4 +1,9 @@ mockWebApplication([ 'components' => [ 'urlManager' => [ - 'scriptUrl' => '/index.php' + 'scriptUrl' => '/index.php', ], ], ]); diff --git a/tests/framework/data/SortTest.php b/tests/framework/data/SortTest.php index 8b68ddb..426b6b5 100644 --- a/tests/framework/data/SortTest.php +++ b/tests/framework/data/SortTest.php @@ -7,9 +7,9 @@ namespace yiiunit\framework\data; +use yii\data\Sort; use yii\web\UrlManager; use yiiunit\TestCase; -use yii\data\Sort; /** * @author Qiang Xue @@ -36,7 +36,7 @@ class SortTest extends TestCase ], ], 'params' => [ - 'sort' => 'age,-name' + 'sort' => 'age,-name', ], 'enableMultiSort' => true, ]); @@ -67,7 +67,7 @@ class SortTest extends TestCase ], ], 'params' => [ - 'sort' => 'age,-name' + 'sort' => 'age,-name', ], 'enableMultiSort' => true, ]); @@ -97,7 +97,7 @@ class SortTest extends TestCase ], ], 'params' => [ - 'sort' => 'age,-name' + 'sort' => 'age,-name', ], 'enableMultiSort' => true, ]); @@ -121,7 +121,7 @@ class SortTest extends TestCase ], ], 'params' => [ - 'sort' => 'age,-name' + 'sort' => 'age,-name', ], 'enableMultiSort' => true, ]); @@ -157,7 +157,7 @@ class SortTest extends TestCase ], ], 'params' => [ - 'sort' => 'age,-name' + 'sort' => 'age,-name', ], 'enableMultiSort' => true, 'route' => 'site/index', @@ -184,7 +184,7 @@ class SortTest extends TestCase ], ], 'params' => [ - 'sort' => 'age,-name' + 'sort' => 'age,-name', ], 'enableMultiSort' => true, 'urlManager' => $manager, @@ -216,7 +216,7 @@ class SortTest extends TestCase ], ], 'params' => [ - 'sort' => 'age,-name' + 'sort' => 'age,-name', ], 'enableMultiSort' => true, 'urlManager' => $manager, @@ -231,15 +231,15 @@ class SortTest extends TestCase $sort = new CustomSort([ 'attributes' => [ 'age', - 'name' + 'name', ], 'params' => [ 'sort' => [ ['field' => 'age', 'dir' => 'asc'], - ['field' => 'name', 'dir' => 'desc'] - ] + ['field' => 'name', 'dir' => 'desc'], + ], ], - 'enableMultiSort' => true + 'enableMultiSort' => true, ]); $this->assertEquals(SORT_ASC, $sort->getAttributeOrder('age')); diff --git a/tests/framework/data/SqlDataProviderTest.php b/tests/framework/data/SqlDataProviderTest.php index d5edc47..3ccb408 100644 --- a/tests/framework/data/SqlDataProviderTest.php +++ b/tests/framework/data/SqlDataProviderTest.php @@ -1,12 +1,14 @@ 'select * from `customer` where id > :minimum', 'params' => [ - ':minimum' => -1 + ':minimum' => -1, ], 'db' => $this->getConnection(), ]); diff --git a/tests/framework/db/ActiveQueryTest.php b/tests/framework/db/ActiveQueryTest.php index 792f896..230ec45 100644 --- a/tests/framework/db/ActiveQueryTest.php +++ b/tests/framework/db/ActiveQueryTest.php @@ -1,4 +1,9 @@ joinWith('profile'); $this->assertEquals([ - [['profile'], true, 'LEFT JOIN'] + [['profile'], true, 'LEFT JOIN'], ], $result->joinWith); } @@ -125,7 +130,7 @@ abstract class ActiveQueryTest extends DatabaseTestCase $query = new ActiveQuery(Customer::className()); $result = $query->innerJoinWith('profile'); $this->assertEquals([ - [['profile'], true, 'INNER JOIN'] + [['profile'], true, 'INNER JOIN'], ], $result->joinWith); } @@ -135,16 +140,16 @@ abstract class ActiveQueryTest extends DatabaseTestCase public function testGetQueryTableName_from_not_set() { $query = new ActiveQuery(Customer::className()); - $result = $this->invokeMethod($query,'getTableNameAndAlias'); - $this->assertEquals(['customer','customer'], $result); + $result = $this->invokeMethod($query, 'getTableNameAndAlias'); + $this->assertEquals(['customer', 'customer'], $result); } public function testGetQueryTableName_from_set() { - $options = ['from' => ['alias'=>'customer']]; + $options = ['from' => ['alias' => 'customer']]; $query = new ActiveQuery(Customer::className(), $options); - $result = $this->invokeMethod($query,'getTableNameAndAlias'); - $this->assertEquals(['customer','alias'], $result); + $result = $this->invokeMethod($query, 'getTableNameAndAlias'); + $this->assertEquals(['customer', 'alias'], $result); } public function testOnCondition() @@ -280,7 +285,7 @@ abstract class ActiveQueryTest extends DatabaseTestCase public function testGetTableNames_isFromObject_generateException() { $query = new ActiveQuery(null); - $query->from = new \stdClass; + $query->from = new \stdClass(); $this->setExpectedException('\yii\base\InvalidConfigException'); @@ -329,14 +334,14 @@ abstract class ActiveQueryTest extends DatabaseTestCase '{{srv}}' => '{{service}}', '{{order}}' => '{{order}}', '{{c d}}' => '{{a b}}', - '{{myalias}}' => '{{something}}' + '{{myalias}}' => '{{something}}', ], $tables); } public function testGetTablesAlias_isFromObject_generateException() { $query = new ActiveQuery(null); - $query->from = new \stdClass; + $query->from = new \stdClass(); $this->setExpectedException('\yii\base\InvalidConfigException'); diff --git a/tests/framework/db/ActiveRecordTest.php b/tests/framework/db/ActiveRecordTest.php index 8c5b105..6f607eb 100644 --- a/tests/framework/db/ActiveRecordTest.php +++ b/tests/framework/db/ActiveRecordTest.php @@ -1,26 +1,31 @@ assertCount(0, $order->books); $order = Order::find()->where(['id' => 1])->asArray()->one(); - $this->assertTrue(is_array($order)); + $this->assertInternalType('array', $order); } public function testFindEagerViaTable() @@ -207,10 +212,10 @@ abstract class ActiveRecordTest extends DatabaseTestCase // https://github.com/yiisoft/yii2/issues/1402 $orders = Order::find()->with('books')->orderBy('id')->asArray()->all(); $this->assertCount(3, $orders); - $this->assertTrue(is_array($orders[0]['orderItems'][0])); + $this->assertInternalType('array', $orders[0]['orderItems'][0]); $order = $orders[0]; - $this->assertTrue(is_array($order)); + $this->assertInternalType('array', $order); $this->assertEquals(1, $order['id']); $this->assertCount(2, $order['books']); $this->assertEquals(1, $order['books'][0]['id']); @@ -258,7 +263,6 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertCount(1, $orders); $this->assertInstanceOf(Order::className(), $orders[0]); $this->assertEquals(2, $orders[0]->id); - } public function testStoreNull() @@ -393,7 +397,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase // inner join filtering without eager loading, conditions on both primary and relation $orders = Order::find()->innerJoinWith([ 'customer' => function ($query) { - $query->where(['customer.id' => 2]); + $query->where(['customer.id' => 2]); }, ], false)->where(['order.id' => [1, 2]])->orderBy('order.id')->all(); $this->assertCount(1, $orders); @@ -430,7 +434,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $orders = Order::find()->joinWith([ 'customer' => function ($q) { $q->from('customer c'); - } + }, ])->orderBy('c.id DESC, order.id')->all(); $this->assertCount(3, $orders); $this->assertEquals(2, $orders[0]->id); @@ -509,9 +513,13 @@ abstract class ActiveRecordTest extends DatabaseTestCase // https://github.com/yiisoft/yii2/issues/2880 $query = Order::findOne(1); - $customer = $query->getCustomer()->joinWith([ - 'orders' => function ($q) { $q->orderBy([]); } - ])->one(); + $customer = $query->getCustomer() + ->joinWith([ + 'orders' => function ($q) { + $q->orderBy([]); + }, + ]) + ->one(); $this->assertEquals(1, $customer->id); $order = Order::find()->joinWith([ 'items' => function ($q) { @@ -521,16 +529,19 @@ abstract class ActiveRecordTest extends DatabaseTestCase ])->orderBy('order.id')->one(); // join with sub-relation called inside Closure - $orders = Order::find()->joinWith([ + $orders = Order::find() + ->joinWith([ 'items' => function ($q) { $q->orderBy('item.id'); $q->joinWith([ - 'category'=> function ($q) { - $q->where('{{category}}.[[id]] = 2'); - } - ]); + 'category' => function ($q) { + $q->where('{{category}}.[[id]] = 2'); + }, + ]); }, - ])->orderBy('order.id')->all(); + ]) + ->orderBy('order.id') + ->all(); $this->assertCount(1, $orders); $this->assertTrue($orders[0]->isRelationPopulated('items')); $this->assertEquals(2, $orders[0]->id); @@ -561,7 +572,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $customers = Customer::find()->active()->joinWith([ 'orders' => function ($q) { $q->orderBy('order.id'); - } + }, ])->orderBy('customer.id DESC, order.id')->all(); $this->assertCount(2, $customers); $this->assertEquals(2, $customers[0]->id); @@ -667,11 +678,10 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertCount(2, $orders[0]->books); $this->assertCount(1, $orders[1]->books); - // joining sub relations $query = Order::find()->innerJoinWith([ 'items i' => function ($q) use ($aliasMethod) { - /** @var $q ActiveQuery */ + /* @var $q ActiveQuery */ if ($aliasMethod === 'explicit') { $q->orderBy('{{i}}.[[id]]'); } elseif ($aliasMethod === 'querysyntax') { @@ -681,15 +691,15 @@ abstract class ActiveRecordTest extends DatabaseTestCase } }, 'items.category c' => function ($q) use ($aliasMethod) { - /** @var $q ActiveQuery */ - if ($aliasMethod === 'explicit') { - $q->where('{{c}}.[[id]] = 2'); - } elseif ($aliasMethod === 'querysyntax') { - $q->where('{{@category}}.[[id]] = 2'); - } elseif ($aliasMethod === 'applyAlias') { - $q->where([$q->applyAlias('category', 'id') => 2]); - } - }, + /* @var $q ActiveQuery */ + if ($aliasMethod === 'explicit') { + $q->where('{{c}}.[[id]] = 2'); + } elseif ($aliasMethod === 'querysyntax') { + $q->where('{{@category}}.[[id]] = 2'); + } elseif ($aliasMethod === 'applyAlias') { + $q->where([$q->applyAlias('category', 'id') => 2]); + } + }, ]); if ($aliasMethod === 'explicit') { $orders = $query->orderBy('{{i}}.id')->all(); @@ -768,7 +778,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase // join with sub-relation called inside Closure $orders = Order::find()->joinWith([ 'items' => function ($q) use ($aliasMethod) { - /** @var $q ActiveQuery */ + /* @var $q ActiveQuery */ $q->orderBy('item.id'); $q->joinWith(['category c']); if ($aliasMethod === 'explicit') { @@ -786,7 +796,6 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertCount(3, $orders[0]->items); $this->assertTrue($orders[0]->items[0]->isRelationPopulated('category')); $this->assertEquals(2, $orders[0]->items[0]->category->id); - } public function testJoinWithSameTable() @@ -820,8 +829,16 @@ abstract class ActiveRecordTest extends DatabaseTestCase // alias is defined in the call to joinWith() // without eager loading $query = Order::find() - ->joinWith(['itemsIndexed books' => function($q) { $q->onCondition('books.category_id = 1'); }], false) - ->joinWith(['itemsIndexed movies' => function($q) { $q->onCondition('movies.category_id = 2'); }], false) + ->joinWith([ + 'itemsIndexed books' => function ($q) { + $q->onCondition('books.category_id = 1'); + }, + ], false) + ->joinWith([ + 'itemsIndexed movies' => function ($q) { + $q->onCondition('movies.category_id = 2'); + }, + ], false) ->where(['movies.name' => 'Toy Story']); $orders = $query->all(); $this->assertCount(1, $orders, $query->createCommand()->rawSql . print_r($orders, true)); @@ -829,8 +846,16 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertFalse($orders[0]->isRelationPopulated('itemsIndexed')); // with eager loading, only for one relation as it would be overwritten otherwise. $query = Order::find() - ->joinWith(['itemsIndexed books' => function($q) { $q->onCondition('books.category_id = 1'); }], false) - ->joinWith(['itemsIndexed movies' => function($q) { $q->onCondition('movies.category_id = 2'); }], true) + ->joinWith([ + 'itemsIndexed books' => function ($q) { + $q->onCondition('books.category_id = 1'); + }, + ], false) + ->joinWith([ + 'itemsIndexed movies' => function ($q) { + $q->onCondition('movies.category_id = 2'); + }, + ], true) ->where(['movies.name' => 'Toy Story']); $orders = $query->all(); $this->assertCount(1, $orders, $query->createCommand()->rawSql . print_r($orders, true)); @@ -839,8 +864,16 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertCount(3, $orders[0]->itemsIndexed); // with eager loading, and the other relation $query = Order::find() - ->joinWith(['itemsIndexed books' => function($q) { $q->onCondition('books.category_id = 1'); }], true) - ->joinWith(['itemsIndexed movies' => function($q) { $q->onCondition('movies.category_id = 2'); }], false) + ->joinWith([ + 'itemsIndexed books' => function ($q) { + $q->onCondition('books.category_id = 1'); + }, + ], true) + ->joinWith([ + 'itemsIndexed movies' => function ($q) { + $q->onCondition('movies.category_id = 2'); + }, + ], false) ->where(['movies.name' => 'Toy Story']); $orders = $query->all(); $this->assertCount(1, $orders, $query->createCommand()->rawSql . print_r($orders, true)); @@ -877,7 +910,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertInstanceOf('yiiunit\data\ar\Customer', $customerWithJoin); $customerWithJoinIndexOrdered = $order->customerJoinedWithProfileIndexOrdered; - $this->assertTrue(is_array($customerWithJoinIndexOrdered)); + $this->assertInternalType('array', $customerWithJoinIndexOrdered); $this->assertArrayHasKey('user1', $customerWithJoinIndexOrdered); $this->assertInstanceOf('yiiunit\data\ar\Customer', $customerWithJoinIndexOrdered['user1']); } @@ -905,12 +938,12 @@ abstract class ActiveRecordTest extends DatabaseTestCase /** @var $order Order */ $order = Order::findOne(1); $itemsSQL = $order->getOrderitems()->createCommand()->rawSql; - $expectedSQL = $this->replaceQuotes("SELECT * FROM [[order_item]] WHERE [[order_id]]=1"); + $expectedSQL = $this->replaceQuotes('SELECT * FROM [[order_item]] WHERE [[order_id]]=1'); $this->assertEquals($expectedSQL, $itemsSQL); $order = Order::findOne(1); $itemsSQL = $order->getOrderItems()->joinWith('item')->createCommand()->rawSql; - $expectedSQL = $this->replaceQuotes("SELECT [[order_item]].* FROM [[order_item]] LEFT JOIN [[item]] ON [[order_item]].[[item_id]] = [[item]].[[id]] WHERE [[order_item]].[[order_id]]=1"); + $expectedSQL = $this->replaceQuotes('SELECT [[order_item]].* FROM [[order_item]] LEFT JOIN [[item]] ON [[order_item]].[[item_id]] = [[item]].[[id]] WHERE [[order_item]].[[order_id]]=1'); $this->assertEquals($expectedSQL, $itemsSQL); Order::$tableName = null; @@ -1127,7 +1160,14 @@ abstract class ActiveRecordTest extends DatabaseTestCase $this->assertCount(2, $orders[0]->orderItems); $this->assertCount(3, $orders[1]->orderItems); $this->assertCount(1, $orders[2]->orderItems); - $orders = Order::find()->with(['orderItems' => function ($q) { $q->indexBy('item_id'); }])->orderBy('id')->all(); + $orders = Order::find() + ->with([ + 'orderItems' => function ($q) { + $q->indexBy('item_id'); + }, + ]) + ->orderBy('id') + ->all(); $this->assertCount(3, $orders); $this->assertCount(2, $orders[0]->orderItems); $this->assertCount(3, $orders[1]->orderItems); @@ -1156,7 +1196,7 @@ abstract class ActiveRecordTest extends DatabaseTestCase public function testSaveEmpty() { - $record = new NullValues; + $record = new NullValues(); $this->assertTrue($record->save(false)); $this->assertEquals(1, $record->id); } @@ -1276,9 +1316,9 @@ abstract class ActiveRecordTest extends DatabaseTestCase public function testLinkWhenRelationIsIndexed2() { $order = Order::find() - ->with('orderItems2') - ->where(['id' => 1]) - ->one(); + ->with('orderItems2') + ->where(['id' => 1]) + ->one(); $orderItem = new OrderItem([ 'order_id' => $order->id, 'item_id' => 3, @@ -1292,9 +1332,9 @@ abstract class ActiveRecordTest extends DatabaseTestCase public function testLinkWhenRelationIsIndexed3() { $order = Order::find() - ->with('orderItems3') - ->where(['id' => 1]) - ->one(); + ->with('orderItems3') + ->where(['id' => 1]) + ->one(); $orderItem = new OrderItem([ 'order_id' => $order->id, 'item_id' => 3, diff --git a/tests/framework/db/BatchQueryResultTest.php b/tests/framework/db/BatchQueryResultTest.php index 5fab5ce..0936cdd 100644 --- a/tests/framework/db/BatchQueryResultTest.php +++ b/tests/framework/db/BatchQueryResultTest.php @@ -1,11 +1,16 @@ createCommand(); - $this->assertEquals(null, $command->sql); + $this->assertNull($command->sql); // string $sql = 'SELECT * FROM customer'; @@ -43,7 +48,7 @@ abstract class CommandTest extends DatabaseTestCase $sql = 'SELECT [[id]], [[t.name]] FROM {{customer}} t'; $command = $db->createCommand($sql); - $this->assertEquals("SELECT `id`, `t`.`name` FROM `customer` t", $command->sql); + $this->assertEquals('SELECT `id`, `t`.`name` FROM `customer` t', $command->sql); } public function testPrepareCancel() @@ -53,7 +58,7 @@ abstract class CommandTest extends DatabaseTestCase $command = $db->createCommand('SELECT * FROM {{customer}}'); $this->assertEquals(null, $command->pdoStatement); $command->prepare(); - $this->assertNotEquals(null, $command->pdoStatement); + $this->assertNotNull($command->pdoStatement); $command->cancel(); $this->assertEquals(null, $command->pdoStatement); } @@ -202,7 +207,7 @@ SQL; } elseif (defined('HHVM_VERSION') && $this->driverName === 'pgsql') { // HHVMs pgsql implementation does not seem to support blob columns correctly. } else { - $this->assertTrue(is_resource($row['blob_col'])); + $this->assertInternalType('resource', $row['blob_col']); $this->assertEquals($blobCol, stream_get_contents($row['blob_col'])); } $this->assertEquals($numericCol, $row['numeric_col']); @@ -266,7 +271,7 @@ SQL; $command = $db->createCommand($sql); $command->fetchMode = \PDO::FETCH_OBJ; $result = $command->queryOne(); - $this->assertTrue(is_object($result)); + $this->assertInternalType('object', $result); // FETCH_NUM, customized in query method $sql = 'SELECT * FROM {{customer}}'; @@ -442,7 +447,8 @@ SQL; * Data provider for testInsertSelectFailed * @return array */ - public function invalidSelectColumns() { + public function invalidSelectColumns() + { return [ [[]], ['*'], @@ -481,7 +487,7 @@ SQL; break; case 'cubrid': case 'mysql': - $expression = "YEAR(NOW())"; + $expression = 'YEAR(NOW())'; break; case 'sqlite': $expression = "strftime('%Y')"; diff --git a/tests/framework/db/ConnectionTest.php b/tests/framework/db/ConnectionTest.php index 772ce09..3562e0e 100644 --- a/tests/framework/db/ConnectionTest.php +++ b/tests/framework/db/ConnectionTest.php @@ -1,4 +1,9 @@ getConnection(false); @@ -33,7 +37,7 @@ abstract class ConnectionTest extends DatabaseTestCase $this->assertFalse($connection->isActive); $this->assertEquals(null, $connection->pdo); - $connection = new Connection; + $connection = new Connection(); $connection->dsn = 'unknown::memory:'; $this->expectException('yii\db\Exception'); $connection->open(); @@ -47,7 +51,7 @@ abstract class ConnectionTest extends DatabaseTestCase $unserialized = unserialize($serialized); $this->assertInstanceOf('yii\db\Connection', $unserialized); - $this->assertEquals(123, $unserialized->createCommand("SELECT 123")->queryScalar()); + $this->assertEquals(123, $unserialized->createCommand('SELECT 123')->queryScalar()); } public function testGetDriverName() @@ -208,9 +212,9 @@ abstract class ConnectionTest extends DatabaseTestCase { /** @var Connection $connection */ $connection = $this->getConnection(true); - $connection->transaction(function(Connection $db) { + $connection->transaction(function (Connection $db) { $this->assertNotNull($db->transaction); - $db->transaction(function(Connection $db) { + $db->transaction(function (Connection $db) { $this->assertNotNull($db->transaction); $db->transaction->rollBack(); }); @@ -221,7 +225,7 @@ abstract class ConnectionTest extends DatabaseTestCase public function testEnableQueryLog() { $connection = $this->getConnection(); - foreach(['qlog1', 'qlog2', 'qlog3', 'qlog4'] as $table) { + foreach (['qlog1', 'qlog2', 'qlog3', 'qlog4'] as $table) { if ($connection->getTableSchema($table, true) !== null) { $connection->createCommand()->dropTable($table)->execute(); } @@ -317,7 +321,7 @@ abstract class ConnectionTest extends DatabaseTestCase try { $connection->createCommand('INSERT INTO qlog1(a) VALUES(:a);', [':a' => 1])->execute(); } catch (\yii\db\Exception $e) { - $this->assertContains('INSERT INTO qlog1(a) VALUES(1);', $e->getMessage(), 'Exception message should contain raw SQL query: ' . (string)$e); + $this->assertContains('INSERT INTO qlog1(a) VALUES(1);', $e->getMessage(), 'Exception message should contain raw SQL query: ' . (string) $e); $thrown = true; } $this->assertTrue($thrown, 'An exception should have been thrown by the command.'); @@ -326,7 +330,7 @@ abstract class ConnectionTest extends DatabaseTestCase try { $connection->createCommand('SELECT * FROM qlog1 WHERE id=:a ORDER BY nonexistingcolumn;', [':a' => 1])->queryAll(); } catch (\yii\db\Exception $e) { - $this->assertContains('SELECT * FROM qlog1 WHERE id=1 ORDER BY nonexistingcolumn;', $e->getMessage(), 'Exception message should contain raw SQL query: ' . (string)$e); + $this->assertContains('SELECT * FROM qlog1 WHERE id=1 ORDER BY nonexistingcolumn;', $e->getMessage(), 'Exception message should contain raw SQL query: ' . (string) $e); $thrown = true; } $this->assertTrue($thrown, 'An exception should have been thrown by the command.'); diff --git a/tests/framework/db/DatabaseTestCase.php b/tests/framework/db/DatabaseTestCase.php index 7d6de14..eb8e935 100644 --- a/tests/framework/db/DatabaseTestCase.php +++ b/tests/framework/db/DatabaseTestCase.php @@ -1,4 +1,9 @@ database = $databases[$this->driverName]; - $pdo_database = 'pdo_'.$this->driverName; + $pdo_database = 'pdo_' . $this->driverName; if ($this->driverName === 'oci') { $pdo_database = 'oci8'; } if (!extension_loaded('pdo') || !extension_loaded($pdo_database)) { - $this->markTestSkipped('pdo and '.$pdo_database.' extension are required.'); + $this->markTestSkipped('pdo and ' . $pdo_database . ' extension are required.'); } $this->mockApplication(); } @@ -66,7 +71,7 @@ abstract class DatabaseTestCase extends TestCase try { $this->_db = $this->prepareDatabase($config, $fixture, $open); } catch (\Exception $e) { - $this->markTestSkipped("Something wrong when preparing database: " . $e->getMessage()); + $this->markTestSkipped('Something wrong when preparing database: ' . $e->getMessage()); } return $this->_db; } diff --git a/tests/framework/db/QueryBuilderTest.php b/tests/framework/db/QueryBuilderTest.php index 34d6b06..464b8f2 100644 --- a/tests/framework/db/QueryBuilderTest.php +++ b/tests/framework/db/QueryBuilderTest.php @@ -1,18 +1,23 @@ primaryKey()->first(), [ - 'mysql' => "int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST", + 'mysql' => 'int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST', 'postgres' => 'serial NOT NULL PRIMARY KEY', 'oci' => 'NUMBER(10) NOT NULL PRIMARY KEY', 'sqlsrv' => 'int IDENTITY PRIMARY KEY', - 'cubrid' => "int NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST", + 'cubrid' => 'int NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST', ], ], [ - Schema::TYPE_INTEGER . " FIRST", + Schema::TYPE_INTEGER . ' FIRST', $this->integer()->first(), [ - 'mysql' => "int(11) FIRST", + 'mysql' => 'int(11) FIRST', 'postgres' => 'integer', - 'oci' => "NUMBER(10)", + 'oci' => 'NUMBER(10)', 'sqlsrv' => 'int', - 'cubrid' => "int FIRST", + 'cubrid' => 'int FIRST', ], ], [ @@ -966,14 +971,14 @@ abstract class QueryBuilderTest extends DatabaseTestCase ], ], [ - Schema::TYPE_INTEGER . " NOT NULL FIRST", + Schema::TYPE_INTEGER . ' NOT NULL FIRST', $this->integer()->append('NOT NULL')->first(), [ - 'mysql' => "int(11) NOT NULL FIRST", + 'mysql' => 'int(11) NOT NULL FIRST', 'postgres' => 'integer NOT NULL', - 'oci' => "NUMBER(10) NOT NULL", + 'oci' => 'NUMBER(10) NOT NULL', 'sqlsrv' => 'int NOT NULL', - 'cubrid' => "int NOT NULL FIRST", + 'cubrid' => 'int NOT NULL FIRST', ], ], [ @@ -993,8 +998,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase if (array_key_exists($this->driverName, $item[2])) { $item[2] = $item[2][$this->driverName]; $items[$i] = $item; - } - else { + } else { unset($items[$i]); } } @@ -1007,7 +1011,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase $qb = $this->getQueryBuilder(); foreach ($this->columnTypes() as $item) { - list ($column, $builder, $expected) = $item; + list($column, $builder, $expected) = $item; $expectedColumnSchemaBuilder = isset($item[3]) ? $item[3] : $column; $this->assertEquals($expected, $qb->getColumnType($column)); @@ -1025,7 +1029,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase $columns = []; $i = 0; foreach ($this->columnTypes() as $item) { - list ($column, $builder, $expected) = $item; + list($column, $builder, $expected) = $item; if (!(strncmp($column, Schema::TYPE_PK, 2) === 0 || strncmp($column, Schema::TYPE_UPK, 3) === 0 || strncmp($column, Schema::TYPE_BIGPK, 5) === 0 || @@ -1043,52 +1047,52 @@ abstract class QueryBuilderTest extends DatabaseTestCase { $conditions = [ // empty values - [ ['like', 'name', []], '0=1', [] ], - [ ['not like', 'name', []], '', [] ], - [ ['or like', 'name', []], '0=1', [] ], - [ ['or not like', 'name', []], '', [] ], + [['like', 'name', []], '0=1', []], + [['not like', 'name', []], '', []], + [['or like', 'name', []], '0=1', []], + [['or not like', 'name', []], '', []], // not - [ ['not', 'name'], 'NOT (name)', [] ], + [['not', 'name'], 'NOT (name)', []], // and - [ ['and', 'id=1', 'id=2'], '(id=1) AND (id=2)', [] ], - [ ['and', 'type=1', ['or', 'id=1', 'id=2']], '(type=1) AND ((id=1) OR (id=2))', [] ], - [ ['and', 'id=1', new Expression('id=:qp0', [':qp0' => 2])], '(id=1) AND (id=:qp0)', [':qp0' => 2] ], + [['and', 'id=1', 'id=2'], '(id=1) AND (id=2)', []], + [['and', 'type=1', ['or', 'id=1', 'id=2']], '(type=1) AND ((id=1) OR (id=2))', []], + [['and', 'id=1', new Expression('id=:qp0', [':qp0' => 2])], '(id=1) AND (id=:qp0)', [':qp0' => 2]], // or - [ ['or', 'id=1', 'id=2'], '(id=1) OR (id=2)', [] ], - [ ['or', 'type=1', ['or', 'id=1', 'id=2']], '(type=1) OR ((id=1) OR (id=2))', [] ], - [ ['or', 'type=1', new Expression('id=:qp0', [':qp0' => 1])], '(type=1) OR (id=:qp0)', [':qp0' => 1] ], + [['or', 'id=1', 'id=2'], '(id=1) OR (id=2)', []], + [['or', 'type=1', ['or', 'id=1', 'id=2']], '(type=1) OR ((id=1) OR (id=2))', []], + [['or', 'type=1', new Expression('id=:qp0', [':qp0' => 1])], '(type=1) OR (id=:qp0)', [':qp0' => 1]], // between - [ ['between', 'id', 1, 10], '[[id]] BETWEEN :qp0 AND :qp1', [':qp0' => 1, ':qp1' => 10] ], - [ ['not between', 'id', 1, 10], '[[id]] NOT BETWEEN :qp0 AND :qp1', [':qp0' => 1, ':qp1' => 10] ], - [ ['between', 'date', new Expression('(NOW() - INTERVAL 1 MONTH)'), new Expression('NOW()')], '[[date]] BETWEEN (NOW() - INTERVAL 1 MONTH) AND NOW()', [] ], - [ ['between', 'date', new Expression('(NOW() - INTERVAL 1 MONTH)'), 123], '[[date]] BETWEEN (NOW() - INTERVAL 1 MONTH) AND :qp0', [':qp0' => 123] ], - [ ['not between', 'date', new Expression('(NOW() - INTERVAL 1 MONTH)'), new Expression('NOW()')], '[[date]] NOT BETWEEN (NOW() - INTERVAL 1 MONTH) AND NOW()', [] ], - [ ['not between', 'date', new Expression('(NOW() - INTERVAL 1 MONTH)'), 123], '[[date]] NOT BETWEEN (NOW() - INTERVAL 1 MONTH) AND :qp0', [':qp0' => 123] ], + [['between', 'id', 1, 10], '[[id]] BETWEEN :qp0 AND :qp1', [':qp0' => 1, ':qp1' => 10]], + [['not between', 'id', 1, 10], '[[id]] NOT BETWEEN :qp0 AND :qp1', [':qp0' => 1, ':qp1' => 10]], + [['between', 'date', new Expression('(NOW() - INTERVAL 1 MONTH)'), new Expression('NOW()')], '[[date]] BETWEEN (NOW() - INTERVAL 1 MONTH) AND NOW()', []], + [['between', 'date', new Expression('(NOW() - INTERVAL 1 MONTH)'), 123], '[[date]] BETWEEN (NOW() - INTERVAL 1 MONTH) AND :qp0', [':qp0' => 123]], + [['not between', 'date', new Expression('(NOW() - INTERVAL 1 MONTH)'), new Expression('NOW()')], '[[date]] NOT BETWEEN (NOW() - INTERVAL 1 MONTH) AND NOW()', []], + [['not between', 'date', new Expression('(NOW() - INTERVAL 1 MONTH)'), 123], '[[date]] NOT BETWEEN (NOW() - INTERVAL 1 MONTH) AND :qp0', [':qp0' => 123]], // in - [ ['in', 'id', [1, 2, 3]], '[[id]] IN (:qp0, :qp1, :qp2)', [':qp0' => 1, ':qp1' => 2, ':qp2' => 3] ], - [ ['not in', 'id', [1, 2, 3]], '[[id]] NOT IN (:qp0, :qp1, :qp2)', [':qp0' => 1, ':qp1' => 2, ':qp2' => 3] ], - [ ['in', 'id', (new Query())->select('id')->from('users')->where(['active' => 1])], '[[id]] IN (SELECT [[id]] FROM [[users]] WHERE [[active]]=:qp0)', [':qp0' => 1] ], - [ ['not in', 'id', (new Query())->select('id')->from('users')->where(['active' => 1])], '[[id]] NOT IN (SELECT [[id]] FROM [[users]] WHERE [[active]]=:qp0)', [':qp0' => 1] ], - - [ ['in', 'id', 1], '[[id]]=:qp0', [':qp0' => 1] ], - [ ['in', 'id', [1]], '[[id]]=:qp0', [':qp0' => 1] ], - [ ['in', 'id', new TraversableObject([1])], '[[id]]=:qp0', [':qp0' => 1] ], + [['in', 'id', [1, 2, 3]], '[[id]] IN (:qp0, :qp1, :qp2)', [':qp0' => 1, ':qp1' => 2, ':qp2' => 3]], + [['not in', 'id', [1, 2, 3]], '[[id]] NOT IN (:qp0, :qp1, :qp2)', [':qp0' => 1, ':qp1' => 2, ':qp2' => 3]], + [['in', 'id', (new Query())->select('id')->from('users')->where(['active' => 1])], '[[id]] IN (SELECT [[id]] FROM [[users]] WHERE [[active]]=:qp0)', [':qp0' => 1]], + [['not in', 'id', (new Query())->select('id')->from('users')->where(['active' => 1])], '[[id]] NOT IN (SELECT [[id]] FROM [[users]] WHERE [[active]]=:qp0)', [':qp0' => 1]], + + [['in', 'id', 1], '[[id]]=:qp0', [':qp0' => 1]], + [['in', 'id', [1]], '[[id]]=:qp0', [':qp0' => 1]], + [['in', 'id', new TraversableObject([1])], '[[id]]=:qp0', [':qp0' => 1]], 'composite in' => [ - ['in', ['id', 'name'], [['id' =>1, 'name' => 'oy']]], + ['in', ['id', 'name'], [['id' => 1, 'name' => 'oy']]], '([[id]], [[name]]) IN ((:qp0, :qp1))', - [':qp0' => 1, ':qp1' => 'oy'] + [':qp0' => 1, ':qp1' => 'oy'], ], // in using array objects. - [ ['id' => new TraversableObject([1, 2])], '[[id]] IN (:qp0, :qp1)', [':qp0' => 1, ':qp1' => 2] ], + [['id' => new TraversableObject([1, 2])], '[[id]] IN (:qp0, :qp1)', [':qp0' => 1, ':qp1' => 2]], - [ ['in', 'id', new TraversableObject([1, 2, 3])], '[[id]] IN (:qp0, :qp1, :qp2)', [':qp0' => 1, ':qp1' => 2, ':qp2' => 3] ], + [['in', 'id', new TraversableObject([1, 2, 3])], '[[id]] IN (:qp0, :qp1, :qp2)', [':qp0' => 1, ':qp1' => 2, ':qp2' => 3]], 'composite in using array objects' => [ ['in', new TraversableObject(['id', 'name']), new TraversableObject([ @@ -1096,51 +1100,48 @@ abstract class QueryBuilderTest extends DatabaseTestCase ['id' => 2, 'name' => 'yo'], ])], '([[id]], [[name]]) IN ((:qp0, :qp1), (:qp2, :qp3))', - [':qp0' => 1, ':qp1' => 'oy', ':qp2' => 2, ':qp3' => 'yo'] + [':qp0' => 1, ':qp1' => 'oy', ':qp2' => 2, ':qp3' => 'yo'], ], // exists - [ ['exists', (new Query())->select('id')->from('users')->where(['active' => 1])], 'EXISTS (SELECT [[id]] FROM [[users]] WHERE [[active]]=:qp0)', [':qp0' => 1] ], - [ ['not exists', (new Query())->select('id')->from('users')->where(['active' => 1])], 'NOT EXISTS (SELECT [[id]] FROM [[users]] WHERE [[active]]=:qp0)', [':qp0' => 1] ], + [['exists', (new Query())->select('id')->from('users')->where(['active' => 1])], 'EXISTS (SELECT [[id]] FROM [[users]] WHERE [[active]]=:qp0)', [':qp0' => 1]], + [['not exists', (new Query())->select('id')->from('users')->where(['active' => 1])], 'NOT EXISTS (SELECT [[id]] FROM [[users]] WHERE [[active]]=:qp0)', [':qp0' => 1]], // simple conditions - [ ['=', 'a', 'b'], '[[a]] = :qp0', [':qp0' => 'b'] ], - [ ['>', 'a', 1], '[[a]] > :qp0', [':qp0' => 1] ], - [ ['>=', 'a', 'b'], '[[a]] >= :qp0', [':qp0' => 'b'] ], - [ ['<', 'a', 2], '[[a]] < :qp0', [':qp0' => 2] ], - [ ['<=', 'a', 'b'], '[[a]] <= :qp0', [':qp0' => 'b'] ], - [ ['<>', 'a', 3], '[[a]] <> :qp0', [':qp0' => 3] ], - [ ['!=', 'a', 'b'], '[[a]] != :qp0', [':qp0' => 'b'] ], - [ ['>=', 'date', new Expression('DATE_SUB(NOW(), INTERVAL 1 MONTH)')], '[[date]] >= DATE_SUB(NOW(), INTERVAL 1 MONTH)', [] ], - [ ['>=', 'date', new Expression('DATE_SUB(NOW(), INTERVAL :month MONTH)', [':month' => 2])], '[[date]] >= DATE_SUB(NOW(), INTERVAL :month MONTH)', [':month' => 2] ], - [ ['=', 'date', (new Query())->select('max(date)')->from('test')->where(['id' => 5])], '[[date]] = (SELECT max(date) FROM [[test]] WHERE [[id]]=:qp0)', [':qp0' => 5] ], + [['=', 'a', 'b'], '[[a]] = :qp0', [':qp0' => 'b']], + [['>', 'a', 1], '[[a]] > :qp0', [':qp0' => 1]], + [['>=', 'a', 'b'], '[[a]] >= :qp0', [':qp0' => 'b']], + [['<', 'a', 2], '[[a]] < :qp0', [':qp0' => 2]], + [['<=', 'a', 'b'], '[[a]] <= :qp0', [':qp0' => 'b']], + [['<>', 'a', 3], '[[a]] <> :qp0', [':qp0' => 3]], + [['!=', 'a', 'b'], '[[a]] != :qp0', [':qp0' => 'b']], + [['>=', 'date', new Expression('DATE_SUB(NOW(), INTERVAL 1 MONTH)')], '[[date]] >= DATE_SUB(NOW(), INTERVAL 1 MONTH)', []], + [['>=', 'date', new Expression('DATE_SUB(NOW(), INTERVAL :month MONTH)', [':month' => 2])], '[[date]] >= DATE_SUB(NOW(), INTERVAL :month MONTH)', [':month' => 2]], + [['=', 'date', (new Query())->select('max(date)')->from('test')->where(['id' => 5])], '[[date]] = (SELECT max(date) FROM [[test]] WHERE [[id]]=:qp0)', [':qp0' => 5]], // hash condition - [ ['a' => 1, 'b' => 2], '([[a]]=:qp0) AND ([[b]]=:qp1)', [':qp0' => 1, ':qp1' => 2] ], - [ ['a' => new Expression('CONCAT(col1, col2)'), 'b' => 2], '([[a]]=CONCAT(col1, col2)) AND ([[b]]=:qp0)', [':qp0' => 2] ], + [['a' => 1, 'b' => 2], '([[a]]=:qp0) AND ([[b]]=:qp1)', [':qp0' => 1, ':qp1' => 2]], + [['a' => new Expression('CONCAT(col1, col2)'), 'b' => 2], '([[a]]=CONCAT(col1, col2)) AND ([[b]]=:qp0)', [':qp0' => 2]], // direct conditions - [ 'a = CONCAT(col1, col2)', 'a = CONCAT(col1, col2)', [] ], - [ new Expression('a = CONCAT(col1, :param1)', ['param1' => 'value1']), 'a = CONCAT(col1, :param1)', ['param1' => 'value1'] ], - - - + ['a = CONCAT(col1, col2)', 'a = CONCAT(col1, col2)', []], + [new Expression('a = CONCAT(col1, :param1)', ['param1' => 'value1']), 'a = CONCAT(col1, :param1)', ['param1' => 'value1']], ]; switch ($this->driverName) { case 'sqlsrv': case 'sqlite': $conditions = array_merge($conditions, [ - [ ['in', ['id', 'name'], [['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']]], '(([[id]] = :qp0 AND [[name]] = :qp1) OR ([[id]] = :qp2 AND [[name]] = :qp3))', [':qp0' => 1, ':qp1' => 'foo', ':qp2' => 2, ':qp3' => 'bar'] ], - [ ['not in', ['id', 'name'], [['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']]], '(([[id]] != :qp0 OR [[name]] != :qp1) AND ([[id]] != :qp2 OR [[name]] != :qp3))', [':qp0' => 1, ':qp1' => 'foo', ':qp2' => 2, ':qp3' => 'bar'] ], + [['in', ['id', 'name'], [['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']]], '(([[id]] = :qp0 AND [[name]] = :qp1) OR ([[id]] = :qp2 AND [[name]] = :qp3))', [':qp0' => 1, ':qp1' => 'foo', ':qp2' => 2, ':qp3' => 'bar']], + [['not in', ['id', 'name'], [['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']]], '(([[id]] != :qp0 OR [[name]] != :qp1) AND ([[id]] != :qp2 OR [[name]] != :qp3))', [':qp0' => 1, ':qp1' => 'foo', ':qp2' => 2, ':qp3' => 'bar']], //[ ['in', ['id', 'name'], (new Query())->select(['id', 'name'])->from('users')->where(['active' => 1])], 'EXISTS (SELECT 1 FROM (SELECT [[id]], [[name]] FROM [[users]] WHERE [[active]]=:qp0) AS a WHERE a.[[id]] = [[id AND a.]]name[[ = ]]name`)', [':qp0' => 1] ], //[ ['not in', ['id', 'name'], (new Query())->select(['id', 'name'])->from('users')->where(['active' => 1])], 'NOT EXISTS (SELECT 1 FROM (SELECT [[id]], [[name]] FROM [[users]] WHERE [[active]]=:qp0) AS a WHERE a.[[id]] = [[id]] AND a.[[name = ]]name`)', [':qp0' => 1] ], ]); break; default: $conditions = array_merge($conditions, [ - [ ['in', ['id', 'name'], [['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']]], '([[id]], [[name]]) IN ((:qp0, :qp1), (:qp2, :qp3))', [':qp0' => 1, ':qp1' => 'foo', ':qp2' => 2, ':qp3' => 'bar'] ], - [ ['not in', ['id', 'name'], [['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']]], '([[id]], [[name]]) NOT IN ((:qp0, :qp1), (:qp2, :qp3))', [':qp0' => 1, ':qp1' => 'foo', ':qp2' => 2, ':qp3' => 'bar'] ], - [ ['in', ['id', 'name'], (new Query())->select(['id', 'name'])->from('users')->where(['active' => 1])], '([[id]], [[name]]) IN (SELECT [[id]], [[name]] FROM [[users]] WHERE [[active]]=:qp0)', [':qp0' => 1] ], - [ ['not in', ['id', 'name'], (new Query())->select(['id', 'name'])->from('users')->where(['active' => 1])], '([[id]], [[name]]) NOT IN (SELECT [[id]], [[name]] FROM [[users]] WHERE [[active]]=:qp0)', [':qp0' => 1] ], + [['in', ['id', 'name'], [['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']]], '([[id]], [[name]]) IN ((:qp0, :qp1), (:qp2, :qp3))', [':qp0' => 1, ':qp1' => 'foo', ':qp2' => 2, ':qp3' => 'bar']], + [['not in', ['id', 'name'], [['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']]], '([[id]], [[name]]) NOT IN ((:qp0, :qp1), (:qp2, :qp3))', [':qp0' => 1, ':qp1' => 'foo', ':qp2' => 2, ':qp3' => 'bar']], + [['in', ['id', 'name'], (new Query())->select(['id', 'name'])->from('users')->where(['active' => 1])], '([[id]], [[name]]) IN (SELECT [[id]], [[name]] FROM [[users]] WHERE [[active]]=:qp0)', [':qp0' => 1]], + [['not in', ['id', 'name'], (new Query())->select(['id', 'name'])->from('users')->where(['active' => 1])], '([[id]], [[name]]) NOT IN (SELECT [[id]], [[name]] FROM [[users]] WHERE [[active]]=:qp0)', [':qp0' => 1]], ]); break; } @@ -1156,41 +1157,41 @@ abstract class QueryBuilderTest extends DatabaseTestCase { $conditions = [ // like - [ ['like', 'name', []], '', [] ], - [ ['not like', 'name', []], '', [] ], - [ ['or like', 'name', []], '', [] ], - [ ['or not like', 'name', []], '', [] ], + [['like', 'name', []], '', []], + [['not like', 'name', []], '', []], + [['or like', 'name', []], '', []], + [['or not like', 'name', []], '', []], // not - [ ['not', ''], '', [] ], + [['not', ''], '', []], // and - [ ['and', '', ''], '', [] ], - [ ['and', '', 'id=2'], '(id=2)', [] ], - [ ['and', 'id=1', ''], '(id=1)', [] ], - [ ['and', 'type=1', ['or', '', 'id=2']], '(type=1) AND ((id=2))', [] ], + [['and', '', ''], '', []], + [['and', '', 'id=2'], '(id=2)', []], + [['and', 'id=1', ''], '(id=1)', []], + [['and', 'type=1', ['or', '', 'id=2']], '(type=1) AND ((id=2))', []], // or - [ ['or', 'id=1', ''], '(id=1)', [] ], - [ ['or', 'type=1', ['or', '', 'id=2']], '(type=1) OR ((id=2))', [] ], + [['or', 'id=1', ''], '(id=1)', []], + [['or', 'type=1', ['or', '', 'id=2']], '(type=1) OR ((id=2))', []], // between - [ ['between', 'id', 1, null], '', [] ], - [ ['not between', 'id', null, 10], '', [] ], + [['between', 'id', 1, null], '', []], + [['not between', 'id', null, 10], '', []], // in - [ ['in', 'id', []], '', [] ], - [ ['not in', 'id', []], '', [] ], + [['in', 'id', []], '', []], + [['not in', 'id', []], '', []], // simple conditions - [ ['=', 'a', ''], '', [] ], - [ ['>', 'a', ''], '', [] ], - [ ['>=', 'a', ''], '', [] ], - [ ['<', 'a', ''], '', [] ], - [ ['<=', 'a', ''], '', [] ], - [ ['<>', 'a', ''], '', [] ], - [ ['!=', 'a', ''], '', [] ], + [['=', 'a', ''], '', []], + [['>', 'a', ''], '', []], + [['>=', 'a', ''], '', []], + [['<', 'a', ''], '', []], + [['<=', 'a', ''], '', []], + [['<>', 'a', ''], '', []], + [['!=', 'a', ''], '', []], ]; // adjust dbms specific escaping @@ -1225,7 +1226,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase public function testAddDropPrimaryKey() { $tableName = 'constraints'; - $pkeyName = $tableName . "_pkey"; + $pkeyName = $tableName . '_pkey'; // ADD $qb = $this->getQueryBuilder(); @@ -1255,8 +1256,8 @@ abstract class QueryBuilderTest extends DatabaseTestCase public function existsParamsProvider() { return [ - ['exists', $this->replaceQuotes("SELECT [[id]] FROM [[TotalExample]] [[t]] WHERE EXISTS (SELECT [[1]] FROM [[Website]] [[w]])")], - ['not exists', $this->replaceQuotes("SELECT [[id]] FROM [[TotalExample]] [[t]] WHERE NOT EXISTS (SELECT [[1]] FROM [[Website]] [[w]])")] + ['exists', $this->replaceQuotes('SELECT [[id]] FROM [[TotalExample]] [[t]] WHERE EXISTS (SELECT [[1]] FROM [[Website]] [[w]])')], + ['not exists', $this->replaceQuotes('SELECT [[id]] FROM [[TotalExample]] [[t]] WHERE NOT EXISTS (SELECT [[1]] FROM [[Website]] [[w]])')], ]; } @@ -1285,9 +1286,9 @@ abstract class QueryBuilderTest extends DatabaseTestCase public function testBuildWhereExistsWithParameters() { $expectedQuerySql = $this->replaceQuotes( - "SELECT [[id]] FROM [[TotalExample]] [[t]] WHERE (EXISTS (SELECT [[1]] FROM [[Website]] [[w]] WHERE (w.id = t.website_id) AND (w.merchant_id = :merchant_id))) AND (t.some_column = :some_value)" + 'SELECT [[id]] FROM [[TotalExample]] [[t]] WHERE (EXISTS (SELECT [[1]] FROM [[Website]] [[w]] WHERE (w.id = t.website_id) AND (w.merchant_id = :merchant_id))) AND (t.some_column = :some_value)' ); - $expectedQueryParams = [':some_value' => "asd", ':merchant_id' => 6]; + $expectedQueryParams = [':some_value' => 'asd', ':merchant_id' => 6]; $subQuery = new Query(); $subQuery->select('1') @@ -1299,7 +1300,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase $query->select('id') ->from('TotalExample t') ->where(['exists', $subQuery]) - ->andWhere('t.some_column = :some_value', [':some_value' => "asd"]); + ->andWhere('t.some_column = :some_value', [':some_value' => 'asd']); list($actualQuerySql, $queryParams) = $this->getQueryBuilder()->build($query); $this->assertEquals($expectedQuerySql, $actualQuerySql); @@ -1309,7 +1310,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase public function testBuildWhereExistsWithArrayParameters() { $expectedQuerySql = $this->replaceQuotes( - "SELECT [[id]] FROM [[TotalExample]] [[t]] WHERE (EXISTS (SELECT [[1]] FROM [[Website]] [[w]] WHERE (w.id = t.website_id) AND (([[w]].[[merchant_id]]=:qp0) AND ([[w]].[[user_id]]=:qp1)))) AND ([[t]].[[some_column]]=:qp2)" + 'SELECT [[id]] FROM [[TotalExample]] [[t]] WHERE (EXISTS (SELECT [[1]] FROM [[Website]] [[w]] WHERE (w.id = t.website_id) AND (([[w]].[[merchant_id]]=:qp0) AND ([[w]].[[user_id]]=:qp1)))) AND ([[t]].[[some_column]]=:qp2)' ); $expectedQueryParams = [':qp0' => 6, ':qp1' => 210, ':qp2' => 'asd']; @@ -1323,7 +1324,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase $query->select('id') ->from('TotalExample t') ->where(['exists', $subQuery]) - ->andWhere(['t.some_column' => "asd"]); + ->andWhere(['t.some_column' => 'asd']); list($actualQuerySql, $queryParams) = $this->getQueryBuilder()->build($query); $this->assertEquals($expectedQuerySql, $actualQuerySql); @@ -1337,7 +1338,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase public function testBuildUnion() { $expectedQuerySql = $this->replaceQuotes( - "(SELECT [[id]] FROM [[TotalExample]] [[t1]] WHERE (w > 0) AND (x < 2)) UNION ( SELECT [[id]] FROM [[TotalTotalExample]] [[t2]] WHERE w > 5 ) UNION ALL ( SELECT [[id]] FROM [[TotalTotalExample]] [[t3]] WHERE w = 3 )" + '(SELECT [[id]] FROM [[TotalExample]] [[t1]] WHERE (w > 0) AND (x < 2)) UNION ( SELECT [[id]] FROM [[TotalTotalExample]] [[t2]] WHERE w > 5 ) UNION ALL ( SELECT [[id]] FROM [[TotalTotalExample]] [[t3]] WHERE w = 3 )' ); $query = new Query(); $secondQuery = new Query(); @@ -1352,7 +1353,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->from('TotalExample t1') ->where(['and', 'w > 0', 'x < 2']) ->union($secondQuery) - ->union($thirdQuery, TRUE); + ->union($thirdQuery, true); list($actualQuerySql, $queryParams) = $this->getQueryBuilder()->build($query); $this->assertEquals($expectedQuerySql, $actualQuerySql); $this->assertEquals([], $queryParams); @@ -1368,7 +1369,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->select('*') ->from('accounts') ->addSelect(['operations_count' => $subquery]); - list ($sql, $params) = $this->getQueryBuilder()->build($query); + list($sql, $params) = $this->getQueryBuilder()->build($query); $expected = $this->replaceQuotes('SELECT *, (SELECT COUNT(*) FROM [[operations]] WHERE account_id = accounts.id) AS [[operations_count]] FROM [[accounts]]'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); @@ -1386,7 +1387,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase new Expression($this->replaceQuotes("case t.Status_Id when 1 then 'Acknowledge' when 2 then 'No Action' else 'Unknown Action' END as [[Next Action]]")), ]) ->from('tablename'); - list ($sql, $params) = $this->getQueryBuilder()->build($query); + list($sql, $params) = $this->getQueryBuilder()->build($query); $expected = $this->replaceQuotes( 'SELECT [[t]].[[id]] AS [[ID]], [[gsm]].[[username]] AS [[GSM]], [[part]].[[Part]], [[t]].[[Part_Cost]] AS [[Part Cost]], st_x(location::geometry) as lon,' . ' case t.Status_Id when 1 then \'Acknowledge\' when 2 then \'No Action\' else \'Unknown Action\' END as [[Next Action]] FROM [[tablename]]'); @@ -1397,31 +1398,30 @@ abstract class QueryBuilderTest extends DatabaseTestCase public function testSelectExpression() { $query = (new Query()) - ->select(new Expression("1 AS ab")) + ->select(new Expression('1 AS ab')) ->from('tablename'); - list ($sql, $params) = $this->getQueryBuilder()->build($query); - $expected = $this->replaceQuotes("SELECT 1 AS ab FROM [[tablename]]"); + list($sql, $params) = $this->getQueryBuilder()->build($query); + $expected = $this->replaceQuotes('SELECT 1 AS ab FROM [[tablename]]'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); $query = (new Query()) - ->select(new Expression("1 AS ab")) - ->addSelect(new Expression("2 AS cd")) - ->addSelect(['ef' => new Expression("3")]) + ->select(new Expression('1 AS ab')) + ->addSelect(new Expression('2 AS cd')) + ->addSelect(['ef' => new Expression('3')]) ->from('tablename'); - list ($sql, $params) = $this->getQueryBuilder()->build($query); - $expected = $this->replaceQuotes("SELECT 1 AS ab, 2 AS cd, 3 AS [[ef]] FROM [[tablename]]"); + list($sql, $params) = $this->getQueryBuilder()->build($query); + $expected = $this->replaceQuotes('SELECT 1 AS ab, 2 AS cd, 3 AS [[ef]] FROM [[tablename]]'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); $query = (new Query()) - ->select(new Expression("SUBSTR(name, 0, :len)", [':len' => 4])) + ->select(new Expression('SUBSTR(name, 0, :len)', [':len' => 4])) ->from('tablename'); - list ($sql, $params) = $this->getQueryBuilder()->build($query); - $expected = $this->replaceQuotes("SELECT SUBSTR(name, 0, :len) FROM [[tablename]]"); + list($sql, $params) = $this->getQueryBuilder()->build($query); + $expected = $this->replaceQuotes('SELECT SUBSTR(name, 0, :len) FROM [[tablename]]'); $this->assertEquals($expected, $sql); $this->assertEquals([':len' => 4], $params); - } /** @@ -1429,16 +1429,16 @@ abstract class QueryBuilderTest extends DatabaseTestCase */ public function testFromIndexHint() { - $query = (new Query)->from([new Expression('{{%user}} USE INDEX (primary)')]); - list ($sql, $params) = $this->getQueryBuilder()->build($query); + $query = (new Query())->from([new Expression('{{%user}} USE INDEX (primary)')]); + list($sql, $params) = $this->getQueryBuilder()->build($query); $expected = $this->replaceQuotes('SELECT * FROM {{%user}} USE INDEX (primary)'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); - $query = (new Query) + $query = (new Query()) ->from([new Expression('{{user}} {{t}} FORCE INDEX (primary) IGNORE INDEX FOR ORDER BY (i1)')]) ->leftJoin(['p' => 'profile'], 'user.id = profile.user_id USE INDEX (i2)'); - list ($sql, $params) = $this->getQueryBuilder()->build($query); + list($sql, $params) = $this->getQueryBuilder()->build($query); $expected = $this->replaceQuotes('SELECT * FROM {{user}} {{t}} FORCE INDEX (primary) IGNORE INDEX FOR ORDER BY (i1) LEFT JOIN [[profile]] [[p]] ON user.id = profile.user_id USE INDEX (i2)'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); @@ -1447,19 +1447,19 @@ abstract class QueryBuilderTest extends DatabaseTestCase public function testFromSubquery() { // query subquery - $subquery = (new Query)->from('user')->where('account_id = accounts.id'); - $query = (new Query)->from(['activeusers' => $subquery]); + $subquery = (new Query())->from('user')->where('account_id = accounts.id'); + $query = (new Query())->from(['activeusers' => $subquery]); // SELECT * FROM (SELECT * FROM [[user]] WHERE [[active]] = 1) [[activeusers]]; - list ($sql, $params) = $this->getQueryBuilder()->build($query); + list($sql, $params) = $this->getQueryBuilder()->build($query); $expected = $this->replaceQuotes('SELECT * FROM (SELECT * FROM [[user]] WHERE account_id = accounts.id) [[activeusers]]'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); // query subquery with params - $subquery = (new Query)->from('user')->where('account_id = :id', ['id' => 1]); - $query = (new Query)->from(['activeusers' => $subquery])->where('abc = :abc', ['abc' => 'abc']); + $subquery = (new Query())->from('user')->where('account_id = :id', ['id' => 1]); + $query = (new Query())->from(['activeusers' => $subquery])->where('abc = :abc', ['abc' => 'abc']); // SELECT * FROM (SELECT * FROM [[user]] WHERE [[active]] = 1) [[activeusers]]; - list ($sql, $params) = $this->getQueryBuilder()->build($query); + list($sql, $params) = $this->getQueryBuilder()->build($query); $expected = $this->replaceQuotes('SELECT * FROM (SELECT * FROM [[user]] WHERE account_id = :id) [[activeusers]] WHERE abc = :abc'); $this->assertEquals($expected, $sql); $this->assertEquals([ @@ -1468,10 +1468,10 @@ abstract class QueryBuilderTest extends DatabaseTestCase ], $params); // simple subquery - $subquery = "(SELECT * FROM user WHERE account_id = accounts.id)"; - $query = (new Query)->from(['activeusers' => $subquery]); + $subquery = '(SELECT * FROM user WHERE account_id = accounts.id)'; + $query = (new Query())->from(['activeusers' => $subquery]); // SELECT * FROM (SELECT * FROM [[user]] WHERE [[active]] = 1) [[activeusers]]; - list ($sql, $params) = $this->getQueryBuilder()->build($query); + list($sql, $params) = $this->getQueryBuilder()->build($query); $expected = $this->replaceQuotes('SELECT * FROM (SELECT * FROM user WHERE account_id = accounts.id) [[activeusers]]'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); @@ -1484,7 +1484,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->select('*') ->from('operations') ->orderBy('name ASC, date DESC'); - list ($sql, $params) = $this->getQueryBuilder()->build($query); + list($sql, $params) = $this->getQueryBuilder()->build($query); $expected = $this->replaceQuotes('SELECT * FROM [[operations]] ORDER BY [[name]], [[date]] DESC'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); @@ -1494,7 +1494,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->select('*') ->from('operations') ->orderBy(['name' => SORT_ASC, 'date' => SORT_DESC]); - list ($sql, $params) = $this->getQueryBuilder()->build($query); + list($sql, $params) = $this->getQueryBuilder()->build($query); $expected = $this->replaceQuotes('SELECT * FROM [[operations]] ORDER BY [[name]], [[date]] DESC'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); @@ -1505,7 +1505,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->from('operations') ->where('account_id = accounts.id') ->orderBy(new Expression('SUBSTR(name, 3, 4) DESC, x ASC')); - list ($sql, $params) = $this->getQueryBuilder()->build($query); + list($sql, $params) = $this->getQueryBuilder()->build($query); $expected = $this->replaceQuotes('SELECT * FROM [[operations]] WHERE account_id = accounts.id ORDER BY SUBSTR(name, 3, 4) DESC, x ASC'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); @@ -1515,7 +1515,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->select('*') ->from('operations') ->orderBy(new Expression('SUBSTR(name, 3, :to) DESC, x ASC', [':to' => 4])); - list ($sql, $params) = $this->getQueryBuilder()->build($query); + list($sql, $params) = $this->getQueryBuilder()->build($query); $expected = $this->replaceQuotes('SELECT * FROM [[operations]] ORDER BY SUBSTR(name, 3, :to) DESC, x ASC'); $this->assertEquals($expected, $sql); $this->assertEquals([':to' => 4], $params); @@ -1528,7 +1528,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->select('*') ->from('operations') ->groupBy('name, date'); - list ($sql, $params) = $this->getQueryBuilder()->build($query); + list($sql, $params) = $this->getQueryBuilder()->build($query); $expected = $this->replaceQuotes('SELECT * FROM [[operations]] GROUP BY [[name]], [[date]]'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); @@ -1538,7 +1538,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->select('*') ->from('operations') ->groupBy(['name', 'date']); - list ($sql, $params) = $this->getQueryBuilder()->build($query); + list($sql, $params) = $this->getQueryBuilder()->build($query); $expected = $this->replaceQuotes('SELECT * FROM [[operations]] GROUP BY [[name]], [[date]]'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); @@ -1549,7 +1549,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->from('operations') ->where('account_id = accounts.id') ->groupBy(new Expression('SUBSTR(name, 0, 1), x')); - list ($sql, $params) = $this->getQueryBuilder()->build($query); + list($sql, $params) = $this->getQueryBuilder()->build($query); $expected = $this->replaceQuotes('SELECT * FROM [[operations]] WHERE account_id = accounts.id GROUP BY SUBSTR(name, 0, 1), x'); $this->assertEquals($expected, $sql); $this->assertEmpty($params); @@ -1559,7 +1559,7 @@ abstract class QueryBuilderTest extends DatabaseTestCase ->select('*') ->from('operations') ->groupBy(new Expression('SUBSTR(name, 0, :to), x', [':to' => 4])); - list ($sql, $params) = $this->getQueryBuilder()->build($query); + list($sql, $params) = $this->getQueryBuilder()->build($query); $expected = $this->replaceQuotes('SELECT * FROM [[operations]] GROUP BY SUBSTR(name, 0, :to), x'); $this->assertEquals($expected, $sql); $this->assertEquals([':to' => 4], $params); @@ -1578,43 +1578,43 @@ abstract class QueryBuilderTest extends DatabaseTestCase 'customer', ['email', 'name', 'address'], [['test@example.com', 'silverfire', 'Kyiv {{city}}, Ukraine']], - $this->replaceQuotes("INSERT INTO [[customer]] ([[email]], [[name]], [[address]]) VALUES ('test@example.com', 'silverfire', 'Kyiv {{city}}, Ukraine')") + $this->replaceQuotes("INSERT INTO [[customer]] ([[email]], [[name]], [[address]]) VALUES ('test@example.com', 'silverfire', 'Kyiv {{city}}, Ukraine')"), ], 'escape-danger-chars' => [ 'customer', ['address'], [["SQL-danger chars are escaped: '); --"]], - 'expected' => $this->replaceQuotes("INSERT INTO [[customer]] ([[address]]) VALUES ('SQL-danger chars are escaped: \'); --')") + 'expected' => $this->replaceQuotes("INSERT INTO [[customer]] ([[address]]) VALUES ('SQL-danger chars are escaped: \'); --')"), ], [ 'customer', ['address'], [], - '' + '', ], [ 'customer', [], - [["no columns passed"]], - $this->replaceQuotes("INSERT INTO [[customer]] () VALUES ('no columns passed')") + [['no columns passed']], + $this->replaceQuotes("INSERT INTO [[customer]] () VALUES ('no columns passed')"), ], 'bool-false, bool2-null' => [ 'type', ['bool_col', 'bool_col2'], [[false, null]], - 'expected' => $this->replaceQuotes("INSERT INTO [[type]] ([[bool_col]], [[bool_col2]]) VALUES (0, NULL)") + 'expected' => $this->replaceQuotes('INSERT INTO [[type]] ([[bool_col]], [[bool_col2]]) VALUES (0, NULL)'), ], [ '{{%type}}', ['{{%type}}.[[float_col]]', '[[time]]'], [[null, new Expression('now()')]], - "INSERT INTO {{%type}} ({{%type}}.[[float_col]], [[time]]) VALUES (NULL, now())" + 'INSERT INTO {{%type}} ({{%type}}.[[float_col]], [[time]]) VALUES (NULL, now())', ], 'bool-false, time-now()' => [ '{{%type}}', ['{{%type}}.[[bool_col]]', '[[time]]'], [[false, new Expression('now()')]], - 'expected' => "INSERT INTO {{%type}} ({{%type}}.[[bool_col]], [[time]]) VALUES (0, now())" + 'expected' => 'INSERT INTO {{%type}} ({{%type}}.[[bool_col]], [[time]]) VALUES (0, now())', ], ]; } @@ -1675,26 +1675,26 @@ abstract class QueryBuilderTest extends DatabaseTestCase { $conditions = [ // simple like - [ ['like', 'name', 'foo%'], '[[name]] LIKE :qp0', [':qp0' => '%foo\%%'] ], - [ ['not like', 'name', 'foo%'], '[[name]] NOT LIKE :qp0', [':qp0' => '%foo\%%'] ], - [ ['or like', 'name', 'foo%'], '[[name]] LIKE :qp0', [':qp0' => '%foo\%%'] ], - [ ['or not like', 'name', 'foo%'], '[[name]] NOT LIKE :qp0', [':qp0' => '%foo\%%'] ], + [['like', 'name', 'foo%'], '[[name]] LIKE :qp0', [':qp0' => '%foo\%%']], + [['not like', 'name', 'foo%'], '[[name]] NOT LIKE :qp0', [':qp0' => '%foo\%%']], + [['or like', 'name', 'foo%'], '[[name]] LIKE :qp0', [':qp0' => '%foo\%%']], + [['or not like', 'name', 'foo%'], '[[name]] NOT LIKE :qp0', [':qp0' => '%foo\%%']], // like for many values - [ ['like', 'name', ['foo%', '[abc]']], '[[name]] LIKE :qp0 AND [[name]] LIKE :qp1', [':qp0' => '%foo\%%', ':qp1' => '%[abc]%'] ], - [ ['not like', 'name', ['foo%', '[abc]']], '[[name]] NOT LIKE :qp0 AND [[name]] NOT LIKE :qp1', [':qp0' => '%foo\%%', ':qp1' => '%[abc]%'] ], - [ ['or like', 'name', ['foo%', '[abc]']], '[[name]] LIKE :qp0 OR [[name]] LIKE :qp1', [':qp0' => '%foo\%%', ':qp1' => '%[abc]%'] ], - [ ['or not like', 'name', ['foo%', '[abc]']], '[[name]] NOT LIKE :qp0 OR [[name]] NOT LIKE :qp1', [':qp0' => '%foo\%%', ':qp1' => '%[abc]%'] ], + [['like', 'name', ['foo%', '[abc]']], '[[name]] LIKE :qp0 AND [[name]] LIKE :qp1', [':qp0' => '%foo\%%', ':qp1' => '%[abc]%']], + [['not like', 'name', ['foo%', '[abc]']], '[[name]] NOT LIKE :qp0 AND [[name]] NOT LIKE :qp1', [':qp0' => '%foo\%%', ':qp1' => '%[abc]%']], + [['or like', 'name', ['foo%', '[abc]']], '[[name]] LIKE :qp0 OR [[name]] LIKE :qp1', [':qp0' => '%foo\%%', ':qp1' => '%[abc]%']], + [['or not like', 'name', ['foo%', '[abc]']], '[[name]] NOT LIKE :qp0 OR [[name]] NOT LIKE :qp1', [':qp0' => '%foo\%%', ':qp1' => '%[abc]%']], // like with Expression - [ ['like', 'name', new Expression('CONCAT("test", name, "%")')], '[[name]] LIKE CONCAT("test", name, "%")', [] ], - [ ['not like', 'name', new Expression('CONCAT("test", name, "%")')], '[[name]] NOT LIKE CONCAT("test", name, "%")', [] ], - [ ['or like', 'name', new Expression('CONCAT("test", name, "%")')], '[[name]] LIKE CONCAT("test", name, "%")', [] ], - [ ['or not like', 'name', new Expression('CONCAT("test", name, "%")')], '[[name]] NOT LIKE CONCAT("test", name, "%")', [] ], - [ ['like', 'name', [new Expression('CONCAT("test", name, "%")'), '\ab_c']], '[[name]] LIKE CONCAT("test", name, "%") AND [[name]] LIKE :qp0', [':qp0' => '%\\\ab\_c%'] ], - [ ['not like', 'name', [new Expression('CONCAT("test", name, "%")'), '\ab_c']], '[[name]] NOT LIKE CONCAT("test", name, "%") AND [[name]] NOT LIKE :qp0', [':qp0' => '%\\\ab\_c%'] ], - [ ['or like', 'name', [new Expression('CONCAT("test", name, "%")'), '\ab_c']], '[[name]] LIKE CONCAT("test", name, "%") OR [[name]] LIKE :qp0', [':qp0' => '%\\\ab\_c%'] ], - [ ['or not like', 'name', [new Expression('CONCAT("test", name, "%")'), '\ab_c']], '[[name]] NOT LIKE CONCAT("test", name, "%") OR [[name]] NOT LIKE :qp0', [':qp0' => '%\\\ab\_c%'] ], + [['like', 'name', new Expression('CONCAT("test", name, "%")')], '[[name]] LIKE CONCAT("test", name, "%")', []], + [['not like', 'name', new Expression('CONCAT("test", name, "%")')], '[[name]] NOT LIKE CONCAT("test", name, "%")', []], + [['or like', 'name', new Expression('CONCAT("test", name, "%")')], '[[name]] LIKE CONCAT("test", name, "%")', []], + [['or not like', 'name', new Expression('CONCAT("test", name, "%")')], '[[name]] NOT LIKE CONCAT("test", name, "%")', []], + [['like', 'name', [new Expression('CONCAT("test", name, "%")'), '\ab_c']], '[[name]] LIKE CONCAT("test", name, "%") AND [[name]] LIKE :qp0', [':qp0' => '%\\\ab\_c%']], + [['not like', 'name', [new Expression('CONCAT("test", name, "%")'), '\ab_c']], '[[name]] NOT LIKE CONCAT("test", name, "%") AND [[name]] NOT LIKE :qp0', [':qp0' => '%\\\ab\_c%']], + [['or like', 'name', [new Expression('CONCAT("test", name, "%")'), '\ab_c']], '[[name]] LIKE CONCAT("test", name, "%") OR [[name]] LIKE :qp0', [':qp0' => '%\\\ab\_c%']], + [['or not like', 'name', [new Expression('CONCAT("test", name, "%")'), '\ab_c']], '[[name]] NOT LIKE CONCAT("test", name, "%") OR [[name]] NOT LIKE :qp0', [':qp0' => '%\\\ab\_c%']], ]; // adjust dbms specific escaping diff --git a/tests/framework/db/QueryTest.php b/tests/framework/db/QueryTest.php index 50d038a..b225487 100644 --- a/tests/framework/db/QueryTest.php +++ b/tests/framework/db/QueryTest.php @@ -1,4 +1,9 @@ select('*'); $this->assertEquals(['*'], $query->select); $this->assertNull($query->distinct); $this->assertEquals(null, $query->selectOption); - $query = new Query; + $query = new Query(); $query->select('id, name', 'something')->distinct(true); $this->assertEquals(['id', 'name'], $query->select); $this->assertTrue($query->distinct); @@ -36,14 +41,14 @@ abstract class QueryTest extends DatabaseTestCase public function testFrom() { - $query = new Query; + $query = new Query(); $query->from('user'); $this->assertEquals(['user'], $query->from); } public function testWhere() { - $query = new Query; + $query = new Query(); $query->where('id = :id', [':id' => 1]); $this->assertEquals('id = :id', $query->where); $this->assertEquals([':id' => 1], $query->params); @@ -59,7 +64,7 @@ abstract class QueryTest extends DatabaseTestCase public function testFilterWhereWithHashFormat() { - $query = new Query; + $query = new Query(); $query->filterWhere([ 'id' => 0, 'title' => ' ', @@ -76,7 +81,7 @@ abstract class QueryTest extends DatabaseTestCase public function testFilterWhereWithOperatorFormat() { - $query = new Query; + $query = new Query(); $condition = ['like', 'name', 'Alex']; $query->filterWhere($condition); $this->assertEquals($condition, $query->where); @@ -111,7 +116,7 @@ abstract class QueryTest extends DatabaseTestCase public function testFilterHavingWithHashFormat() { - $query = new Query; + $query = new Query(); $query->filterHaving([ 'id' => 0, 'title' => ' ', @@ -128,7 +133,7 @@ abstract class QueryTest extends DatabaseTestCase public function testFilterHavingWithOperatorFormat() { - $query = new Query; + $query = new Query(); $condition = ['like', 'name', 'Alex']; $query->filterHaving($condition); $this->assertEquals($condition, $query->having); @@ -174,7 +179,7 @@ abstract class QueryTest extends DatabaseTestCase public function testGroup() { - $query = new Query; + $query = new Query(); $query->groupBy('team'); $this->assertEquals(['team'], $query->groupBy); @@ -187,7 +192,7 @@ abstract class QueryTest extends DatabaseTestCase public function testHaving() { - $query = new Query; + $query = new Query(); $query->having('id = :id', [':id' => 1]); $this->assertEquals('id = :id', $query->having); $this->assertEquals([':id' => 1], $query->params); @@ -203,7 +208,7 @@ abstract class QueryTest extends DatabaseTestCase public function testOrder() { - $query = new Query; + $query = new Query(); $query->orderBy('team'); $this->assertEquals(['team' => SORT_ASC], $query->orderBy); @@ -230,7 +235,7 @@ abstract class QueryTest extends DatabaseTestCase public function testLimitOffset() { - $query = new Query; + $query = new Query(); $query->limit(10)->offset(5); $this->assertEquals(10, $query->limit); $this->assertEquals(5, $query->offset); @@ -255,7 +260,7 @@ abstract class QueryTest extends DatabaseTestCase public function testUnion() { $connection = $this->getConnection(); - $query = new Query; + $query = new Query(); $query->select(['id', 'name']) ->from('item') ->limit(2) @@ -274,10 +279,10 @@ abstract class QueryTest extends DatabaseTestCase { $db = $this->getConnection(); - $result = (new Query)->from('customer')->where(['status' => 2])->one($db); + $result = (new Query())->from('customer')->where(['status' => 2])->one($db); $this->assertEquals('user3', $result['name']); - $result = (new Query)->from('customer')->where(['status' => 3])->one($db); + $result = (new Query())->from('customer')->where(['status' => 3])->one($db); $this->assertFalse($result); } @@ -285,21 +290,21 @@ abstract class QueryTest extends DatabaseTestCase { $db = $this->getConnection(); - $result = (new Query)->from('customer')->where(['status' => 2])->exists($db); + $result = (new Query())->from('customer')->where(['status' => 2])->exists($db); $this->assertTrue($result); - $result = (new Query)->from('customer')->where(['status' => 3])->exists($db); + $result = (new Query())->from('customer')->where(['status' => 3])->exists($db); $this->assertFalse($result); } public function testColumn() { $db = $this->getConnection(); - $result = (new Query)->select('name')->from('customer')->orderBy(['id' => SORT_DESC])->column($db); + $result = (new Query())->select('name')->from('customer')->orderBy(['id' => SORT_DESC])->column($db); $this->assertEquals(['user3', 'user2', 'user1'], $result); // https://github.com/yiisoft/yii2/issues/7515 - $result = (new Query)->from('customer') + $result = (new Query())->from('customer') ->select('name') ->orderBy(['id' => SORT_DESC]) ->indexBy('id') @@ -307,7 +312,7 @@ abstract class QueryTest extends DatabaseTestCase $this->assertEquals([3 => 'user3', 2 => 'user2', 1 => 'user1'], $result); // https://github.com/yiisoft/yii2/issues/12649 - $result = (new Query)->from('customer') + $result = (new Query())->from('customer') ->select(['name', 'id']) ->orderBy(['id' => SORT_DESC]) ->indexBy(function ($row) { @@ -316,7 +321,7 @@ abstract class QueryTest extends DatabaseTestCase ->column($db); $this->assertEquals([6 => 'user3', 4 => 'user2', 2 => 'user1'], $result); - $result = (new Query)->from('customer') + $result = (new Query())->from('customer') ->select(['name']) ->indexBy('name') ->orderBy(['id' => SORT_DESC]) @@ -328,20 +333,20 @@ abstract class QueryTest extends DatabaseTestCase { $db = $this->getConnection(); - $count = (new Query)->from('customer')->count('*', $db); + $count = (new Query())->from('customer')->count('*', $db); $this->assertEquals(3, $count); - $count = (new Query)->from('customer')->where(['status' => 2])->count('*', $db); + $count = (new Query())->from('customer')->where(['status' => 2])->count('*', $db); $this->assertEquals(1, $count); - $count = (new Query)->select('[[status]], COUNT([[id]])')->from('customer')->groupBy('status')->count('*', $db); + $count = (new Query())->select('[[status]], COUNT([[id]])')->from('customer')->groupBy('status')->count('*', $db); $this->assertEquals(2, $count); // testing that orderBy() should be ignored here as it does not affect the count anyway. - $count = (new Query)->from('customer')->orderBy('status')->count('*', $db); + $count = (new Query())->from('customer')->orderBy('status')->count('*', $db); $this->assertEquals(3, $count); - - $count = (new Query)->from('customer')->orderBy('id')->limit(1)->count('*', $db); + + $count = (new Query())->from('customer')->orderBy('id')->limit(1)->count('*', $db); $this->assertEquals(3, $count); } @@ -351,7 +356,7 @@ abstract class QueryTest extends DatabaseTestCase */ public function testAndFilterCompare() { - $query = new Query; + $query = new Query(); $result = $query->andFilterCompare('name', null); $this->assertInstanceOf('yii\db\Query', $result); @@ -390,7 +395,7 @@ abstract class QueryTest extends DatabaseTestCase $db = $this->getConnection(); - $count = (new Query)->from('customer')->having(['status' => 2])->count('*', $db); + $count = (new Query())->from('customer')->having(['status' => 2])->count('*', $db); $this->assertEquals(1, $count); } @@ -496,11 +501,11 @@ abstract class QueryTest extends DatabaseTestCase $tableName = 'like_test'; $columnName = 'col'; - if($db->getSchema()->getTableSchema($tableName) !== null){ + if ($db->getSchema()->getTableSchema($tableName) !== null) { $db->createCommand()->dropTable($tableName)->execute(); } $db->createCommand()->createTable($tableName, [ - $columnName => $db->getSchema()->createColumnSchemaBuilder(Schema::TYPE_STRING, 64) + $columnName => $db->getSchema()->createColumnSchemaBuilder(Schema::TYPE_STRING, 64), ])->execute(); $db->createCommand()->batchInsert($tableName, ['col'], [ ['test0'], diff --git a/tests/framework/db/SchemaTest.php b/tests/framework/db/SchemaTest.php index f80d7ae..871529c 100644 --- a/tests/framework/db/SchemaTest.php +++ b/tests/framework/db/SchemaTest.php @@ -1,4 +1,9 @@ 'string', 'allowNull' => true, 'autoIncrement' => false, - 'enumValues' => ['a', 'B','c,D'], + 'enumValues' => ['a', 'B', 'c,D'], 'size' => null, 'precision' => null, 'scale' => null, @@ -376,7 +381,7 @@ abstract class SchemaTest extends DatabaseTestCase $this->assertSame($expected['precision'], $column->precision, "precision of column $name does not match."); $this->assertSame($expected['scale'], $column->scale, "scale of column $name does not match."); if (is_object($expected['defaultValue'])) { - $this->assertTrue(is_object($column->defaultValue), "defaultValue of column $name is expected to be an object but it is not."); + $this->assertInternalType('object', $column->defaultValue, "defaultValue of column $name is expected to be an object but it is not."); $this->assertEquals((string) $expected['defaultValue'], (string) $column->defaultValue, "defaultValue of column $name does not match."); } else { $this->assertSame($expected['defaultValue'], $column->defaultValue, "defaultValue of column $name does not match."); diff --git a/tests/framework/db/UnqueryableQueryMock.php b/tests/framework/db/UnqueryableQueryMock.php index 87172be..e95d275 100644 --- a/tests/framework/db/UnqueryableQueryMock.php +++ b/tests/framework/db/UnqueryableQueryMock.php @@ -1,4 +1,9 @@ createCommand($sql); - $this->assertEquals("SELECT [id], [t].[name] FROM [customer] t", $command->sql); + $this->assertEquals('SELECT [id], [t].[name] FROM [customer] t', $command->sql); } public function testPrepareCancel() diff --git a/tests/framework/db/mssql/ConnectionTest.php b/tests/framework/db/mssql/ConnectionTest.php index 3658b4c..7e7024d 100644 --- a/tests/framework/db/mssql/ConnectionTest.php +++ b/tests/framework/db/mssql/ConnectionTest.php @@ -1,4 +1,9 @@ primaryKey()->after('col_before'), - 'int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY AFTER `col_before`' + 'int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY AFTER `col_before`', ], [ Schema::TYPE_PK . ' FIRST', $this->primaryKey()->first(), - 'int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST' + 'int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST', ], [ Schema::TYPE_PK . ' FIRST', $this->primaryKey()->first()->after('col_before'), - 'int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST' + 'int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST', ], [ Schema::TYPE_PK . '(8) AFTER `col_before`', $this->primaryKey(8)->after('col_before'), - 'int(8) NOT NULL AUTO_INCREMENT PRIMARY KEY AFTER `col_before`' + 'int(8) NOT NULL AUTO_INCREMENT PRIMARY KEY AFTER `col_before`', ], [ Schema::TYPE_PK . '(8) FIRST', $this->primaryKey(8)->first(), - 'int(8) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST' + 'int(8) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST', ], [ Schema::TYPE_PK . '(8) FIRST', $this->primaryKey(8)->first()->after('col_before'), - 'int(8) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST' + 'int(8) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST', ], [ Schema::TYPE_PK . " COMMENT 'test' AFTER `col_before`", $this->primaryKey()->comment('test')->after('col_before'), - "int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'test' AFTER `col_before`" + "int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'test' AFTER `col_before`", ], ]); } diff --git a/tests/framework/db/mysql/QueryTest.php b/tests/framework/db/mysql/QueryTest.php index 1e9018c..f225398 100644 --- a/tests/framework/db/mysql/QueryTest.php +++ b/tests/framework/db/mysql/QueryTest.php @@ -1,6 +1,12 @@ getConnection(); - $query = (new Query)->from([new Expression('{{%customer}} USE INDEX (primary)')]); + $query = (new Query())->from([new Expression('{{%customer}} USE INDEX (primary)')]); $row = $query->one($db); $this->assertArrayHasKey('id', $row); $this->assertArrayHasKey('name', $row); diff --git a/tests/framework/db/mysql/SchemaTest.php b/tests/framework/db/mysql/SchemaTest.php index b103632..5671904 100644 --- a/tests/framework/db/mysql/SchemaTest.php +++ b/tests/framework/db/mysql/SchemaTest.php @@ -1,4 +1,9 @@ getLogContentAndDelete(); if ($errors) { $this->fail( - join('; ', $errors) + implode('; ', $errors) . ($logContent ? ". Shared children log:\n$logContent" : '') ); } @@ -137,16 +142,16 @@ class DeadLockTest extends \yiiunit\framework\db\mysql\ConnectionTest private function childrenSelectAndAccidentUpdate($pidSecond) { try { - $this->log("child 1: connect"); + $this->log('child 1: connect'); /** @var Connection $first */ $first = $this->getConnection(false, false); - $this->log("child 1: delete"); + $this->log('child 1: delete'); $first->createCommand() ->delete('{{customer}}', ['id' => 97]) ->execute(); - $this->log("child 1: insert"); + $this->log('child 1: insert'); // insert test row $first->createCommand() ->insert('{{customer}}', [ @@ -157,15 +162,15 @@ class DeadLockTest extends \yiiunit\framework\db\mysql\ConnectionTest ]) ->execute(); - $this->log("child 1: transaction"); + $this->log('child 1: transaction'); $first->transaction(function (Connection $first) use ($pidSecond) { $first->transaction(function (Connection $first) use ($pidSecond) { - $this->log("child 1: select"); + $this->log('child 1: select'); // SELECT with shared lock - $first->createCommand("SELECT id FROM {{customer}} WHERE id = 97 LOCK IN SHARE MODE") + $first->createCommand('SELECT id FROM {{customer}} WHERE id = 97 LOCK IN SHARE MODE') ->execute(); - $this->log("child 1: send signal to child 2"); + $this->log('child 1: send signal to child 2'); // let child to continue if (!posix_kill($pidSecond, SIGUSR1)) { throw new \RuntimeException('Cannot send signal'); @@ -176,16 +181,16 @@ class DeadLockTest extends \yiiunit\framework\db\mysql\ConnectionTest // delay to let child hit the lock sleep(2); - $this->log("child 1: update"); + $this->log('child 1: update'); // now do the 3rd update for deadlock $first->createCommand() ->update('{{customer}}', ['name' => 'first'], ['id' => 97]) ->execute(); - $this->log("child 1: commit"); + $this->log('child 1: commit'); }); }, Transaction::REPEATABLE_READ); } catch (Exception $e) { - list ($sqlError, $driverError, $driverMessage) = $e->errorInfo; + list($sqlError, $driverError, $driverMessage) = $e->errorInfo; // Deadlock found when trying to get lock; try restarting transaction if ('40001' === $sqlError && 1213 === $driverError) { return self::CHILD_EXIT_CODE_DEADLOCK; @@ -193,13 +198,13 @@ class DeadLockTest extends \yiiunit\framework\db\mysql\ConnectionTest $this->log("child 1: ! sql error $sqlError: $driverError: $driverMessage"); return 1; } catch (\Exception $e) { - $this->log("child 1: ! exit <<" . get_class($e) . " #" . $e->getCode() . ": " . $e->getMessage() . "\n" . $e->getTraceAsString() . ">>"); + $this->log('child 1: ! exit <<' . get_class($e) . ' #' . $e->getCode() . ': ' . $e->getMessage() . "\n" . $e->getTraceAsString() . '>>'); return 1; } catch (\Throwable $e) { - $this->log("child 1: ! exit <<" . get_class($e) . " #" . $e->getCode() . ": " . $e->getMessage() . "\n" . $e->getTraceAsString() . ">>"); + $this->log('child 1: ! exit <<' . get_class($e) . ' #' . $e->getCode() . ': ' . $e->getMessage() . "\n" . $e->getTraceAsString() . '>>'); return 1; } - $this->log("child 1: exit"); + $this->log('child 1: exit'); return 0; } @@ -215,37 +220,37 @@ class DeadLockTest extends \yiiunit\framework\db\mysql\ConnectionTest { // install no-op signal handler to prevent termination if (!pcntl_signal(SIGUSR1, function () {}, false)) { - $this->log("child 2: cannot install signal handler"); + $this->log('child 2: cannot install signal handler'); return 1; } try { // at first, parent should do 1st select - $this->log("child 2: wait signal from child 1"); + $this->log('child 2: wait signal from child 1'); if (pcntl_sigtimedwait([SIGUSR1], $info, 10) <= 0) { - $this->log("child 2: wait timeout exceeded"); + $this->log('child 2: wait timeout exceeded'); return 1; } - $this->log("child 2: connect"); + $this->log('child 2: connect'); /** @var Connection $second */ $second = $this->getConnection(true, false); $second->open(); //sleep(1); - $this->log("child 2: transaction"); + $this->log('child 2: transaction'); $second->transaction(function (Connection $second) { $second->transaction(function (Connection $second) { - $this->log("child 2: update"); + $this->log('child 2: update'); // do the 2nd update $second->createCommand() ->update('{{customer}}', ['name' => 'second'], ['id' => 97]) ->execute(); - $this->log("child 2: commit"); + $this->log('child 2: commit'); }); }, Transaction::REPEATABLE_READ); } catch (Exception $e) { - list ($sqlError, $driverError, $driverMessage) = $e->errorInfo; + list($sqlError, $driverError, $driverMessage) = $e->errorInfo; // Deadlock found when trying to get lock; try restarting transaction if ('40001' === $sqlError && 1213 === $driverError) { return self::CHILD_EXIT_CODE_DEADLOCK; @@ -253,13 +258,13 @@ class DeadLockTest extends \yiiunit\framework\db\mysql\ConnectionTest $this->log("child 2: ! sql error $sqlError: $driverError: $driverMessage"); return 1; } catch (\Exception $e) { - $this->log("child 2: ! exit <<" . get_class($e) . " #" . $e->getCode() . ": " . $e->getMessage() . "\n" . $e->getTraceAsString() . ">>"); + $this->log('child 2: ! exit <<' . get_class($e) . ' #' . $e->getCode() . ': ' . $e->getMessage() . "\n" . $e->getTraceAsString() . '>>'); return 1; } catch (\Throwable $e) { - $this->log("child 2: ! exit <<" . get_class($e) . " #" . $e->getCode() . ": " . $e->getMessage() . "\n" . $e->getTraceAsString() . ">>"); + $this->log('child 2: ! exit <<' . get_class($e) . ' #' . $e->getCode() . ': ' . $e->getMessage() . "\n" . $e->getTraceAsString() . '>>'); return 1; } - $this->log("child 2: exit"); + $this->log('child 2: exit'); return 0; } diff --git a/tests/framework/db/oci/ActiveDataProviderTest.php b/tests/framework/db/oci/ActiveDataProviderTest.php index b08cfbb..7831afc 100644 --- a/tests/framework/db/oci/ActiveDataProviderTest.php +++ b/tests/framework/db/oci/ActiveDataProviderTest.php @@ -1,4 +1,9 @@ assertInstanceOf('yii\db\Connection', $unserialized); - $this->assertEquals(123, $unserialized->createCommand("SELECT 123 FROM DUAL")->queryScalar()); + $this->assertEquals(123, $unserialized->createCommand('SELECT 123 FROM DUAL')->queryScalar()); } public function testQuoteTableName() diff --git a/tests/framework/db/oci/ExistValidatorTest.php b/tests/framework/db/oci/ExistValidatorTest.php index ca18cfa..5c5c583 100644 --- a/tests/framework/db/oci/ExistValidatorTest.php +++ b/tests/framework/db/oci/ExistValidatorTest.php @@ -1,4 +1,9 @@ boolean()->notNull()->defaultValue(1), - 'NUMBER(1) DEFAULT 1 NOT NULL' + 'NUMBER(1) DEFAULT 1 NOT NULL', ], ]); } @@ -67,12 +72,12 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest $qb = $this->getQueryBuilder(); $expected = 'DROP SEQUENCE "item_SEQ";' - .'CREATE SEQUENCE "item_SEQ" START WITH 6 INCREMENT BY 1 NOMAXVALUE NOCACHE'; + . 'CREATE SEQUENCE "item_SEQ" START WITH 6 INCREMENT BY 1 NOMAXVALUE NOCACHE'; $sql = $qb->resetSequence('item'); $this->assertEquals($expected, $sql); $expected = 'DROP SEQUENCE "item_SEQ";' - .'CREATE SEQUENCE "item_SEQ" START WITH 4 INCREMENT BY 1 NOMAXVALUE NOCACHE'; + . 'CREATE SEQUENCE "item_SEQ" START WITH 4 INCREMENT BY 1 NOMAXVALUE NOCACHE'; $sql = $qb->resetSequence('item', 4); $this->assertEquals($expected, $sql); } @@ -97,10 +102,10 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest ' (' . '([[id]] IN (' . implode(', ', $this->generateSprintfSeries(':qp%d', 0, 999)) . '))' . ' OR ([[id]] IN (' . implode(', ', $this->generateSprintfSeries(':qp%d', 1000, 1999)) . '))' - . ' OR ([[id]] IN (' . implode(', ', $this->generateSprintfSeries(':qp%d', 2000, 2500)) .'))' + . ' OR ([[id]] IN (' . implode(', ', $this->generateSprintfSeries(':qp%d', 2000, 2500)) . '))' . ')', - array_flip($this->generateSprintfSeries(':qp%d', 0, 2500)) + array_flip($this->generateSprintfSeries(':qp%d', 0, 2500)), ], [ ['not in', 'id', range(0, 2500)], @@ -108,10 +113,10 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest '(' . '([[id]] NOT IN (' . implode(', ', $this->generateSprintfSeries(':qp%d', 0, 999)) . '))' . ' AND ([[id]] NOT IN (' . implode(', ', $this->generateSprintfSeries(':qp%d', 1000, 1999)) . '))' - . ' AND ([[id]] NOT IN (' . implode(', ', $this->generateSprintfSeries(':qp%d', 2000, 2500)) .'))' + . ' AND ([[id]] NOT IN (' . implode(', ', $this->generateSprintfSeries(':qp%d', 2000, 2500)) . '))' . ')', - array_flip($this->generateSprintfSeries(':qp%d', 0, 2500)) + array_flip($this->generateSprintfSeries(':qp%d', 0, 2500)), ], [ ['not in', 'id', new TraversableObject(range(0, 2500))], @@ -119,15 +124,16 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest '(' . '([[id]] NOT IN (' . implode(', ', $this->generateSprintfSeries(':qp%d', 0, 999)) . '))' . ' AND ([[id]] NOT IN (' . implode(', ', $this->generateSprintfSeries(':qp%d', 1000, 1999)) . '))' - . ' AND ([[id]] NOT IN (' . implode(', ', $this->generateSprintfSeries(':qp%d', 2000, 2500)) .'))' + . ' AND ([[id]] NOT IN (' . implode(', ', $this->generateSprintfSeries(':qp%d', 2000, 2500)) . '))' . ')', - array_flip($this->generateSprintfSeries(':qp%d', 0, 2500)) + array_flip($this->generateSprintfSeries(':qp%d', 0, 2500)), ], ]); } - protected function generateSprintfSeries ($pattern, $from, $to) { + protected function generateSprintfSeries($pattern, $from, $to) + { $items = []; for ($i = $from; $i <= $to; $i++) { $items[] = sprintf($pattern, $i); diff --git a/tests/framework/db/oci/QueryTest.php b/tests/framework/db/oci/QueryTest.php index 306e739..e2a2c82 100644 --- a/tests/framework/db/oci/QueryTest.php +++ b/tests/framework/db/oci/QueryTest.php @@ -1,4 +1,9 @@ getConnection(); - $result = (new Query)->from('customer')->where(['[[status]]' => 2])->one($db); + $result = (new Query())->from('customer')->where(['[[status]]' => 2])->one($db); $this->assertEquals('user3', $result['name']); - $result = (new Query)->from('customer')->where(['[[status]]' => 3])->one($db); + $result = (new Query())->from('customer')->where(['[[status]]' => 3])->one($db); $this->assertFalse($result); } } diff --git a/tests/framework/db/oci/SchemaTest.php b/tests/framework/db/oci/SchemaTest.php index 8198230..a65b0c3 100644 --- a/tests/framework/db/oci/SchemaTest.php +++ b/tests/framework/db/oci/SchemaTest.php @@ -1,10 +1,12 @@ getConnection(); $db->charset = 'utf8'; - $db->createCommand("DROP TABLE IF EXISTS bool_user;")->execute(); + $db->createCommand('DROP TABLE IF EXISTS bool_user;')->execute(); $db->createCommand()->createTable('bool_user', [ 'id' => Schema::TYPE_PK, 'username' => Schema::TYPE_STRING . ' NOT NULL', diff --git a/tests/framework/db/pgsql/BatchQueryResultTest.php b/tests/framework/db/pgsql/BatchQueryResultTest.php index 9261baa..e935611 100644 --- a/tests/framework/db/pgsql/BatchQueryResultTest.php +++ b/tests/framework/db/pgsql/BatchQueryResultTest.php @@ -1,4 +1,9 @@ assertTrue(is_object($this->getConnection(true))); + $this->assertInternalType('object', $this->getConnection(true)); } public function testQuoteValue() diff --git a/tests/framework/db/pgsql/ExistValidatorTest.php b/tests/framework/db/pgsql/ExistValidatorTest.php index 978b42a..0f13237 100644 --- a/tests/framework/db/pgsql/ExistValidatorTest.php +++ b/tests/framework/db/pgsql/ExistValidatorTest.php @@ -1,4 +1,9 @@ boolean()->notNull()->defaultValue(true), - 'boolean NOT NULL DEFAULT TRUE' + 'boolean NOT NULL DEFAULT TRUE', ], [ Schema::TYPE_CHAR . ' CHECK (value LIKE \'test%\')', $this->char()->check('value LIKE \'test%\''), - 'char(1) CHECK (value LIKE \'test%\')' + 'char(1) CHECK (value LIKE \'test%\')', ], [ Schema::TYPE_CHAR . '(6) CHECK (value LIKE \'test%\')', $this->char(6)->check('value LIKE \'test%\''), - 'char(6) CHECK (value LIKE \'test%\')' + 'char(6) CHECK (value LIKE \'test%\')', ], [ Schema::TYPE_CHAR . '(6)', $this->char(6)->unsigned(), - 'char(6)' + 'char(6)', ], [ Schema::TYPE_INTEGER . '(8)', $this->integer(8)->unsigned(), - 'integer' + 'integer', ], [ Schema::TYPE_TIMESTAMP . '(4)', $this->timestamp(4), - 'timestamp(4)' + 'timestamp(4)', ], ]); } @@ -55,22 +60,22 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest // http://www.postgresql.org/docs/8.3/static/functions-matching.html#FUNCTIONS-LIKE // empty values - [ ['ilike', 'name', []], '0=1', [] ], - [ ['not ilike', 'name', []], '', [] ], - [ ['or ilike', 'name', []], '0=1', [] ], - [ ['or not ilike', 'name', []], '', [] ], + [['ilike', 'name', []], '0=1', []], + [['not ilike', 'name', []], '', []], + [['or ilike', 'name', []], '0=1', []], + [['or not ilike', 'name', []], '', []], // simple ilike - [ ['ilike', 'name', 'heyho'], '"name" ILIKE :qp0', [':qp0' => '%heyho%'] ], - [ ['not ilike', 'name', 'heyho'], '"name" NOT ILIKE :qp0', [':qp0' => '%heyho%'] ], - [ ['or ilike', 'name', 'heyho'], '"name" ILIKE :qp0', [':qp0' => '%heyho%'] ], - [ ['or not ilike', 'name', 'heyho'], '"name" NOT ILIKE :qp0', [':qp0' => '%heyho%'] ], + [['ilike', 'name', 'heyho'], '"name" ILIKE :qp0', [':qp0' => '%heyho%']], + [['not ilike', 'name', 'heyho'], '"name" NOT ILIKE :qp0', [':qp0' => '%heyho%']], + [['or ilike', 'name', 'heyho'], '"name" ILIKE :qp0', [':qp0' => '%heyho%']], + [['or not ilike', 'name', 'heyho'], '"name" NOT ILIKE :qp0', [':qp0' => '%heyho%']], // ilike for many values - [ ['ilike', 'name', ['heyho', 'abc']], '"name" ILIKE :qp0 AND "name" ILIKE :qp1', [':qp0' => '%heyho%', ':qp1' => '%abc%'] ], - [ ['not ilike', 'name', ['heyho', 'abc']], '"name" NOT ILIKE :qp0 AND "name" NOT ILIKE :qp1', [':qp0' => '%heyho%', ':qp1' => '%abc%'] ], - [ ['or ilike', 'name', ['heyho', 'abc']], '"name" ILIKE :qp0 OR "name" ILIKE :qp1', [':qp0' => '%heyho%', ':qp1' => '%abc%'] ], - [ ['or not ilike', 'name', ['heyho', 'abc']], '"name" NOT ILIKE :qp0 OR "name" NOT ILIKE :qp1', [':qp0' => '%heyho%', ':qp1' => '%abc%'] ], + [['ilike', 'name', ['heyho', 'abc']], '"name" ILIKE :qp0 AND "name" ILIKE :qp1', [':qp0' => '%heyho%', ':qp1' => '%abc%']], + [['not ilike', 'name', ['heyho', 'abc']], '"name" NOT ILIKE :qp0 AND "name" NOT ILIKE :qp1', [':qp0' => '%heyho%', ':qp1' => '%abc%']], + [['or ilike', 'name', ['heyho', 'abc']], '"name" ILIKE :qp0 OR "name" ILIKE :qp1', [':qp0' => '%heyho%', ':qp1' => '%abc%']], + [['or not ilike', 'name', ['heyho', 'abc']], '"name" NOT ILIKE :qp0 OR "name" NOT ILIKE :qp1', [':qp0' => '%heyho%', ':qp1' => '%abc%']], ]); } @@ -103,7 +108,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest $sql = $qb->addCommentOnColumn('comment', 'text', 'This is my column.'); $this->assertEquals($this->replaceQuotes($expected), $sql); - $expected = "COMMENT ON COLUMN [[comment]].[[text]] IS NULL"; + $expected = 'COMMENT ON COLUMN [[comment]].[[text]] IS NULL'; $sql = $qb->dropCommentFromColumn('comment', 'text'); $this->assertEquals($this->replaceQuotes($expected), $sql); } @@ -116,7 +121,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest $sql = $qb->addCommentOnTable('comment', 'This is my table.'); $this->assertEquals($this->replaceQuotes($expected), $sql); - $expected = "COMMENT ON TABLE [[comment]] IS NULL"; + $expected = 'COMMENT ON TABLE [[comment]] IS NULL'; $sql = $qb->dropCommentFromTable('comment'); $this->assertEquals($this->replaceQuotes($expected), $sql); } @@ -127,7 +132,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest $data['escape-danger-chars']['expected'] = "INSERT INTO \"customer\" (\"address\") VALUES ('SQL-danger chars are escaped: ''); --')"; $data['bool-false, bool2-null']['expected'] = 'INSERT INTO "type" ("bool_col", "bool_col2") VALUES (FALSE, NULL)'; - $data['bool-false, time-now()']['expected'] = "INSERT INTO {{%type}} ({{%type}}.[[bool_col]], [[time]]) VALUES (FALSE, now())"; + $data['bool-false, time-now()']['expected'] = 'INSERT INTO {{%type}} ({{%type}}.[[bool_col]], [[time]]) VALUES (FALSE, now())'; return $data; } diff --git a/tests/framework/db/pgsql/QueryTest.php b/tests/framework/db/pgsql/QueryTest.php index bf3de41..61dc518 100644 --- a/tests/framework/db/pgsql/QueryTest.php +++ b/tests/framework/db/pgsql/QueryTest.php @@ -1,8 +1,12 @@ createCommand($sql); - $this->assertEquals("SELECT `id`, `t`.`name` FROM `customer` t", $command->sql); + $this->assertEquals('SELECT `id`, `t`.`name` FROM `customer` t', $command->sql); } } diff --git a/tests/framework/db/sqlite/ConnectionTest.php b/tests/framework/db/sqlite/ConnectionTest.php index 2f869bd..8a8e00f 100644 --- a/tests/framework/db/sqlite/ConnectionTest.php +++ b/tests/framework/db/sqlite/ConnectionTest.php @@ -1,4 +1,9 @@ assertNull($db->getMaster()); } - $this->assertNotEquals('test', $db->createCommand("SELECT description FROM profile WHERE id=1")->queryScalar()); + $this->assertNotEquals('test', $db->createCommand('SELECT description FROM profile WHERE id=1')->queryScalar()); $result = $db->useMaster(function (Connection $db) { - return $db->createCommand("SELECT description FROM profile WHERE id=1")->queryScalar(); + return $db->createCommand('SELECT description FROM profile WHERE id=1')->queryScalar(); }); $this->assertEquals('test', $result); @@ -106,7 +111,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest $hit_slaves = $hit_masters = []; - for ($i = $nodesCount * $retryPerNode; $i-- > 0; ) { + for ($i = $nodesCount * $retryPerNode; $i-- > 0;) { $db = $this->prepareMasterSlave($mastersCount, $slavesCount); $db->shuffleMasters = true; @@ -128,7 +133,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest $hit_slaves = $hit_masters = []; - for ($i = $nodesCount * $retryPerNode; $i-- > 0; ) { + for ($i = $nodesCount * $retryPerNode; $i-- > 0;) { $db = $this->prepareMasterSlave($mastersCount, $slavesCount); $db->shuffleMasters = false; @@ -193,7 +198,7 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest public function testAliasDbPath() { $config = [ - 'dsn' => "sqlite:@yiiunit/runtime/yii2aliastest.sq3", + 'dsn' => 'sqlite:@yiiunit/runtime/yii2aliastest.sq3', ]; $connection = new Connection($config); $connection->open(); @@ -207,5 +212,4 @@ class ConnectionTest extends \yiiunit\framework\db\ConnectionTest { // This test does not work on sqlite because preparing the failing query fails } - } diff --git a/tests/framework/db/sqlite/ExistValidatorTest.php b/tests/framework/db/sqlite/ExistValidatorTest.php index 840798f..8c8652a 100644 --- a/tests/framework/db/sqlite/ExistValidatorTest.php +++ b/tests/framework/db/sqlite/ExistValidatorTest.php @@ -1,4 +1,9 @@ primaryKey()->first()->after('col_before'), - 'integer PRIMARY KEY AUTOINCREMENT NOT NULL' + 'integer PRIMARY KEY AUTOINCREMENT NOT NULL', ], ]); } @@ -36,12 +41,12 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest ['id' => 2, 'name' => 'yo'], ])], '(([[id]] = :qp0 AND [[name]] = :qp1) OR ([[id]] = :qp2 AND [[name]] = :qp3))', - [':qp0' => 1, ':qp1' => 'oy', ':qp2' => 2, ':qp3' => 'yo'] + [':qp0' => 1, ':qp1' => 'oy', ':qp2' => 2, ':qp3' => 'yo'], ], 'composite in' => [ - ['in', ['id', 'name'], [['id' =>1, 'name' => 'oy']]], + ['in', ['id', 'name'], [['id' => 1, 'name' => 'oy']]], '(([[id]] = :qp0 AND [[name]] = :qp1))', - [':qp0' => 1, ':qp1' => 'oy'] + [':qp0' => 1, ':qp1' => 'oy'], ], ]); } @@ -81,7 +86,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest public function testRenameTable() { $sql = $this->getQueryBuilder()->renameTable('table_from', 'table_to'); - $this->assertEquals("ALTER TABLE `table_from` RENAME TO `table_to`", $sql); + $this->assertEquals('ALTER TABLE `table_from` RENAME TO `table_to`', $sql); } /** @@ -90,7 +95,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest public function testBuildUnion() { $expectedQuerySql = $this->replaceQuotes( - "SELECT `id` FROM `TotalExample` `t1` WHERE (w > 0) AND (x < 2) UNION SELECT `id` FROM `TotalTotalExample` `t2` WHERE w > 5 UNION ALL SELECT `id` FROM `TotalTotalExample` `t3` WHERE w = 3" + 'SELECT `id` FROM `TotalExample` `t1` WHERE (w > 0) AND (x < 2) UNION SELECT `id` FROM `TotalTotalExample` `t2` WHERE w > 5 UNION ALL SELECT `id` FROM `TotalTotalExample` `t3` WHERE w = 3' ); $query = new Query(); $secondQuery = new Query(); @@ -105,7 +110,7 @@ class QueryBuilderTest extends \yiiunit\framework\db\QueryBuilderTest ->from('TotalExample t1') ->where(['and', 'w > 0', 'x < 2']) ->union($secondQuery) - ->union($thirdQuery, TRUE); + ->union($thirdQuery, true); list($actualQuerySql, $queryParams) = $this->getQueryBuilder()->build($query); $this->assertEquals($expectedQuerySql, $actualQuerySql); $this->assertEquals([], $queryParams); diff --git a/tests/framework/db/sqlite/QueryTest.php b/tests/framework/db/sqlite/QueryTest.php index 37cb553..e5ee615 100644 --- a/tests/framework/db/sqlite/QueryTest.php +++ b/tests/framework/db/sqlite/QueryTest.php @@ -1,4 +1,10 @@ getConnection(); - $query = new Query; + $query = new Query(); $query->select(['id', 'name']) ->from('item') ->union( diff --git a/tests/framework/db/sqlite/SchemaTest.php b/tests/framework/db/sqlite/SchemaTest.php index 425fd66..f48518a 100644 --- a/tests/framework/db/sqlite/SchemaTest.php +++ b/tests/framework/db/sqlite/SchemaTest.php @@ -1,4 +1,9 @@ @@ -43,7 +42,7 @@ class ContainerTest extends TestCase $Qux = Qux::className(); // automatic wiring - $container = new Container; + $container = new Container(); $container->set($QuxInterface, $Qux); $foo = $container->get($Foo); $this->assertInstanceOf($Foo, $foo); @@ -53,7 +52,7 @@ class ContainerTest extends TestCase $this->assertNotSame($foo, $foo2); // full wiring - $container = new Container; + $container = new Container(); $container->set($QuxInterface, $Qux); $container->set($Bar); $container->set($Qux); @@ -64,9 +63,9 @@ class ContainerTest extends TestCase $this->assertInstanceOf($Qux, $foo->bar->qux); // wiring by closure - $container = new Container; + $container = new Container(); $container->set('foo', function () { - $qux = new Qux; + $qux = new Qux(); $bar = new Bar($qux); return new Foo($bar); }); @@ -76,7 +75,7 @@ class ContainerTest extends TestCase $this->assertInstanceOf($Qux, $foo->bar->qux); // wiring by closure which uses container - $container = new Container; + $container = new Container(); $container->set($QuxInterface, $Qux); $container->set('foo', function (Container $c, $params, $config) { return $c->get(Foo::className()); @@ -87,7 +86,7 @@ class ContainerTest extends TestCase $this->assertInstanceOf($Qux, $foo->bar->qux); // predefined constructor parameters - $container = new Container; + $container = new Container(); $container->set('foo', $Foo, [Instance::of('bar')]); $container->set('bar', $Bar, [Instance::of('qux')]); $container->set('qux', $Qux); @@ -97,14 +96,14 @@ class ContainerTest extends TestCase $this->assertInstanceOf($Qux, $foo->bar->qux); // wiring by closure - $container = new Container; - $container->set('qux', new Qux); + $container = new Container(); + $container->set('qux', new Qux()); $qux1 = $container->get('qux'); $qux2 = $container->get('qux'); $this->assertSame($qux1, $qux2); // config - $container = new Container; + $container = new Container(); $container->set('qux', $Qux); $qux = $container->get('qux', [], ['a' => 2]); $this->assertEquals(2, $qux->a); @@ -126,7 +125,7 @@ class ContainerTest extends TestCase 'class' => 'yiiunit\framework\di\stubs\Qux', 'a' => 'belongAppQux2', ], - ] + ], ]); Yii::$container->set('yiiunit\framework\di\stubs\QuxInterface', [ 'class' => 'yiiunit\framework\di\stubs\Qux', @@ -134,21 +133,21 @@ class ContainerTest extends TestCase ]); // use component of application - $callback = function($param, stubs\QuxInterface $qux, Bar $bar) { + $callback = function ($param, stubs\QuxInterface $qux, Bar $bar) { return [$param, $qux instanceof Qux, $qux->a, $bar->qux->a]; }; $result = Yii::$container->invoke($callback, ['D426']); $this->assertEquals(['D426', true, 'belongApp', 'independent'], $result); // another component of application - $callback = function($param, stubs\QuxInterface $qux2, $other = 'default') { + $callback = function ($param, stubs\QuxInterface $qux2, $other = 'default') { return [$param, $qux2 instanceof Qux, $qux2->a, $other]; }; $result = Yii::$container->invoke($callback, ['M2792684']); $this->assertEquals(['M2792684', true, 'belongAppQux2', 'default'], $result); // component not belong application - $callback = function($param, stubs\QuxInterface $notBelongApp, $other) { + $callback = function ($param, stubs\QuxInterface $notBelongApp, $other) { return [$param, $notBelongApp instanceof Qux, $notBelongApp->a, $other]; }; $result = Yii::$container->invoke($callback, ['MDM', 'not_default']); @@ -192,9 +191,9 @@ class ContainerTest extends TestCase 'class' => 'yiiunit\framework\di\stubs\Qux', 'a' => 'belongAppQux2', ], - ] + ], ]); - $closure = function($a, $x = 5, $b) { + $closure = function ($a, $x = 5, $b) { return $a > $b; }; $this->assertFalse(Yii::$container->invoke($closure, ['b' => 5, 'a' => 1])); @@ -213,9 +212,9 @@ class ContainerTest extends TestCase 'class' => 'yiiunit\framework\di\stubs\Qux', 'a' => 'belongAppQux2', ], - ] + ], ]); - $closure = function($a, $b) { + $closure = function ($a, $b) { return $a > $b; }; $this->assertEquals([1, 5], Yii::$container->resolveCallableDependencies($closure, ['b' => 5, 'a' => 1])); @@ -227,7 +226,7 @@ class ContainerTest extends TestCase { $container = new Container(); // Test optional unresolvable dependency. - $closure = function(QuxInterface $test = null) { + $closure = function (QuxInterface $test = null) { return $test; }; $this->assertNull($container->invoke($closure)); @@ -241,11 +240,11 @@ class ContainerTest extends TestCase Cat::className() => Type::className(), 'test\TraversableInterface' => [ ['class' => 'yiiunit\data\base\TraversableObject'], - [['item1', 'item2']] + [['item1', 'item2']], ], 'qux.using.closure' => function () { return new Qux(); - } + }, ]); $container->setDefinitions([]); @@ -266,11 +265,11 @@ class ContainerTest extends TestCase 'model.order' => Order::className(), 'test\TraversableInterface' => [ ['class' => 'yiiunit\data\base\TraversableObject'], - [['item1', 'item2']] + [['item1', 'item2']], ], 'qux.using.closure' => function () { return new Qux(); - } + }, ]); $container->setSingletons([]); diff --git a/tests/framework/di/InstanceTest.php b/tests/framework/di/InstanceTest.php index a668919..cbda936 100644 --- a/tests/framework/di/InstanceTest.php +++ b/tests/framework/di/InstanceTest.php @@ -48,7 +48,7 @@ class InstanceTest extends TestCase ]); $this->assertInstanceOf(Connection::className(), Instance::ensure('db', 'yii\db\Connection', $container)); - $this->assertInstanceOf(Connection::className(), Instance::ensure(new Connection, 'yii\db\Connection', $container)); + $this->assertInstanceOf(Connection::className(), Instance::ensure(new Connection(), 'yii\db\Connection', $container)); $this->assertInstanceOf('\\yii\\db\\Connection', Instance::ensure(['class' => 'yii\db\Connection', 'dsn' => 'test'], 'yii\db\Connection', $container)); } @@ -83,7 +83,7 @@ class InstanceTest extends TestCase ]); $this->assertInstanceOf(Connection::className(), Instance::ensure('db', null, $container)); - $this->assertInstanceOf(Connection::className(), Instance::ensure(new Connection, null, $container)); + $this->assertInstanceOf(Connection::className(), Instance::ensure(new Connection(), null, $container)); $this->assertInstanceOf('\\yii\\db\\Connection', Instance::ensure(['class' => 'yii\db\Connection', 'dsn' => 'test'], null, $container)); } @@ -95,14 +95,14 @@ class InstanceTest extends TestCase ]); $this->assertInstanceOf(Connection::className(), Instance::ensure('db')); - $this->assertInstanceOf(Connection::className(), Instance::ensure(new Connection)); + $this->assertInstanceOf(Connection::className(), Instance::ensure(new Connection())); $this->assertInstanceOf(Connection::className(), Instance::ensure(['class' => 'yii\db\Connection', 'dsn' => 'test'])); - Yii::$container = new Container; + Yii::$container = new Container(); } public function testExceptionRefersTo() { - $container = new Container; + $container = new Container(); $container->set('db', [ 'class' => 'yii\db\Connection', 'dsn' => 'test', @@ -118,7 +118,7 @@ class InstanceTest extends TestCase { $this->expectException('yii\base\InvalidConfigException'); $this->expectExceptionMessage('Invalid data type: yii\db\Connection. yii\base\Widget is expected.'); - Instance::ensure(new Connection, 'yii\base\Widget'); + Instance::ensure(new Connection(), 'yii\base\Widget'); } public function testExceptionComponentIsNotSpecified() @@ -135,8 +135,8 @@ class InstanceTest extends TestCase 'db' => [ 'class' => 'yii\db\Connection', 'dsn' => 'test', - ] - ] + ], + ], ]); $container = Instance::of('db'); @@ -151,10 +151,10 @@ class InstanceTest extends TestCase */ public function testLazyInitializationExample() { - Yii::$container = new Container; + Yii::$container = new Container(); Yii::$container->set('cache', [ 'class' => 'yii\caching\DbCache', - 'db' => Instance::of('db') + 'db' => Instance::of('db'), ]); Yii::$container->set('db', [ 'class' => 'yii\db\Connection', diff --git a/tests/framework/di/ServiceLocatorTest.php b/tests/framework/di/ServiceLocatorTest.php index 36766b7..e220d23 100644 --- a/tests/framework/di/ServiceLocatorTest.php +++ b/tests/framework/di/ServiceLocatorTest.php @@ -15,7 +15,7 @@ class Creator { public static function create() { - return new TestClass; + return new TestClass(); } } @@ -51,7 +51,7 @@ class ServiceLocatorTest extends TestCase // static method $container = new ServiceLocator(); $className = TestClass::className(); - $container->set($className, [__NAMESPACE__ . "\\Creator", 'create']); + $container->set($className, [__NAMESPACE__ . '\\Creator', 'create']); $object = $container->get($className); $this->assertInstanceOf($className, $object); $this->assertEquals(1, $object->prop1); @@ -62,7 +62,7 @@ class ServiceLocatorTest extends TestCase { $object = new TestClass(); $className = TestClass::className(); - $container = new ServiceLocator; + $container = new ServiceLocator(); $container->set($className, $object); $this->assertSame($container->get($className), $object); } diff --git a/tests/framework/di/stubs/QuxInterface.php b/tests/framework/di/stubs/QuxInterface.php index 8a98471..8815021 100644 --- a/tests/framework/di/stubs/QuxInterface.php +++ b/tests/framework/di/stubs/QuxInterface.php @@ -13,5 +13,5 @@ namespace yiiunit\framework\di\stubs; */ interface QuxInterface { - function quxMethod(); + public function quxMethod(); } diff --git a/tests/framework/filters/AccessRuleTest.php b/tests/framework/filters/AccessRuleTest.php index 9de4d80..98ba205 100644 --- a/tests/framework/filters/AccessRuleTest.php +++ b/tests/framework/filters/AccessRuleTest.php @@ -1,4 +1,9 @@ 'user2'], null], // user2 is author, can only edit own posts - ['update', true, 'user2', function() { return ['authorID' => 'user2']; }, true], - ['update', true, 'user2', function() { return ['authorID' => 'user1']; }, null], + ['update', true, 'user2', function () { return ['authorID' => 'user2']; }, true], + ['update', true, 'user2', function () { return ['authorID' => 'user1']; }, null], // user1 is admin, can update all posts - ['update', true, 'user1', function() { return ['authorID' => 'user1']; }, true], - ['update', true, 'user1', function() { return ['authorID' => 'user2']; }, true], + ['update', true, 'user1', function () { return ['authorID' => 'user1']; }, true], + ['update', true, 'user1', function () { return ['authorID' => 'user2']; }, true], // unknown user can not edit anything - ['update', true, 'unknown', function() { return ['authorID' => 'user1']; }, null], - ['update', true, 'unknown', function() { return ['authorID' => 'user2']; }, null], + ['update', true, 'unknown', function () { return ['authorID' => 'user1']; }, null], + ['update', true, 'unknown', function () { return ['authorID' => 'user2']; }, null], ]; } @@ -248,12 +254,13 @@ class AccessRuleTest extends \yiiunit\TestCase * * @dataProvider matchRoleProvider * @param string $actionid the action id - * @param boolean $allow whether the rule should allow access + * @param bool $allow whether the rule should allow access * @param string $userid the userid to check * @param array|Closure $roleParams params for $roleParams - * @param boolean $expected the expected result or null + * @param bool $expected the expected result or null */ - public function testMatchRole($actionid, $allow, $userid, $roleParams, $expected) { + public function testMatchRole($actionid, $allow, $userid, $roleParams, $expected) + { $action = $this->mockAction(); $auth = $this->mockAuthManager(); $request = $this->mockRequest(); @@ -277,7 +284,8 @@ class AccessRuleTest extends \yiiunit\TestCase * * @see https://github.com/yiisoft/yii2/issues/4793 */ - public function testMatchRoleWithoutUser() { + public function testMatchRoleWithoutUser() + { $action = $this->mockAction(); $request = $this->mockRequest(); diff --git a/tests/framework/filters/HostControlTest.php b/tests/framework/filters/HostControlTest.php index 9ec462a..0cb1bc8 100644 --- a/tests/framework/filters/HostControlTest.php +++ b/tests/framework/filters/HostControlTest.php @@ -1,4 +1,9 @@ mockWebApplication(); } @@ -33,46 +38,46 @@ class HostControlTest extends TestCase [ null, 'example.com', - true + true, ], [ 'example.com', 'example.com', - true + true, ], [ ['example.com'], 'example.com', - true + true, ], [ ['example.com'], 'domain.com', - false + false, ], [ ['*.example.com'], 'en.example.com', - true + true, ], [ ['*.example.com'], 'fake.com', - false + false, ], [ function () { return ['example.com']; }, 'example.com', - true + true, ], [ function () { return ['example.com']; }, 'fake.com', - false + false, ], ]; } @@ -122,7 +127,7 @@ class HostControlTest extends TestCase $filter = new HostControl(); $filter->allowedHosts = ['example.com']; $this->denyCallBackCalled = false; - $filter->denyCallback = function() { + $filter->denyCallback = function () { $this->denyCallBackCalled = true; }; @@ -137,7 +142,7 @@ class HostControlTest extends TestCase $filter = new HostControl(); $filter->allowedHosts = ['example.com']; $filter->fallbackHostInfo = 'http://yiiframework.com'; - $filter->denyCallback = function() {}; + $filter->denyCallback = function () {}; $controller = new Controller('test', Yii::$app); $action = new Action('test', $controller); diff --git a/tests/framework/filters/HttpCacheTest.php b/tests/framework/filters/HttpCacheTest.php index 46a05df..399eb8f 100644 --- a/tests/framework/filters/HttpCacheTest.php +++ b/tests/framework/filters/HttpCacheTest.php @@ -1,4 +1,9 @@ mockWebApplication(); } @@ -24,14 +29,14 @@ class HttpCacheTest extends \yiiunit\TestCase { $httpCache = new HttpCache(); $this->assertTrue($httpCache->beforeAction(null)); - $httpCache->enabled=false; + $httpCache->enabled = false; $this->assertTrue($httpCache->beforeAction(null)); } public function testEmptyPragma() { $httpCache = new HttpCache(); - $httpCache->etagSeed = function($action, $params) { + $httpCache->etagSeed = function ($action, $params) { return ''; }; $httpCache->beforeAction(null); @@ -41,7 +46,7 @@ class HttpCacheTest extends \yiiunit\TestCase } /** - * @covers yii\filters\HttpCache::validateCache + * @covers \yii\filters\HttpCache::validateCache */ public function testValidateCache() { @@ -71,21 +76,21 @@ class HttpCacheTest extends \yiiunit\TestCase } /** - * @covers yii\filters\HttpCache::generateEtag + * @covers \yii\filters\HttpCache::generateEtag */ public function testGenerateEtag() { $httpCache = new HttpCache(); $httpCache->weakEtag = false; - $httpCache->etagSeed = function($action, $params) { + $httpCache->etagSeed = function ($action, $params) { return null; }; $httpCache->beforeAction(null); $response = Yii::$app->getResponse(); $this->assertFalse($response->getHeaders()->offsetExists('ETag')); - $httpCache->etagSeed = function($action, $params) { + $httpCache->etagSeed = function ($action, $params) { return ''; }; $httpCache->beforeAction(null); diff --git a/tests/framework/filters/PageCacheTest.php b/tests/framework/filters/PageCacheTest.php index c23a797..237049a 100644 --- a/tests/framework/filters/PageCacheTest.php +++ b/tests/framework/filters/PageCacheTest.php @@ -1,4 +1,9 @@ 'disabled', 'properties' => [ - 'enabled' => false + 'enabled' => false, ], 'cacheable' => false, ]], @@ -52,64 +57,64 @@ class PageCacheTest extends TestCase [[ 'name' => 'allCookies', 'properties' => [ - 'cacheCookies' => true + 'cacheCookies' => true, ], 'cookies' => [ 'test-cookie-1' => true, 'test-cookie-2' => true, - ] + ], ]], [[ 'name' => 'someCookies', 'properties' => [ - 'cacheCookies' => ['test-cookie-2'] + 'cacheCookies' => ['test-cookie-2'], ], 'cookies' => [ 'test-cookie-1' => false, 'test-cookie-2' => true, - ] + ], ]], [[ 'name' => 'noCookies', 'properties' => [ - 'cacheCookies' => false + 'cacheCookies' => false, ], 'cookies' => [ 'test-cookie-1' => false, 'test-cookie-2' => false, - ] + ], ]], // Headers [[ 'name' => 'allHeaders', 'properties' => [ - 'cacheHeaders' => true + 'cacheHeaders' => true, ], 'headers' => [ 'test-header-1' => true, 'test-header-2' => true, - ] + ], ]], [[ 'name' => 'someHeaders', 'properties' => [ - 'cacheHeaders' => ['test-header-2'] + 'cacheHeaders' => ['test-header-2'], ], 'headers' => [ 'test-header-1' => false, 'test-header-2' => true, - ] + ], ]], [[ 'name' => 'noHeaders', 'properties' => [ - 'cacheHeaders' => false + 'cacheHeaders' => false, ], 'headers' => [ 'test-header-1' => false, 'test-header-2' => false, - ] + ], ]], // All together @@ -117,7 +122,7 @@ class PageCacheTest extends TestCase 'name' => 'someCookiesSomeHeaders', 'properties' => [ 'cacheCookies' => ['test-cookie-2'], - 'cacheHeaders' => ['test-header-2'] + 'cacheHeaders' => ['test-header-2'], ], 'cookies' => [ 'test-cookie-1' => false, @@ -126,7 +131,7 @@ class PageCacheTest extends TestCase 'headers' => [ 'test-header-1' => false, 'test-header-2' => true, - ] + ], ]], ]; } @@ -149,7 +154,7 @@ class PageCacheTest extends TestCase $action = new Action('test', $controller); $filter = new PageCache(array_merge([ 'cache' => $cache = new ArrayCache(), - 'view' => new View() + 'view' => new View(), ], $testCase['properties'])); $this->assertTrue($filter->beforeAction($action), $testCase['name']); // Cookies @@ -160,7 +165,7 @@ class PageCacheTest extends TestCase Yii::$app->response->cookies->add(new Cookie([ 'name' => $name, 'value' => $value, - 'expire' => PHP_INT_MAX + 'expire' => PHP_INT_MAX, ])); $cookies[$name] = $value; } @@ -203,7 +208,7 @@ class PageCacheTest extends TestCase $action = new Action('test', $controller); $filter = new PageCache(array_merge([ 'cache' => $cache, - 'view' => new View() + 'view' => new View(), ]), $testCase['properties']); Yii::$app->params['dynamic'] = $dynamic = Yii::$app->security->generateRandomString(); $this->assertFalse($filter->beforeAction($action), $testCase['name']); @@ -248,7 +253,7 @@ class PageCacheTest extends TestCase $filter = new PageCache([ 'cache' => $cache = new ArrayCache(), 'view' => new View(), - 'duration' => 1 + 'duration' => 1, ]); $this->assertTrue($filter->beforeAction($action)); $static = Yii::$app->security->generateRandomString(); @@ -272,7 +277,7 @@ class PageCacheTest extends TestCase $action = new Action('test', $controller); $filter = new PageCache([ 'cache' => $cache, - 'view' => new View() + 'view' => new View(), ]); Yii::$app->params['dynamic'] = $dynamic = Yii::$app->security->generateRandomString(); $this->assertTrue($filter->beforeAction($action)); @@ -300,7 +305,7 @@ class PageCacheTest extends TestCase $filter = new PageCache([ 'cache' => $cache = new ArrayCache(), 'view' => new View(), - 'varyByRoute' => $enabled + 'varyByRoute' => $enabled, ]); $this->assertTrue($filter->beforeAction($action)); $static = Yii::$app->security->generateRandomString(); @@ -322,7 +327,7 @@ class PageCacheTest extends TestCase $filter = new PageCache([ 'cache' => $cache, 'view' => new View(), - 'varyByRoute' => $enabled + 'varyByRoute' => $enabled, ]); Yii::$app->params['dynamic'] = $dynamic = Yii::$app->security->generateRandomString(); $this->assertSame($enabled, $filter->beforeAction($action), $enabled); @@ -353,7 +358,7 @@ class PageCacheTest extends TestCase $filter = new PageCache([ 'cache' => $cache = new ArrayCache(), 'view' => new View(), - 'variations' => $originalVariations + 'variations' => $originalVariations, ]); $this->assertTrue($filter->beforeAction($action)); $static = Yii::$app->security->generateRandomString(); @@ -374,7 +379,7 @@ class PageCacheTest extends TestCase $filter = new PageCache([ 'cache' => $cache, 'view' => new View(), - 'variations' => $testCase + 'variations' => $testCase, ]); Yii::$app->params['dynamic'] = $dynamic = Yii::$app->security->generateRandomString(); $this->assertNotSame($expected, $filter->beforeAction($action), $expected); @@ -405,7 +410,7 @@ class PageCacheTest extends TestCase 'dependency' => [ 'class' => ExpressionDependency::className(), 'expression' => 'Yii::$app->params[\'dependency\']', - ] + ], ]); $this->assertTrue($filter->beforeAction($action)); $static = Yii::$app->security->generateRandomString(); diff --git a/tests/framework/filters/RateLimiterTest.php b/tests/framework/filters/RateLimiterTest.php index e4ca515..e6f0333 100644 --- a/tests/framework/filters/RateLimiterTest.php +++ b/tests/framework/filters/RateLimiterTest.php @@ -1,16 +1,21 @@ 'Request']); @@ -106,7 +111,7 @@ class RateLimiterTest extends TestCase public function testCheckRateLimitTooManyRequests() { /* @var $rateLimit UserIdentity|\Prophecy\ObjectProphecy */ - $rateLimit = new RateLimit; + $rateLimit = new RateLimit(); $rateLimit ->setRateLimit([1, 1]) ->setAllowance([1, time() + 2]); @@ -119,7 +124,7 @@ class RateLimiterTest extends TestCase public function testCheckRateaddRateLimitHeaders() { /* @var $user UserIdentity|\Prophecy\ObjectProphecy */ - $rateLimit = new RateLimit; + $rateLimit = new RateLimit(); $rateLimit ->setRateLimit([1, 1]) ->setAllowance([1, time()]); diff --git a/tests/framework/filters/auth/AuthMethodTest.php b/tests/framework/filters/auth/AuthMethodTest.php index f79e274..c55293b 100644 --- a/tests/framework/filters/auth/AuthMethodTest.php +++ b/tests/framework/filters/auth/AuthMethodTest.php @@ -1,4 +1,9 @@ mockWebApplication([ 'components' => [ 'user' => [ - 'identityClass' => UserIdentity::className() + 'identityClass' => UserIdentity::className(), ], - ] + ], ]); } @@ -80,4 +85,4 @@ class AuthMethodTest extends TestCase $this->assertFalse($method->invokeArgs($filter, [$this->createAction(['id' => 'index'])])); $this->assertTrue($method->invokeArgs($filter, [$this->createAction(['id' => 'test/index'])])); } -} \ No newline at end of file +} diff --git a/tests/framework/filters/auth/AuthTest.php b/tests/framework/filters/auth/AuthTest.php index e06305e..bba6836 100644 --- a/tests/framework/filters/auth/AuthTest.php +++ b/tests/framework/filters/auth/AuthTest.php @@ -1,4 +1,9 @@ [ 'user' => [ - 'identityClass' => UserIdentity::className() + 'identityClass' => UserIdentity::className(), ], ], 'controllerMap' => [ - 'test-auth' => TestAuthController::className() - ] + 'test-auth' => TestAuthController::className(), + ], ]; $this->mockWebApplication($appConfig); @@ -60,7 +65,6 @@ class AuthTest extends \yiiunit\TestCase try { $this->assertEquals($login, $controller->run($action)); } catch (UnauthorizedHttpException $e) { - } } @@ -72,7 +76,6 @@ class AuthTest extends \yiiunit\TestCase try { $this->assertEquals($login, $controller->run($action)); } catch (UnauthorizedHttpException $e) { - } } @@ -84,14 +87,14 @@ class AuthTest extends \yiiunit\TestCase try { $this->assertEquals($login, $controller->run($action)); } catch (UnauthorizedHttpException $e) { - } } /** * @dataProvider tokenProvider */ - public function testQueryParamAuth($token, $login) { + public function testQueryParamAuth($token, $login) + { $_GET['access-token'] = $token; $filter = ['class' => QueryParamAuth::className()]; $this->authOnly($token, $login, $filter, 'query-param-auth'); @@ -102,7 +105,8 @@ class AuthTest extends \yiiunit\TestCase /** * @dataProvider tokenProvider */ - public function testHttpBasicAuth($token, $login) { + public function testHttpBasicAuth($token, $login) + { $_SERVER['PHP_AUTH_USER'] = $token; $_SERVER['PHP_AUTH_PW'] = 'whatever, we are testers'; $filter = ['class' => HttpBasicAuth::className()]; @@ -114,7 +118,8 @@ class AuthTest extends \yiiunit\TestCase /** * @dataProvider tokenProvider */ - public function testHttpBasicAuthCustom($token, $login) { + public function testHttpBasicAuthCustom($token, $login) + { $_SERVER['PHP_AUTH_USER'] = $login; $_SERVER['PHP_AUTH_PW'] = 'whatever, we are testers'; $filter = [ @@ -125,7 +130,7 @@ class AuthTest extends \yiiunit\TestCase } return null; - } + }, ]; $this->authOnly($token, $login, $filter, 'basic-auth'); $this->authOptional($token, $login, $filter, 'basic-auth'); @@ -135,7 +140,8 @@ class AuthTest extends \yiiunit\TestCase /** * @dataProvider tokenProvider */ - public function testHttpBearerAuth($token, $login) { + public function testHttpBearerAuth($token, $login) + { Yii::$app->request->headers->set('Authorization', "Bearer $token"); $filter = ['class' => HttpBearerAuth::className()]; $this->authOnly($token, $login, $filter, 'bearer-auth'); @@ -159,7 +165,7 @@ class AuthTest extends \yiiunit\TestCase public function testActive($authClass) { /** @var $filter AuthMethod */ - $filter = new $authClass; + $filter = new $authClass(); $reflection = new \ReflectionClass($filter); $method = $reflection->getMethod('isActive'); $method->setAccessible(true); @@ -200,7 +206,6 @@ class AuthTest extends \yiiunit\TestCase $this->assertEquals(true, $method->invokeArgs($filter, [new Action('index', $controller)])); $this->assertEquals(false, $method->invokeArgs($filter, [new Action('view', $controller)])); } - } /** diff --git a/tests/framework/filters/auth/CompositeAuthTest.php b/tests/framework/filters/auth/CompositeAuthTest.php index 71a35ec..99faf3d 100644 --- a/tests/framework/filters/auth/CompositeAuthTest.php +++ b/tests/framework/filters/auth/CompositeAuthTest.php @@ -1,4 +1,9 @@ runAction('a'); @@ -36,7 +41,7 @@ class TestController extends Controller public function actionC() { - /** + /* * this call will execute the actionA in a same instance of TestController */ return $this->run('a'); @@ -44,7 +49,7 @@ class TestController extends Controller public function actionD() { - /** + /* * this call will execute the actionA in a new instance of TestController */ return $this->run('test/a'); @@ -52,7 +57,7 @@ class TestController extends Controller public function behaviors() { - /** + /* * the CompositeAuth::authenticate() assumes that it is only executed once per the controller's instance * i believe this is okay as long as we specify in the documentation that if we want to use the authenticate * method again(this might even be also true to other behaviors that attaches to the beforeAction event), @@ -62,7 +67,7 @@ class TestController extends Controller 'authenticator' => [ 'class' => CompositeAuth::className(), 'authMethods' => [ - TestAuth::className() + TestAuth::className(), ], ], ]; @@ -78,18 +83,18 @@ class CompositeAuthTest 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'; $appConfig = [ 'components' => [ 'user' => [ - 'identityClass' => UserIdentity::className() + 'identityClass' => UserIdentity::className(), ], ], 'controllerMap' => [ - 'test' => TestController::className() - ] + 'test' => TestController::className(), + ], ]; $this->mockWebApplication($appConfig); diff --git a/tests/framework/filters/stubs/MockAuthManager.php b/tests/framework/filters/stubs/MockAuthManager.php index 956787f..1ed140e 100644 --- a/tests/framework/filters/stubs/MockAuthManager.php +++ b/tests/framework/filters/stubs/MockAuthManager.php @@ -1,16 +1,21 @@ _rateLimit = $rateLimit; - + return $this; } @@ -40,5 +45,4 @@ class RateLimit extends Object implements RateLimitInterface { return [$action, $allowance, $timestamp]; } - } diff --git a/tests/framework/filters/stubs/UserIdentity.php b/tests/framework/filters/stubs/UserIdentity.php index 18cd026..086ab8b 100644 --- a/tests/framework/filters/stubs/UserIdentity.php +++ b/tests/framework/filters/stubs/UserIdentity.php @@ -1,4 +1,9 @@ urlCreator = function($model, $key, $index) { + $column->urlCreator = function ($model, $key, $index) { return 'http://test.com'; }; $columnContents = $column->renderDataCell(['id' => 1], 1, 0); @@ -45,14 +48,14 @@ class ActionColumnTest extends \yiiunit\TestCase $this->assertEquals($expectedHtml, $columnContents); $column = new ActionColumn(); - $column->urlCreator = function($model, $key, $index) { + $column->urlCreator = function ($model, $key, $index) { return 'http://test.com'; }; $column->template = '{update}'; $column->buttons = [ - 'update' => function($url, $model, $key) { + 'update' => function ($url, $model, $key) { return 'update_button'; - } + }, ]; //test default visible button @@ -61,31 +64,30 @@ class ActionColumnTest extends \yiiunit\TestCase //test visible button $column->visibleButtons = [ - 'update' => true + 'update' => true, ]; $columnContents = $column->renderDataCell(['id' => 1], 1, 0); $this->assertContains('update_button', $columnContents); //test visible button (condition is callback) $column->visibleButtons = [ - 'update' => function($model, $key, $index) {return $model['id'] == 1;} + 'update' => function ($model, $key, $index) {return $model['id'] == 1;}, ]; $columnContents = $column->renderDataCell(['id' => 1], 1, 0); $this->assertContains('update_button', $columnContents); //test invisible button $column->visibleButtons = [ - 'update' => false + 'update' => false, ]; $columnContents = $column->renderDataCell(['id' => 1], 1, 0); $this->assertNotContains('update_button', $columnContents); //test invisible button (condition is callback) $column->visibleButtons = [ - 'update' => function($model, $key, $index) {return $model['id'] != 1;} + 'update' => function ($model, $key, $index) {return $model['id'] != 1;}, ]; $columnContents = $column->renderDataCell(['id' => 1], 1, 0); $this->assertNotContains('update_button', $columnContents); - } } diff --git a/tests/framework/grid/CheckboxColumnTest.php b/tests/framework/grid/CheckboxColumnTest.php index b69b795..5612c83 100644 --- a/tests/framework/grid/CheckboxColumnTest.php +++ b/tests/framework/grid/CheckboxColumnTest.php @@ -7,13 +7,11 @@ namespace yiiunit\framework\grid; +use Yii; use yii\data\ArrayDataProvider; use yii\grid\CheckboxColumn; use yii\grid\GridView; use yii\helpers\FileHelper; -use yii\i18n\Formatter; -use yii\web\View; -use Yii; use yiiunit\framework\i18n\IntlTestHelper; use yiiunit\TestCase; @@ -69,7 +67,7 @@ class CheckboxColumnTest extends TestCase 'checkboxOptions' => function ($model, $key, $index, $column) { return []; }, - 'grid' => $this->getGrid() + 'grid' => $this->getGrid(), ]); $this->assertContains('value="1"', $column->renderDataCell([], 1, 0)); $this->assertContains('value="42"', $column->renderDataCell([], 42, 0)); @@ -79,7 +77,7 @@ class CheckboxColumnTest extends TestCase 'checkboxOptions' => function ($model, $key, $index, $column) { return ['value' => 42]; }, - 'grid' => $this->getGrid() + 'grid' => $this->getGrid(), ]); $this->assertNotContains('value="1"', $column->renderDataCell([], 1, 0)); $this->assertContains('value="42"', $column->renderDataCell([], 1, 0)); diff --git a/tests/framework/grid/DataColumnTest.php b/tests/framework/grid/DataColumnTest.php index 454fe08..eed8c7a 100644 --- a/tests/framework/grid/DataColumnTest.php +++ b/tests/framework/grid/DataColumnTest.php @@ -1,5 +1,9 @@ new ArrayDataProvider([ 'allModels' => [], 'totalCount' => 0, - 'modelClass' => Order::className() + 'modelClass' => Order::className(), ]), 'columns' => ['customer_id', 'total'], ]); @@ -52,7 +56,7 @@ class DataColumnTest extends \yiiunit\TestCase 'totalCount' => 0, ]), 'columns' => ['customer_id', 'total'], - 'filterModel' => new Order, + 'filterModel' => new Order(), ]); $labels = []; foreach ($grid->columns as $column) { @@ -82,7 +86,6 @@ class DataColumnTest extends \yiiunit\TestCase 'filter' => $filterInput, ], ], - ]); //print_r($grid->columns);exit(); $dataColumn = $grid->columns[0]; @@ -104,8 +107,8 @@ class DataColumnTest extends \yiiunit\TestCase 'db' => [ 'class' => '\yii\db\Connection', 'dsn' => 'sqlite::memory:', - ] - ] + ], + ], ]); $columns = [ 'id' => 'pk', @@ -124,9 +127,9 @@ class DataColumnTest extends \yiiunit\TestCase 0 => [ 'attribute' => 'customer_id', 'filter' => $filterInput, - ] + ], ], - 'filterModel' => new Order, + 'filterModel' => new Order(), ]); $dataColumn = $grid->columns[0]; @@ -155,8 +158,8 @@ HTML 'db' => [ 'class' => '\yii\db\Connection', 'dsn' => 'sqlite::memory:', - ] - ] + ], + ], ]); $columns = [ 'id' => 'pk', @@ -176,7 +179,7 @@ HTML 'format' => 'boolean', // does not make sense for this column but should still output proper dropdown list ], ], - 'filterModel' => new Order, + 'filterModel' => new Order(), ]); $dataColumn = $grid->columns[0]; diff --git a/tests/framework/grid/GridViewTest.php b/tests/framework/grid/GridViewTest.php index 983fd8f..deb6687 100644 --- a/tests/framework/grid/GridViewTest.php +++ b/tests/framework/grid/GridViewTest.php @@ -1,12 +1,16 @@ @@ -74,7 +78,7 @@ class GridViewTest extends \yiiunit\TestCase public function testGuessColumns() { - $row = ['id' => 1, 'name' => 'Name1', 'value' => 'Value1', 'description' => 'Description1',]; + $row = ['id' => 1, 'name' => 'Name1', 'value' => 'Value1', 'description' => 'Description1']; $grid = new GridView([ 'dataProvider' => new ArrayDataProvider( @@ -94,8 +98,8 @@ class GridViewTest extends \yiiunit\TestCase $this->assertArrayHasKey($column->attribute, $row); } - $row = array_merge($row, ['relation' => ['id' => 1, 'name' => 'RelationName',],]); - $row = array_merge($row, ['otherRelation' => (object)$row['relation']]); + $row = array_merge($row, ['relation' => ['id' => 1, 'name' => 'RelationName']]); + $row = array_merge($row, ['otherRelation' => (object) $row['relation']]); $grid = new GridView([ 'dataProvider' => new ArrayDataProvider( diff --git a/tests/framework/grid/RadiobuttonColumnTest.php b/tests/framework/grid/RadiobuttonColumnTest.php index c011e9e..14acae9 100644 --- a/tests/framework/grid/RadiobuttonColumnTest.php +++ b/tests/framework/grid/RadiobuttonColumnTest.php @@ -16,7 +16,6 @@ use yiiunit\TestCase; /** * Class RadiobuttonColumnTest - * @package yiiunit\framework\grid * @group grid * @since 2.0.11 */ @@ -29,7 +28,7 @@ class RadiobuttonColumnTest extends TestCase public function testException() { new RadioButtonColumn([ - 'name' => null + 'name' => null, ]); } @@ -37,8 +36,8 @@ class RadiobuttonColumnTest extends TestCase { $column = new RadioButtonColumn([ 'radioOptions' => [ - 'value' => 42 - ] + 'value' => 42, + ], ]); $this->assertEquals('', $column->renderDataCell([], 1, 0)); } @@ -47,14 +46,14 @@ class RadiobuttonColumnTest extends TestCase { $model = [ 'label' => 'label', - 'value' => 123 + 'value' => 123, ]; $column = new RadioButtonColumn([ 'radioOptions' => function ($model) { return [ - 'value' => $model['value'] + 'value' => $model['value'], ]; - } + }, ]); $actual = $column->renderDataCell($model, 1, 0); $this->assertEquals('', $actual); @@ -70,7 +69,7 @@ class RadiobuttonColumnTest extends TestCase $models = [ ['label' => 'label1', 'value' => 1], - ['label' => 'label2', 'value' => 2, 'checked' => true] + ['label' => 'label2', 'value' => 2, 'checked' => true], ]; $grid = new GridView([ 'dataProvider' => new ArrayDataProvider(['allModels' => $models]), @@ -81,11 +80,11 @@ class RadiobuttonColumnTest extends TestCase 'radioOptions' => function ($model) { return [ 'value' => $model['value'], - 'checked' => $model['value'] == 2 + 'checked' => $model['value'] == 2, ]; - } - ] - ] + }, + ], + ], ]); ob_start(); $grid->run(); diff --git a/tests/framework/helpers/ArrayHelperTest.php b/tests/framework/helpers/ArrayHelperTest.php index 4d4e737..4e09d65 100644 --- a/tests/framework/helpers/ArrayHelperTest.php +++ b/tests/framework/helpers/ArrayHelperTest.php @@ -1,11 +1,16 @@ method('toArray')->willReturn([]); $this->assertEquals([], ArrayHelper::toArray($dataArrayable)); $this->assertEquals(['foo'], ArrayHelper::toArray('foo')); - $object = new Post1; + $object = new Post1(); $this->assertEquals(get_object_vars($object), ArrayHelper::toArray($object)); - $object = new Post2; + $object = new Post2(); $this->assertEquals(get_object_vars($object), ArrayHelper::toArray($object)); - $object1 = new Post1; - $object2 = new Post2; + $object1 = new Post1(); + $object2 = new Post2(); $this->assertEquals([ get_object_vars($object1), get_object_vars($object2), @@ -70,7 +75,7 @@ class ArrayHelperTest extends TestCase $object2, ])); - $object = new Post2; + $object = new Post2(); $this->assertEquals([ 'id' => 123, 'secret' => 's', @@ -82,8 +87,8 @@ class ArrayHelperTest extends TestCase '_content' => 'content', 'length' => function ($post) { return strlen($post->content); - } - ] + }, + ], ])); $object = new Post3(); @@ -108,14 +113,14 @@ class ArrayHelperTest extends TestCase $object->className() => [ 'id', 'subObject', 'id_plus_1' => function ($post) { - return $post->id+1; - } + return $post->id + 1; + }, ], $object->subObject->className() => [ 'id', 'id_plus_1' => function ($post) { - return $post->id+1; - } + return $post->id + 1; + }, ], ])); @@ -130,8 +135,8 @@ class ArrayHelperTest extends TestCase $object->subObject->className() => [ 'id', 'id_plus_1' => function ($post) { - return $post->id+1; - } + return $post->id + 1; + }, ], ])); } @@ -154,18 +159,18 @@ class ArrayHelperTest extends TestCase 'Bob' => 'Dylan', 'Michael' => 'Jackson', 'Mick' => 'Jagger', - 'Janet' => 'Jackson' + 'Janet' => 'Jackson', ]; $removed = ArrayHelper::removeValue($array, 'Jackson'); $this->assertEquals([ 'Bob' => 'Dylan', - 'Mick' => 'Jagger' + 'Mick' => 'Jagger', ], $array); $this->assertEquals([ 'Michael' => 'Jackson', - 'Janet' => 'Jackson' + 'Janet' => 'Jackson', ], $removed); } @@ -175,7 +180,7 @@ class ArrayHelperTest extends TestCase 'Bob' => 'Dylan', 'Michael' => 'Jackson', 'Mick' => 'Jagger', - 'Janet' => 'Jackson' + 'Janet' => 'Jackson', ]; $removed = ArrayHelper::removeValue($array, 'Marley'); @@ -184,7 +189,7 @@ class ArrayHelperTest extends TestCase 'Bob' => 'Dylan', 'Michael' => 'Jackson', 'Mick' => 'Jagger', - 'Janet' => 'Jackson' + 'Janet' => 'Jackson', ], $array); $this->assertEquals([], $removed); } @@ -242,21 +247,21 @@ class ArrayHelperTest extends TestCase public function testMultisortNestedObjects() { $obj1 = new \stdClass(); - $obj1->type = "def"; + $obj1->type = 'def'; $obj1->owner = $obj1; $obj2 = new \stdClass(); - $obj2->type = "abc"; + $obj2->type = 'abc'; $obj2->owner = $obj2; $obj3 = new \stdClass(); - $obj3->type = "abc"; + $obj3->type = 'abc'; $obj3->owner = $obj3; $models = [ $obj1, $obj2, - $obj3 + $obj3, ]; $this->assertEquals($obj2, $obj3); @@ -321,7 +326,7 @@ class ArrayHelperTest extends TestCase '- Bug: test4', ]; $i = 0; - ArrayHelper::multisort($changelog, function($line) use (&$i) { + ArrayHelper::multisort($changelog, function ($line) use (&$i) { if (preg_match('/^- (Enh|Bug)( #\d+)?: .+$/', $line, $m)) { $o = ['Bug' => 'C', 'Enh' => 'D']; return $o[$m[1]] . ' ' . (!empty($m[2]) ? $m[2] : 'AAAA' . $i++); @@ -336,7 +341,7 @@ class ArrayHelperTest extends TestCase '- Enh: test3', ], $changelog); } - + /** * @expectedException \yii\base\InvalidParamException */ @@ -498,7 +503,7 @@ class ArrayHelperTest extends TestCase $array = [ ['id' => '123', 'data' => 'abc'], ['id' => '345', 'data' => 'def'], - ['id' => '345', 'data' => 'ghi'] + ['id' => '345', 'data' => 'ghi'], ]; $result = ArrayHelper::index($array, 'id'); $this->assertEquals([ @@ -527,24 +532,25 @@ class ArrayHelperTest extends TestCase return $element['id'] == '345' ? null : $element['id']; }); $this->assertEquals([ - '123' => ['id' => '123', 'data' => 'abc'] + '123' => ['id' => '123', 'data' => 'abc'], ], $result); } - public function testIndexGroupBy() { + public function testIndexGroupBy() + { $array = [ ['id' => '123', 'data' => 'abc'], ['id' => '345', 'data' => 'def'], - ['id' => '345', 'data' => 'ghi'] + ['id' => '345', 'data' => 'ghi'], ]; $expected = [ '123' => [ - ['id' => '123', 'data' => 'abc'] + ['id' => '123', 'data' => 'abc'], ], '345' => [ ['id' => '345', 'data' => 'def'], - ['id' => '345', 'data' => 'ghi'] + ['id' => '345', 'data' => 'ghi'], ], ]; $result = ArrayHelper::index($array, null, ['id']); @@ -556,26 +562,26 @@ class ArrayHelperTest extends TestCase $this->assertEquals([ '123' => [ 'abc' => [ - ['id' => '123', 'data' => 'abc'] - ] + ['id' => '123', 'data' => 'abc'], + ], ], '345' => [ 'def' => [ - ['id' => '345', 'data' => 'def'] + ['id' => '345', 'data' => 'def'], ], 'ghi' => [ - ['id' => '345', 'data' => 'ghi'] - ] + ['id' => '345', 'data' => 'ghi'], + ], ], ], $result); $expected = [ '123' => [ - 'abc' => ['id' => '123', 'data' => 'abc'] + 'abc' => ['id' => '123', 'data' => 'abc'], ], '345' => [ 'def' => ['id' => '345', 'data' => 'def'], - 'ghi' => ['id' => '345', 'data' => 'ghi'] + 'ghi' => ['id' => '345', 'data' => 'ghi'], ], ]; $result = ArrayHelper::index($array, 'data', ['id']); @@ -590,16 +596,16 @@ class ArrayHelperTest extends TestCase $expected = [ '123' => [ 'abc' => [ - 'abc' => ['id' => '123', 'data' => 'abc'] - ] + 'abc' => ['id' => '123', 'data' => 'abc'], + ], ], '345' => [ 'def' => [ - 'def' => ['id' => '345', 'data' => 'def'] + 'def' => ['id' => '345', 'data' => 'def'], ], 'ghi' => [ - 'ghi' => ['id' => '345', 'data' => 'ghi'] - ] + 'ghi' => ['id' => '345', 'data' => 'ghi'], + ], ], ]; $result = ArrayHelper::index($array, 'data', ['id', 'data']); @@ -721,7 +727,7 @@ class ArrayHelperTest extends TestCase return $array['date'] . $defaultValue; }, '31-12-2113test', - 'test' + 'test', ], [['version', '1.0', 'status'], 'released'], [['version', '1.0', 'date'], 'defaultValue', 'defaultValue'], @@ -756,8 +762,8 @@ class ArrayHelperTest extends TestCase ], 'version' => [ '1.0' => [ - 'status' => 'released' - ] + 'status' => 'released', + ], ], ]; @@ -861,7 +867,7 @@ class ArrayHelperTest extends TestCase [ '<>' => 'a<>b', '23' => true, - ] + ], ]; $this->assertEquals([ 'abc' => '123', @@ -871,7 +877,7 @@ class ArrayHelperTest extends TestCase [ '<>' => 'a<>b', '23' => true, - ] + ], ], ArrayHelper::htmlDecode($array)); $this->assertEquals([ 'abc' => '123', @@ -881,7 +887,7 @@ class ArrayHelperTest extends TestCase [ '<>' => 'a<>b', '23' => true, - ] + ], ], ArrayHelper::htmlDecode($array, false)); } @@ -899,7 +905,6 @@ class ArrayHelperTest extends TestCase $this->assertTrue(ArrayHelper::isIn(['a'], new \ArrayObject([['a'], 'b']))); $this->assertFalse(ArrayHelper::isIn('a', new \ArrayObject([['a'], 'b']))); $this->assertFalse(ArrayHelper::isIn('a', [['a'], 'b'])); - } public function testIsInStrict() @@ -947,7 +952,7 @@ class ArrayHelperTest extends TestCase $this->assertTrue(ArrayHelper::isTraversable(['a'])); $this->assertTrue(ArrayHelper::isTraversable(new \ArrayObject(['1']))); $this->assertFalse(ArrayHelper::isTraversable(new \stdClass())); - $this->assertFalse(ArrayHelper::isTraversable("A,B,C")); + $this->assertFalse(ArrayHelper::isTraversable('A,B,C')); $this->assertFalse(ArrayHelper::isTraversable(12)); $this->assertFalse(ArrayHelper::isTraversable(false)); $this->assertFalse(ArrayHelper::isTraversable(null)); diff --git a/tests/framework/helpers/ConsoleTest.php b/tests/framework/helpers/ConsoleTest.php index 8952106..f4ad39d 100644 --- a/tests/framework/helpers/ConsoleTest.php +++ b/tests/framework/helpers/ConsoleTest.php @@ -1,4 +1,9 @@ test' + 'test', ], [Console::ansiFormatCode([Console::RESET]) . Console::ansiFormatCode([Console::RESET]), ''], @@ -109,23 +114,23 @@ class ConsoleTest extends TestCase [ Console::ansiFormatCode([Console::BOLD]) . 'abc' . Console::ansiFormatCode([Console::RESET, Console::FG_GREEN]) . 'ghj' . Console::ansiFormatCode([Console::RESET]), - 'abcghj' + 'abcghj', ], [ Console::ansiFormatCode([Console::FG_GREEN]) . ' a ' . Console::ansiFormatCode([Console::BOLD]) . 'abc' . Console::ansiFormatCode([Console::RESET]) . 'ghj', - ' a abcghj' + ' a abcghj', ], [ Console::ansiFormat('test', [Console::FG_GREEN, Console::BG_BLUE, Console::NEGATIVE]), - 'test' + 'test', ], [ Console::ansiFormat('test', [Console::NEGATIVE]), - 'test' + 'test', ], [ Console::ansiFormat('test', [Console::CONCEALED]), - 'test' + 'test', ], ]; } diff --git a/tests/framework/helpers/FallbackInflector.php b/tests/framework/helpers/FallbackInflector.php index 0eff0e9..f9ab341 100644 --- a/tests/framework/helpers/FallbackInflector.php +++ b/tests/framework/helpers/FallbackInflector.php @@ -1,9 +1,12 @@ testFilePath . DIRECTORY_SEPARATOR . 'test_chmod'; mkdir($dir); chmod($dir, 0700); - if ($this->getMode($dir) !== "0700") { - /** + if ($this->getMode($dir) !== '0700') { + /* * Chmod returns true but fileperms does not reflect this. * This happens on remote file systems, also has been seen in vagrant mounts. */ @@ -142,7 +148,6 @@ class FileHelperTest extends TestCase $dirName = $basePath . DIRECTORY_SEPARATOR . 'test_dir_perms'; $this->assertTrue(FileHelper::createDirectory($dirName, 0700, false)); $this->assertFileMode(0700, $dirName); - } /** @@ -156,7 +161,7 @@ class FileHelperTest extends TestCase 'file2.txt' => 'file 2 content', ]; $this->createFileStructure([ - $srcDirName => $files + $srcDirName => $files, ]); $basePath = $this->testFilePath; @@ -188,7 +193,7 @@ class FileHelperTest extends TestCase 'file5.txt' => 'file 5 content', ]; $this->createFileStructure([ - $srcDirName => $structure + $srcDirName => $structure, ]); $basePath = $this->testFilePath; @@ -229,7 +234,7 @@ class FileHelperTest extends TestCase 'file5.txt' => 'file 5 content', ]; $this->createFileStructure([ - $srcDirName => $structure + $srcDirName => $structure, ]); $basePath = $this->testFilePath; @@ -312,7 +317,7 @@ class FileHelperTest extends TestCase { $this->createFileStructure([ 'data' => [], - 'backup' => ['data' => []] + 'backup' => ['data' => []], ]); $this->expectException('yii\base\InvalidParamException'); @@ -330,14 +335,14 @@ class FileHelperTest extends TestCase { $this->createFileStructure([ 'data' => [], - 'backup' => ['data' => []] + 'backup' => ['data' => []], ]); FileHelper::copyDirectory( $this->testFilePath . DIRECTORY_SEPARATOR . 'data', $this->testFilePath . DIRECTORY_SEPARATOR . 'backup' . DIRECTORY_SEPARATOR . 'data' ); - $this->assertTrue(file_exists($this->testFilePath . DIRECTORY_SEPARATOR . 'backup' . DIRECTORY_SEPARATOR . 'data')); + $this->assertFileExists($this->testFilePath . DIRECTORY_SEPARATOR . 'backup' . DIRECTORY_SEPARATOR . 'data'); } /** @@ -347,7 +352,7 @@ class FileHelperTest extends TestCase { $this->createFileStructure([ 'data' => [], - 'data-backup' => [] + 'data-backup' => [], ]); FileHelper::copyDirectory( @@ -392,7 +397,7 @@ class FileHelperTest extends TestCase $dirName => [ 'file' => 'Symlinked file.', 'directory' => [ - 'standard-file-1' => 'Standard file 1.' + 'standard-file-1' => 'Standard file 1.', ], 'symlinks' => [ 'standard-file-2' => 'Standard file 2.', @@ -435,7 +440,7 @@ class FileHelperTest extends TestCase $dirName => [ 'file' => 'Symlinked file.', 'directory' => [ - 'standard-file-1' => 'Standard file 1.' + 'standard-file-1' => 'Standard file 1.', ], 'symlinks' => [ 'standard-file-2' => 'Standard file 2.', @@ -514,7 +519,7 @@ class FileHelperTest extends TestCase $options = [ 'filter' => function ($path) use ($passedFileName) { return $passedFileName == basename($path); - } + }, ]; $foundFiles = FileHelper::findFiles($dirName, $options); $this->assertEquals([$dirName . DIRECTORY_SEPARATOR . $passedFileName], $foundFiles); @@ -561,7 +566,7 @@ class FileHelperTest extends TestCase 'file2' => 'def', ], 'symDir' => ['symlink', 'theDir'], - 'file3' => 'root' + 'file3' => 'root', ], ]); $dirName = $this->testFilePath . DIRECTORY_SEPARATOR . $dirName; @@ -609,7 +614,7 @@ class FileHelperTest extends TestCase $foundFiles = FileHelper::findFiles($basePath, ['except' => ['a.[2-8]']]); sort($foundFiles); $expect = array_values(array_filter($flat, function ($p) { - return substr($p, -3)==='a.1'; + return substr($p, -3) === 'a.1'; })); $this->assertEquals($expect, $foundFiles); @@ -617,7 +622,7 @@ class FileHelperTest extends TestCase $foundFiles = FileHelper::findFiles($basePath, ['except' => ['*.1']]); sort($foundFiles); $expect = array_values(array_filter($flat, function ($p) { - return substr($p, -3)!=='a.1'; + return substr($p, -3) !== 'a.1'; })); $this->assertEquals($expect, $foundFiles); @@ -625,7 +630,7 @@ class FileHelperTest extends TestCase $foundFiles = FileHelper::findFiles($basePath, ['except' => ['/one']]); sort($foundFiles); $expect = array_values(array_filter($flat, function ($p) { - return strpos($p, DIRECTORY_SEPARATOR.'one')===false; + return strpos($p, DIRECTORY_SEPARATOR . 'one') === false; })); $this->assertEquals($expect, $foundFiles); @@ -633,9 +638,9 @@ class FileHelperTest extends TestCase $foundFiles = FileHelper::findFiles($basePath, ['except' => ['?*/a.1']]); sort($foundFiles); $expect = array_values(array_filter($flat, function ($p) { - return substr($p, -11, 10)==='one'.DIRECTORY_SEPARATOR.'two'.DIRECTORY_SEPARATOR.'a.' || ( - substr($p, -8)!==DIRECTORY_SEPARATOR.'one'.DIRECTORY_SEPARATOR.'a.1' && - substr($p, -10)!==DIRECTORY_SEPARATOR.'three'.DIRECTORY_SEPARATOR.'a.1' + return substr($p, -11, 10) === 'one' . DIRECTORY_SEPARATOR . 'two' . DIRECTORY_SEPARATOR . 'a.' || ( + substr($p, -8) !== DIRECTORY_SEPARATOR . 'one' . DIRECTORY_SEPARATOR . 'a.1' && + substr($p, -10) !== DIRECTORY_SEPARATOR . 'three' . DIRECTORY_SEPARATOR . 'a.1' ); })); $this->assertEquals($expect, $foundFiles); @@ -658,14 +663,14 @@ class FileHelperTest extends TestCase $options = [ 'except' => ['*.txt'], - 'caseSensitive' => false + 'caseSensitive' => false, ]; $foundFiles = FileHelper::findFiles($dirName, $options); $this->assertCount(0, $foundFiles); $options = [ 'only' => ['*.txt'], - 'caseSensitive' => false + 'caseSensitive' => false, ]; $foundFiles = FileHelper::findFiles($dirName, $options); $this->assertCount(2, $foundFiles); @@ -710,15 +715,15 @@ class FileHelperTest extends TestCase $this->assertEquals("{$ds}b{$ds}c", FileHelper::normalizePath('/a/../b/c')); $this->assertEquals("{$ds}c", FileHelper::normalizePath('/a\\b/../..///c')); $this->assertEquals("{$ds}c", FileHelper::normalizePath('/a/.\\b//../../c')); - $this->assertEquals("c", FileHelper::normalizePath('/a/.\\b/../..//../c')); + $this->assertEquals('c', FileHelper::normalizePath('/a/.\\b/../..//../c')); $this->assertEquals("..{$ds}c", FileHelper::normalizePath('//a/.\\b//..//..//../../c')); // relative paths - $this->assertEquals(".", FileHelper::normalizePath('.')); - $this->assertEquals(".", FileHelper::normalizePath('./')); - $this->assertEquals("a", FileHelper::normalizePath('.\\a')); + $this->assertEquals('.', FileHelper::normalizePath('.')); + $this->assertEquals('.', FileHelper::normalizePath('./')); + $this->assertEquals('a', FileHelper::normalizePath('.\\a')); $this->assertEquals("a{$ds}b", FileHelper::normalizePath('./a\\b')); - $this->assertEquals(".", FileHelper::normalizePath('./a\\../')); + $this->assertEquals('.', FileHelper::normalizePath('./a\\../')); $this->assertEquals("..{$ds}..{$ds}a", FileHelper::normalizePath('../..\\a')); $this->assertEquals("..{$ds}..{$ds}a", FileHelper::normalizePath('../..\\a/../a')); $this->assertEquals("..{$ds}..{$ds}b", FileHelper::normalizePath('../..\\a/../b')); @@ -771,7 +776,7 @@ class FileHelperTest extends TestCase 'file2.dat' => 'data file 2 content', ]; $this->createFileStructure([ - $srcDirName => array_merge($textFiles, $dataFiles) + $srcDirName => array_merge($textFiles, $dataFiles), ]); $basePath = $this->testFilePath; diff --git a/tests/framework/helpers/FormatConverterTest.php b/tests/framework/helpers/FormatConverterTest.php index 0b3dcbf..fe193ec 100644 --- a/tests/framework/helpers/FormatConverterTest.php +++ b/tests/framework/helpers/FormatConverterTest.php @@ -1,4 +1,9 @@ assertEquals("a<>&"'�", Html::encode("a<>&\"'\x80")); + $this->assertEquals('a<>&"'�', Html::encode("a<>&\"'\x80")); $this->assertEquals('Sam & Dark', Html::encode('Sam & Dark')); } public function testDecode() { - $this->assertEquals("a<>&\"'", Html::decode("a<>&"'")); + $this->assertEquals("a<>&\"'", Html::decode('a<>&"'')); } public function testTag() @@ -113,7 +118,7 @@ class HtmlTest extends TestCase ]); $this->assertEquals('', Html::csrfMetaTags()); } - + public function testCsrfMetaTagsEnableCsrfValidation() { $this->mockApplication([ @@ -132,7 +137,7 @@ class HtmlTest extends TestCase $actual = Html::csrfMetaTags(); $this->assertStringMatchesFormat($pattern, $actual); } - + public function testCsrfMetaTagsEnableCsrfValidationWithoutCookieValidationKey() { $request = $this->getMock('yii\\web\\Request'); @@ -145,7 +150,7 @@ class HtmlTest extends TestCase /** * @dataProvider dataProviderBeginFormSimulateViaPost - * + * * @param string $expected * @param string $method */ @@ -162,12 +167,12 @@ class HtmlTest extends TestCase public function dataProviderBeginFormSimulateViaPost() { return [ - ['
    ', 'GET'], - ['', 'POST'], - ['%A', 'DELETE'], - ['%A', 'GETFOO'], - ['%A', 'POSTFOO'], - ['%A', 'POSTFOOPOST'], + ['', 'GET'], + ['', 'POST'], + ['%A', 'DELETE'], + ['%A', 'GETFOO'], + ['%A', 'POSTFOO'], + ['%A', 'POSTFOOPOST'], ]; } @@ -197,7 +202,7 @@ class HtmlTest extends TestCase $this->assertEquals('something', Html::a('something', '/example')); $this->assertEquals('something', Html::a('something', '')); $this->assertEquals('http://www.быстроном.рф', Html::a('http://www.быстроном.рф', 'http://www.быстроном.рф')); - $this->assertEquals('Test page', Html::a('Test page', Url::to(['/site/test'], 'https'))); + $this->assertEquals('Test page', Html::a('Test page', Url::to(['/site/test'], 'https'))); } public function testMailto() @@ -311,7 +316,7 @@ class HtmlTest extends TestCase { $this->assertEquals('', Html::button()); $this->assertEquals('', Html::button('content<>', ['name' => 'test', 'value' => 'value'])); - $this->assertEquals('', Html::button('content<>', ['type' => 'submit', 'name' => 'test', 'value' => 'value', 'class' => "t"])); + $this->assertEquals('', Html::button('content<>', ['type' => 'submit', 'name' => 'test', 'value' => 'value', 'class' => 't'])); } public function testSubmitButton() @@ -384,25 +389,25 @@ class HtmlTest extends TestCase '', 'test', null, - [] + [], ], [ '', 'test', 'value<>', - ['class' => 't'] + ['class' => 't'], ], [ '', 'test', 'value<>', - [] + [], ], [ '', 'test', 'value<>', - ['doubleEncode' => false] + ['doubleEncode' => false], ], ]; } @@ -425,7 +430,7 @@ class HtmlTest extends TestCase 'class' => 'a', 'value' => null, 'label' => 'ccc', - 'labelOptions' => ['class' =>'bbb'], + 'labelOptions' => ['class' => 'bbb'], ])); $this->assertEquals('', Html::radio('test', true, [ 'class' => 'a', @@ -445,7 +450,7 @@ class HtmlTest extends TestCase 'class' => 'a', 'value' => null, 'label' => 'ccc', - 'labelOptions' => ['class' =>'bbb'], + 'labelOptions' => ['class' => 'bbb'], ])); $this->assertEquals('', Html::checkbox('test', true, [ 'class' => 'a', @@ -493,7 +498,7 @@ EOD; EOD; $this->assertEqualsWithoutLE($expected, Html::dropDownList('test', null, $this->getDataItems(), [ 'options' => [ - 'value2' => ['selected' => true] + 'value2' => ['selected' => true], ], ])); @@ -620,7 +625,7 @@ EOD; $this->assertEqualsWithoutLE($expected, Html::checkboxList('test', ['value2'], $this->getDataItems(), [ 'item' => function ($index, $label, $name, $checked, $value) { return $index . Html::label($label . ' ' . Html::checkbox($name, $checked, ['value' => $value])); - } + }, ])); $expected = << function ($index, $label, $name, $checked, $value) { return $index . Html::label($label . ' ' . Html::checkbox($name, $checked, ['value' => $value])); }, - 'tag' => false + 'tag' => false, ])); @@ -639,9 +644,8 @@ EOD; 'item' => function ($index, $label, $name, $checked, $value) { return $index . Html::label($label . ' ' . Html::checkbox($name, $checked, ['value' => $value])); }, - 'tag' => false + 'tag' => false, ])); - } public function testRadioList() @@ -676,7 +680,7 @@ EOD; $this->assertEqualsWithoutLE($expected, Html::radioList('test', ['value2'], $this->getDataItems(), [ 'item' => function ($index, $label, $name, $checked, $value) { return $index . Html::label($label . ' ' . Html::radio($name, $checked, ['value' => $value])); - } + }, ])); $expected = << function ($index, $label, $name, $checked, $value) { return $index . Html::label($label . ' ' . Html::radio($name, $checked, ['value' => $value])); }, - 'tag' => false + 'tag' => false, ])); $this->assertEqualsWithoutLE($expected, Html::radioList('test', new \ArrayObject(['value2']), $this->getDataItems(), [ 'item' => function ($index, $label, $name, $checked, $value) { return $index . Html::label($label . ' ' . Html::radio($name, $checked, ['value' => $value])); }, - 'tag' => false + 'tag' => false, ])); } @@ -722,7 +726,7 @@ EOD; 'class' => 'test', 'item' => function ($item, $index) { return "
  • $item
  • "; - } + }, ])); $this->assertEquals('
      ', Html::ul([], ['class' => 'test'])); @@ -756,7 +760,7 @@ EOD; 'class' => 'test', 'item' => function ($item, $index) { return "
    • $item
    • "; - } + }, ])); $this->assertEquals('
        ', Html::ol([], ['class' => 'test'])); @@ -872,7 +876,7 @@ EOD; $this->assertEquals(['class' => 'test test2 test3'], $options); $options = [ - 'class' => ['test'] + 'class' => ['test'], ]; Html::addCssClass($options, 'test2'); $this->assertEquals(['class' => ['test', 'test2']], $options); @@ -882,7 +886,7 @@ EOD; $this->assertEquals(['class' => ['test', 'test2', 'test3']], $options); $options = [ - 'class' => 'test' + 'class' => 'test', ]; Html::addCssClass($options, ['test1', 'test2']); $this->assertEquals(['class' => 'test test1 test2'], $options); @@ -895,8 +899,8 @@ EOD; { $options = [ 'class' => [ - 'persistent' => 'test1' - ] + 'persistent' => 'test1', + ], ]; Html::addCssClass($options, ['persistent' => 'test2']); $this->assertEquals(['persistent' => 'test1'], $options['class']); @@ -924,7 +928,7 @@ EOD; $this->assertEquals([], $options); $options = [ - 'class' => 'test test1 test2' + 'class' => 'test test1 test2', ]; Html::removeCssClass($options, ['test1', 'test2']); $this->assertEquals(['class' => 'test'], $options); @@ -972,7 +976,7 @@ EOD; $options = [ 'style' => [ - 'width' => '100px' + 'width' => '100px', ], ]; Html::addCssStyle($options, ['color' => 'red'], false); @@ -1048,14 +1052,14 @@ EOD; [ '', [ - 'maxlength' => true + 'maxlength' => true, ], '', ], [ '', [ - 'maxlength' => 99 + 'maxlength' => 99, ], '', ], @@ -1091,14 +1095,14 @@ EOD; [ '', [ - 'maxlength' => true + 'maxlength' => true, ], '', ], [ '', [ - 'maxlength' => 99 + 'maxlength' => 99, ], '', ], @@ -1125,7 +1129,7 @@ EOD; [ 'ok', [], - '

        Please fix the following errors:

          ' + '

          Please fix the following errors:

            ', ], [ 'ok', @@ -1135,43 +1139,46 @@ EOD; [ str_repeat('long_string', 60), [], - '

            Please fix the following errors:

            • Name should contain at most 100 characters.
            ' + '

            Please fix the following errors:

            • Name should contain at most 100 characters.
            ', ], [ 'not_an_integer', [], '

            Please fix the following errors:

            • Error message. Here are some chars: < >
            ', - function ($model) { /** @var $model DynamicModel */ + function ($model) { + /* @var $model DynamicModel */ $model->addError('name', 'Error message. Here are some chars: < >'); - } + }, ], [ 'not_an_integer', ['encode' => false], '

            Please fix the following errors:

            • Error message. Here are some chars: < >
            ', - function ($model) { /** @var $model DynamicModel */ + function ($model) { + /* @var $model DynamicModel */ $model->addError('name', 'Error message. Here are some chars: < >'); - } + }, ], [ str_repeat('long_string', 60), [], '

            Please fix the following errors:

            • Error message. Here are some chars: < >
            ', - function ($model) { /** @var $model DynamicModel */ + function ($model) { + /* @var $model DynamicModel */ $model->addError('name', 'Error message. Here are some chars: < >'); - } + }, ], [ 'not_an_integer', ['showAllErrors' => true], '

            Please fix the following errors:

            • Error message. Here are some chars: < >
            • Error message. Here are even more chars: ""
            ', - function ($model) { /** @var $model DynamicModel */ + function ($model) { + /* @var $model DynamicModel */ $model->addError('name', 'Error message. Here are some chars: < >'); $model->addError('name', 'Error message. Here are even more chars: ""'); - } + }, ], - ]; } @@ -1210,21 +1217,21 @@ EOD; [ 'some text', [ - 'maxlength' => true + 'maxlength' => true, ], '', ], [ 'some text', [ - 'maxlength' => 99 + 'maxlength' => 99, ], '', ], [ 'some text', [ - 'value' => 'override text' + 'value' => 'override text', ], '', ], @@ -1263,7 +1270,7 @@ EOD; $noCsrfForm = Html::beginForm('/index.php', 'post', ['csrf' => false, 'id' => 'myform']); $this->assertEquals('', $noCsrfForm); } - + /** * Data provider for [[testActiveRadio()]] * @return array test data @@ -1274,26 +1281,26 @@ EOD; [ true, [], - '' + '', ], [ true, ['uncheck' => false], - '' + '', ], [ true, ['label' => false], - '' + '', ], [ true, ['uncheck' => false, 'label' => false], - '' + '', ], ]; } - + /** * @dataProvider dataProviderActiveRadio * @@ -1307,7 +1314,7 @@ EOD; $model->radio = $value; $this->assertEquals($expectedHtml, Html::activeRadio($model, 'radio', $options)); } - + /** * Data provider for [[testActiveCheckbox()]] * @return array test data @@ -1318,26 +1325,26 @@ EOD; [ true, [], - '' + '', ], [ true, ['uncheck' => false], - '' + '', ], [ true, ['label' => false], - '' + '', ], [ true, ['uncheck' => false, 'label' => false], - '' + '', ], ]; } - + /** * @dataProvider dataProviderActiveCheckbox * @@ -1359,22 +1366,22 @@ EOD; public function validAttributeNamesProvider() { return [ - ["asd]asdf.asdfa[asdfa", "asdf.asdfa"], - ["a", "a"], - ["[0]a", "a"], - ["a[0]", "a"], - ["[0]a[0]", "a"], - ["[0]a.[0]", "a."], + ['asd]asdf.asdfa[asdfa', 'asdf.asdfa'], + ['a', 'a'], + ['[0]a', 'a'], + ['a[0]', 'a'], + ['[0]a[0]', 'a'], + ['[0]a.[0]', 'a.'], // Unicode checks. - ["ä", "ä"], - ["ä", "ä"], - ["asdf]öáöio..[asdfasdf", "öáöio.."], - ["öáöio", "öáöio"], - ["[0]test.ööößß.d", "test.ööößß.d"], - ["ИІК", "ИІК"], - ["]ИІК[", "ИІК"], - ["[0]ИІК[0]", "ИІК"] + ['ä', 'ä'], + ['ä', 'ä'], + ['asdf]öáöio..[asdfasdf', 'öáöio..'], + ['öáöio', 'öáöio'], + ['[0]test.ööößß.d', 'test.ööößß.d'], + ['ИІК', 'ИІК'], + [']ИІК[', 'ИІК'], + ['[0]ИІК[0]', 'ИІК'], ]; } @@ -1387,7 +1394,7 @@ EOD; return [ ['. ..'], ['a +b'], - ['a,b'] + ['a,b'], ]; } @@ -1406,7 +1413,7 @@ EOD; $this->assertEquals($expected, Html::getAttributeName($name)); } } - + /** * @dataProvider invalidAttributeNamesProvider * @@ -1439,19 +1446,19 @@ EOD; public function testGetAttributeValue() { $model = new HtmlTestModel(); - + $expected = null; $actual = Html::getAttributeValue($model, 'types'); $this->assertSame($expected, $actual); - + $activeRecord = $this->getMock('yii\\db\\ActiveRecordInterface'); $activeRecord->method('getPrimaryKey')->willReturn(1); $model->types = $activeRecord; - + $expected = 1; $actual = Html::getAttributeValue($model, 'types'); $this->assertSame($expected, $actual); - + $model->types = [ $activeRecord, ]; diff --git a/tests/framework/helpers/InflectorTest.php b/tests/framework/helpers/InflectorTest.php index 2408ba1..75a5087 100644 --- a/tests/framework/helpers/InflectorTest.php +++ b/tests/framework/helpers/InflectorTest.php @@ -1,4 +1,9 @@ assertEquals("Me my self and i", Inflector::titleize('MeMySelfAndI')); - $this->assertEquals("Me My Self And I", Inflector::titleize('MeMySelfAndI', true)); + $this->assertEquals('Me my self and i', Inflector::titleize('MeMySelfAndI')); + $this->assertEquals('Me My Self And I', Inflector::titleize('MeMySelfAndI', true)); } public function testCamelize() { - $this->assertEquals("MeMySelfAndI", Inflector::camelize('me my_self-andI')); - $this->assertEquals("QweQweEwq", Inflector::camelize('qwe qwe^ewq')); + $this->assertEquals('MeMySelfAndI', Inflector::camelize('me my_self-andI')); + $this->assertEquals('QweQweEwq', Inflector::camelize('qwe qwe^ewq')); } public function testUnderscore() { - $this->assertEquals("me_my_self_and_i", Inflector::underscore('MeMySelfAndI')); + $this->assertEquals('me_my_self_and_i', Inflector::underscore('MeMySelfAndI')); } public function testCamel2words() @@ -128,18 +133,18 @@ class InflectorTest extends TestCase public function testHumanize() { - $this->assertEquals("Me my self and i", Inflector::humanize('me_my_self_and_i')); - $this->assertEquals("Me My Self And I", Inflector::humanize('me_my_self_and_i', true)); + $this->assertEquals('Me my self and i', Inflector::humanize('me_my_self_and_i')); + $this->assertEquals('Me My Self And I', Inflector::humanize('me_my_self_and_i', true)); } public function testVariablize() { - $this->assertEquals("customerTable", Inflector::variablize('customer_table')); + $this->assertEquals('customerTable', Inflector::variablize('customer_table')); } public function testTableize() { - $this->assertEquals("customer_tables", Inflector::tableize('customerTable')); + $this->assertEquals('customer_tables', Inflector::tableize('customerTable')); } public function testSlugCommons() @@ -340,7 +345,7 @@ class InflectorTest extends TestCase public function testClassify() { - $this->assertEquals("CustomerTable", Inflector::classify('customer_tables')); + $this->assertEquals('CustomerTable', Inflector::classify('customer_tables')); } public function testOrdinalize() diff --git a/tests/framework/helpers/JsonTest.php b/tests/framework/helpers/JsonTest.php index 4222a3a..a50ae03 100644 --- a/tests/framework/helpers/JsonTest.php +++ b/tests/framework/helpers/JsonTest.php @@ -1,13 +1,18 @@ method('toArray')->willReturn([]); $actual = Json::encode($dataArrayable); $this->assertSame('{}', $actual); - + // basic data encoding $data = '1'; $this->assertSame('"1"', Json::encode($data)); @@ -62,7 +67,7 @@ class JsonTest extends TestCase $expression2 = 'function (b) {}'; $data = [ 'a' => [ - 1, new JsExpression($expression1) + 1, new JsExpression($expression1), ], 'b' => new JsExpression($expression2), ]; @@ -116,14 +121,14 @@ class JsonTest extends TestCase $expression2 = 'function (b) {}'; $data = [ 'a' => [ - 1, new JsExpression($expression1) + 1, new JsExpression($expression1), ], 'b' => new JsExpression($expression2), ]; $this->assertSame("{\"a\":[1,$expression1],\"b\":$expression2}", Json::htmlEncode($data)); // https://github.com/yiisoft/yii2/issues/957 - $data = (object)null; + $data = (object) null; $this->assertSame('{}', Json::htmlEncode($data)); // JsonSerializable @@ -169,8 +174,7 @@ class JsonTest extends TestCase $this->expectException('yii\base\InvalidParamException'); Json::decode($json); } - - + /** * @expectedException \yii\base\InvalidParamException * @expectedExceptionMessage Invalid JSON data. @@ -210,7 +214,7 @@ class JsonModel extends Model implements \JsonSerializable { public $data = ['json' => 'serializable']; - function jsonSerialize() + public function jsonSerialize() { return $this->data; } diff --git a/tests/framework/helpers/MarkdownTest.php b/tests/framework/helpers/MarkdownTest.php index 847884f..cc2a679 100644 --- a/tests/framework/helpers/MarkdownTest.php +++ b/tests/framework/helpers/MarkdownTest.php @@ -1,9 +1,15 @@ assertEquals('abcdef', StringHelper::byteSubstr('abcdef', 0)); $this->assertEquals('abcdef', StringHelper::byteSubstr('abcdef', 0, null)); - $this->assertEquals('de', StringHelper::byteSubstr('abcdef', 3, 2)); - $this->assertEquals('def', StringHelper::byteSubstr('abcdef', 3)); - $this->assertEquals('def', StringHelper::byteSubstr('abcdef', 3, null)); + $this->assertEquals('de', StringHelper::byteSubstr('abcdef', 3, 2)); + $this->assertEquals('def', StringHelper::byteSubstr('abcdef', 3)); + $this->assertEquals('def', StringHelper::byteSubstr('abcdef', 3, null)); - $this->assertEquals('cd', StringHelper::byteSubstr('abcdef', -4, 2)); - $this->assertEquals('cdef', StringHelper::byteSubstr('abcdef', -4)); - $this->assertEquals('cdef', StringHelper::byteSubstr('abcdef', -4, null)); + $this->assertEquals('cd', StringHelper::byteSubstr('abcdef', -4, 2)); + $this->assertEquals('cdef', StringHelper::byteSubstr('abcdef', -4)); + $this->assertEquals('cdef', StringHelper::byteSubstr('abcdef', -4, null)); - $this->assertEquals('', StringHelper::byteSubstr('abcdef', 4, 0)); - $this->assertEquals('', StringHelper::byteSubstr('abcdef', -4, 0)); + $this->assertEquals('', StringHelper::byteSubstr('abcdef', 4, 0)); + $this->assertEquals('', StringHelper::byteSubstr('abcdef', -4, 0)); $this->assertEquals('это', StringHelper::byteSubstr('это', 0)); $this->assertEquals('это', StringHelper::byteSubstr('это', 0, null)); - $this->assertEquals('т', StringHelper::byteSubstr('это', 2, 2)); - $this->assertEquals('то', StringHelper::byteSubstr('это', 2)); - $this->assertEquals('то', StringHelper::byteSubstr('это', 2, null)); + $this->assertEquals('т', StringHelper::byteSubstr('это', 2, 2)); + $this->assertEquals('то', StringHelper::byteSubstr('это', 2)); + $this->assertEquals('то', StringHelper::byteSubstr('это', 2, null)); - $this->assertEquals('т', StringHelper::byteSubstr('это', -4, 2)); - $this->assertEquals('то', StringHelper::byteSubstr('это', -4)); - $this->assertEquals('то', StringHelper::byteSubstr('это', -4, null)); + $this->assertEquals('т', StringHelper::byteSubstr('это', -4, 2)); + $this->assertEquals('то', StringHelper::byteSubstr('это', -4)); + $this->assertEquals('то', StringHelper::byteSubstr('это', -4, null)); - $this->assertEquals('', StringHelper::byteSubstr('это', 4, 0)); - $this->assertEquals('', StringHelper::byteSubstr('это', -4, 0)); + $this->assertEquals('', StringHelper::byteSubstr('это', 4, 0)); + $this->assertEquals('', StringHelper::byteSubstr('это', -4, 0)); } public function testBasename() @@ -248,14 +254,14 @@ class StringHelperTest extends TestCase public function testExplode() { - $this->assertEquals(['It', 'is', 'a first', 'test'], StringHelper::explode("It, is, a first, test")); - $this->assertEquals(['It', 'is', 'a test with trimmed digits', '0', '1', '2'], StringHelper::explode("It, is, a test with trimmed digits, 0, 1, 2", ',', true, true)); - $this->assertEquals(['It', 'is', 'a second', 'test'], StringHelper::explode("It+ is+ a second+ test", '+')); - $this->assertEquals(['Save', '', '', 'empty trimmed string'], StringHelper::explode("Save, ,, empty trimmed string", ',')); - $this->assertEquals(['Здесь', 'multibyte', 'строка'], StringHelper::explode("Здесь我 multibyte我 строка", '我')); - $this->assertEquals(['Disable', ' trim ', 'here but ignore empty'], StringHelper::explode("Disable, trim ,,,here but ignore empty", ',', false, true)); - $this->assertEquals(['It/', ' is?', ' a', ' test with rtrim'], StringHelper::explode("It/, is?, a , test with rtrim", ',', 'rtrim')); - $this->assertEquals(['It', ' is', ' a ', ' test with closure'], StringHelper::explode("It/, is?, a , test with closure", ',', function ($value) { return trim($value, '/?'); })); + $this->assertEquals(['It', 'is', 'a first', 'test'], StringHelper::explode('It, is, a first, test')); + $this->assertEquals(['It', 'is', 'a test with trimmed digits', '0', '1', '2'], StringHelper::explode('It, is, a test with trimmed digits, 0, 1, 2', ',', true, true)); + $this->assertEquals(['It', 'is', 'a second', 'test'], StringHelper::explode('It+ is+ a second+ test', '+')); + $this->assertEquals(['Save', '', '', 'empty trimmed string'], StringHelper::explode('Save, ,, empty trimmed string', ',')); + $this->assertEquals(['Здесь', 'multibyte', 'строка'], StringHelper::explode('Здесь我 multibyte我 строка', '我')); + $this->assertEquals(['Disable', ' trim ', 'here but ignore empty'], StringHelper::explode('Disable, trim ,,,here but ignore empty', ',', false, true)); + $this->assertEquals(['It/', ' is?', ' a', ' test with rtrim'], StringHelper::explode('It/, is?, a , test with rtrim', ',', 'rtrim')); + $this->assertEquals(['It', ' is', ' a ', ' test with closure'], StringHelper::explode('It/, is?, a , test with closure', ',', function ($value) { return trim($value, '/?'); })); } public function testWordCount() diff --git a/tests/framework/helpers/UrlTest.php b/tests/framework/helpers/UrlTest.php index 505e70c..9db7c3c 100644 --- a/tests/framework/helpers/UrlTest.php +++ b/tests/framework/helpers/UrlTest.php @@ -1,4 +1,10 @@ 'yii\web\Request', 'scriptUrl' => '/base/index.php', 'hostInfo' => 'http://example.com/', - 'url' => '/base/index.php&r=site%2Fcurrent&id=42' + 'url' => '/base/index.php&r=site%2Fcurrent&id=42', ], 'urlManager' => [ 'class' => 'yii\web\UrlManager', diff --git a/tests/framework/helpers/VarDumperTest.php b/tests/framework/helpers/VarDumperTest.php index d2a2956..c052b58 100644 --- a/tests/framework/helpers/VarDumperTest.php +++ b/tests/framework/helpers/VarDumperTest.php @@ -1,4 +1,10 @@ assertContains("__PHP_Incomplete_Class#1\n(", $dumpResult); - $this->assertContains("nonExistingClass", $dumpResult); + $this->assertContains('nonExistingClass', $dumpResult); } public function testExportIncompleteObject() @@ -32,7 +38,7 @@ class VarDumperTest extends TestCase $serializedObj = 'O:16:"nonExistingClass":0:{}'; $incompleteObj = unserialize($serializedObj); $exportResult = VarDumper::export($incompleteObj); - $this->assertContains("nonExistingClass", $exportResult); + $this->assertContains('nonExistingClass', $exportResult); } public function testDumpObject() @@ -46,7 +52,7 @@ class VarDumperTest extends TestCase $dumpResult = VarDumper::dumpAsString($obj); $this->assertContains("stdClass#1\n(", $dumpResult); $this->assertContains("[name] => 'test-name'", $dumpResult); - $this->assertContains("[price] => 19", $dumpResult); + $this->assertContains('[price] => 19', $dumpResult); } /** @@ -60,31 +66,31 @@ class VarDumperTest extends TestCase $data = [ [ 'test string', - var_export('test string', true) + var_export('test string', true), ], [ 75, - var_export(75, true) + var_export(75, true), ], [ 7.5, - var_export(7.5, true) + var_export(7.5, true), ], [ null, - 'null' + 'null', ], [ true, - 'true' + 'true', ], [ false, - 'false' + 'false', ], [ [], - '[]' + '[]', ], ]; @@ -175,7 +181,7 @@ RESULT; $slave = new \StdClass(); $master->slave = $slave; $slave->master = $master; - $master->function = function() {return true;}; + $master->function = function () {return true;}; $exportResult = VarDumper::export($master); $this->assertNotEmpty($exportResult); diff --git a/tests/framework/i18n/DbMessageSourceTest.php b/tests/framework/i18n/DbMessageSourceTest.php index 7c254b2..8bc21e7 100644 --- a/tests/framework/i18n/DbMessageSourceTest.php +++ b/tests/framework/i18n/DbMessageSourceTest.php @@ -1,4 +1,9 @@ [ 'class' => $this->getMessageSourceClass(), 'db' => static::$db, - ] - ] + ], + ], ]); } @@ -60,7 +65,7 @@ class DbMessageSourceTest extends I18NTest ob_start(); $result = Yii::$app->runAction($route, $params); - echo "Result is " . $result; + echo 'Result is ' . $result; if ($result !== \yii\console\Controller::EXIT_CODE_NORMAL) { ob_end_flush(); } else { @@ -119,7 +124,7 @@ class DbMessageSourceTest extends I18NTest public static function getConnection() { if (static::$db == null) { - $db = new Connection; + $db = new Connection(); $db->dsn = static::$database['dsn']; if (isset(static::$database['username'])) { $db->username = static::$database['username']; diff --git a/tests/framework/i18n/FallbackMessageFormatterTest.php b/tests/framework/i18n/FallbackMessageFormatterTest.php index 4b2de7c..4281f52 100644 --- a/tests/framework/i18n/FallbackMessageFormatterTest.php +++ b/tests/framework/i18n/FallbackMessageFormatterTest.php @@ -21,11 +21,11 @@ class FallbackMessageFormatterTest extends TestCase const N_VALUE = 42; const F = 'f'; const F_VALUE = 2e+8; - const F_VALUE_FORMATTED = "200,000,000"; + const F_VALUE_FORMATTED = '200,000,000'; const D = 'd'; const D_VALUE = 200000000.101; - const D_VALUE_FORMATTED = "200,000,000.101"; - const D_VALUE_FORMATTED_INTEGER = "200,000,000"; + const D_VALUE_FORMATTED = '200,000,000.101'; + const D_VALUE_FORMATTED_INTEGER = '200,000,000'; const SUBJECT = 'сабж'; const SUBJECT_VALUE = 'Answer to the Ultimate Question of Life, the Universe, and Everything'; @@ -33,62 +33,62 @@ class FallbackMessageFormatterTest extends TestCase { return [ [ - '{'.self::SUBJECT.'} is {'.self::N.'}', // pattern - self::SUBJECT_VALUE.' is '.self::N_VALUE, // expected + '{' . self::SUBJECT . '} is {' . self::N . '}', // pattern + self::SUBJECT_VALUE . ' is ' . self::N_VALUE, // expected [ // params self::N => self::N_VALUE, self::SUBJECT => self::SUBJECT_VALUE, - ] + ], ], [ - '{'.self::SUBJECT.'} is {'.self::N.', number}', // pattern - self::SUBJECT_VALUE.' is '.self::N_VALUE, // expected + '{' . self::SUBJECT . '} is {' . self::N . ', number}', // pattern + self::SUBJECT_VALUE . ' is ' . self::N_VALUE, // expected [ // params self::N => self::N_VALUE, self::SUBJECT => self::SUBJECT_VALUE, - ] + ], ], [ - '{'.self::SUBJECT.'} is {'.self::N.', number, integer}', // pattern - self::SUBJECT_VALUE.' is '.self::N_VALUE, // expected + '{' . self::SUBJECT . '} is {' . self::N . ', number, integer}', // pattern + self::SUBJECT_VALUE . ' is ' . self::N_VALUE, // expected [ // params self::N => self::N_VALUE, self::SUBJECT => self::SUBJECT_VALUE, - ] + ], ], [ - 'Here is a big number: {'.self::F.', number}', // pattern - 'Here is a big number: '.self::F_VALUE_FORMATTED, // expected + 'Here is a big number: {' . self::F . ', number}', // pattern + 'Here is a big number: ' . self::F_VALUE_FORMATTED, // expected [ // params - self::F => self::F_VALUE - ] + self::F => self::F_VALUE, + ], ], [ - 'Here is a big number: {'.self::F.', number, integer}', // pattern - 'Here is a big number: '.self::F_VALUE_FORMATTED, // expected + 'Here is a big number: {' . self::F . ', number, integer}', // pattern + 'Here is a big number: ' . self::F_VALUE_FORMATTED, // expected [ // params - self::F => self::F_VALUE - ] + self::F => self::F_VALUE, + ], ], [ - 'Here is a big number: {'.self::D.', number}', // pattern - 'Here is a big number: '.self::D_VALUE_FORMATTED, // expected + 'Here is a big number: {' . self::D . ', number}', // pattern + 'Here is a big number: ' . self::D_VALUE_FORMATTED, // expected [ // params - self::D => self::D_VALUE - ] + self::D => self::D_VALUE, + ], ], [ - 'Here is a big number: {'.self::D.', number, integer}', // pattern - 'Here is a big number: '.self::D_VALUE_FORMATTED_INTEGER, // expected + 'Here is a big number: {' . self::D . ', number, integer}', // pattern + 'Here is a big number: ' . self::D_VALUE_FORMATTED_INTEGER, // expected [ // params - self::D => self::D_VALUE - ] + self::D => self::D_VALUE, + ], ], // This one was provided by Aura.Intl. Thanks! @@ -116,8 +116,8 @@ _MSG_ 'gender_of_host' => 'male', 'num_guests' => 4, 'host' => 'ralph', - 'guest' => 'beep' - ] + 'guest' => 'beep', + ], ], [ @@ -140,7 +140,7 @@ _MSG_ 'he' => 'wtf', 'she' => 'wtf', 'it' => 'wtf', - ] + ], ], // verify pattern in select message gets replaced @@ -188,10 +188,10 @@ _MSG_ public function testInsufficientArguments() { - $expected = '{'.self::SUBJECT.'} is '.self::N_VALUE; + $expected = '{' . self::SUBJECT . '} is ' . self::N_VALUE; $formatter = new FallbackMessageFormatter(); - $result = $formatter->fallbackFormat('{'.self::SUBJECT.'} is {'.self::N.'}', [ + $result = $formatter->fallbackFormat('{' . self::SUBJECT . '} is {' . self::N . '}', [ self::N => self::N_VALUE, ], 'en-US'); @@ -200,7 +200,7 @@ _MSG_ public function testNoParams() { - $pattern = '{'.self::SUBJECT.'} is '.self::N; + $pattern = '{' . self::SUBJECT . '} is ' . self::N; $formatter = new FallbackMessageFormatter(); $result = $formatter->fallbackFormat($pattern, [], 'en-US'); @@ -217,7 +217,7 @@ _MSG_ public function testUnsupportedPercentException() { - $pattern = 'Number {'.self::N.', number, percent}'; + $pattern = 'Number {' . self::N . ', number, percent}'; $formatter = new FallbackMessageFormatter(); $this->expectException('yii\base\NotSupportedException'); $formatter->fallbackFormat($pattern, [self::N => self::N_VALUE], 'en-US'); @@ -225,7 +225,7 @@ _MSG_ public function testUnsupportedCurrencyException() { - $pattern = 'Number {'.self::N.', number, currency}'; + $pattern = 'Number {' . self::N . ', number, currency}'; $formatter = new FallbackMessageFormatter(); $this->expectException('yii\base\NotSupportedException'); $formatter->fallbackFormat($pattern, [self::N => self::N_VALUE], 'en-US'); diff --git a/tests/framework/i18n/FormatterDateTest.php b/tests/framework/i18n/FormatterDateTest.php index 359f8de..509f27d 100644 --- a/tests/framework/i18n/FormatterDateTest.php +++ b/tests/framework/i18n/FormatterDateTest.php @@ -1,11 +1,16 @@ assertSame("$value", $this->formatter->asTimestamp(date('Y-m-d H:i:s', $value))); // empty input - $this->assertSame("0", $this->formatter->asTimestamp(0)); - $this->assertSame("0", $this->formatter->asTimestamp(false)); - $this->assertSame("0", $this->formatter->asTimestamp("")); + $this->assertSame('0', $this->formatter->asTimestamp(0)); + $this->assertSame('0', $this->formatter->asTimestamp(false)); + $this->assertSame('0', $this->formatter->asTimestamp('')); // null display $this->assertSame($this->formatter->nullDisplay, $this->formatter->asTimestamp(null)); @@ -277,18 +282,18 @@ class FormatterDateTest extends TestCase public function testAsRelativeTime() { - $interval_1_second = new DateInterval("PT1S"); - $interval_244_seconds = new DateInterval("PT244S"); - $interval_1_minute = new DateInterval("PT1M"); - $interval_33_minutes = new DateInterval("PT33M"); - $interval_1_hour = new DateInterval("PT1H"); - $interval_6_hours = new DateInterval("PT6H"); - $interval_1_day = new DateInterval("P1D"); - $interval_89_days = new DateInterval("P89D"); - $interval_1_month = new DateInterval("P1M"); - $interval_5_months = new DateInterval("P5M"); - $interval_1_year = new DateInterval("P1Y"); - $interval_12_years = new DateInterval("P12Y"); + $interval_1_second = new DateInterval('PT1S'); + $interval_244_seconds = new DateInterval('PT244S'); + $interval_1_minute = new DateInterval('PT1M'); + $interval_33_minutes = new DateInterval('PT33M'); + $interval_1_hour = new DateInterval('PT1H'); + $interval_6_hours = new DateInterval('PT6H'); + $interval_1_day = new DateInterval('P1D'); + $interval_89_days = new DateInterval('P89D'); + $interval_1_month = new DateInterval('P1M'); + $interval_5_months = new DateInterval('P5M'); + $interval_1_year = new DateInterval('P1Y'); + $interval_12_years = new DateInterval('P12Y'); // Pass a DateInterval $this->assertSame('a second ago', $this->formatter->asRelativeTime($interval_1_second)); @@ -389,12 +394,12 @@ class FormatterDateTest extends TestCase $this->assertSame('in 28 days', $this->formatter->asRelativeTime($dateThen, $dateNow)); // just now - $this->assertSame("just now", $this->formatter->asRelativeTime($t = time(), $t)); - $this->assertSame("just now", $this->formatter->asRelativeTime(0, 0)); + $this->assertSame('just now', $this->formatter->asRelativeTime($t = time(), $t)); + $this->assertSame('just now', $this->formatter->asRelativeTime(0, 0)); // empty input - $this->assertSame("just now", $this->formatter->asRelativeTime(false, 0)); - $this->assertSame("just now", $this->formatter->asRelativeTime("", 0)); + $this->assertSame('just now', $this->formatter->asRelativeTime(false, 0)); + $this->assertSame('just now', $this->formatter->asRelativeTime('', 0)); // null display $this->assertSame($this->formatter->nullDisplay, $this->formatter->asRelativeTime(null)); @@ -408,19 +413,19 @@ class FormatterDateTest extends TestCase public function testAsDuration() { - $interval_0_seconds = new DateInterval("PT0S"); - $interval_1_second = new DateInterval("PT1S"); - $interval_244_seconds = new DateInterval("PT244S"); - $interval_1_minute = new DateInterval("PT1M"); - $interval_33_minutes = new DateInterval("PT33M"); - $interval_1_hour = new DateInterval("PT1H"); - $interval_6_hours = new DateInterval("PT6H"); - $interval_1_day = new DateInterval("P1D"); - $interval_89_days = new DateInterval("P89D"); - $interval_1_month = new DateInterval("P1M"); - $interval_5_months = new DateInterval("P5M"); - $interval_1_year = new DateInterval("P1Y"); - $interval_12_years = new DateInterval("P12Y"); + $interval_0_seconds = new DateInterval('PT0S'); + $interval_1_second = new DateInterval('PT1S'); + $interval_244_seconds = new DateInterval('PT244S'); + $interval_1_minute = new DateInterval('PT1M'); + $interval_33_minutes = new DateInterval('PT33M'); + $interval_1_hour = new DateInterval('PT1H'); + $interval_6_hours = new DateInterval('PT6H'); + $interval_1_day = new DateInterval('P1D'); + $interval_89_days = new DateInterval('P89D'); + $interval_1_month = new DateInterval('P1M'); + $interval_5_months = new DateInterval('P5M'); + $interval_1_year = new DateInterval('P1Y'); + $interval_12_years = new DateInterval('P12Y'); // Pass a DateInterval $this->assertSame('0 seconds', $this->formatter->asDuration($interval_0_seconds)); @@ -803,7 +808,5 @@ class FormatterDateTest extends TestCase $this->assertEquals('1924-08-17 00:00:00+0000', $this->formatter->asDateTime($timeStamp, 'yyyy-MM-dd HH:mm:ssZ')); $this->formatter->timeZone = 'Europe/Berlin'; $this->assertEquals('1924-08-17 01:00:00+0100', $this->formatter->asDateTime($timeStamp, 'yyyy-MM-dd HH:mm:ssZ')); - } - } diff --git a/tests/framework/i18n/FormatterNumberTest.php b/tests/framework/i18n/FormatterNumberTest.php index 9be3016..000ae85 100644 --- a/tests/framework/i18n/FormatterNumberTest.php +++ b/tests/framework/i18n/FormatterNumberTest.php @@ -1,10 +1,15 @@ assertSame("123", $this->formatter->asInteger(123)); - $this->assertSame("123", $this->formatter->asInteger(123.23)); - $this->assertSame("123", $this->formatter->asInteger(123.53)); - $this->assertSame("0", $this->formatter->asInteger(0)); - $this->assertSame("-123", $this->formatter->asInteger(-123.23)); - $this->assertSame("-123", $this->formatter->asInteger(-123.53)); + $this->assertSame('123', $this->formatter->asInteger(123)); + $this->assertSame('123', $this->formatter->asInteger(123.23)); + $this->assertSame('123', $this->formatter->asInteger(123.53)); + $this->assertSame('0', $this->formatter->asInteger(0)); + $this->assertSame('-123', $this->formatter->asInteger(-123.23)); + $this->assertSame('-123', $this->formatter->asInteger(-123.53)); - $this->assertSame("123,456", $this->formatter->asInteger(123456)); - $this->assertSame("123,456", $this->formatter->asInteger(123456.789)); + $this->assertSame('123,456', $this->formatter->asInteger(123456)); + $this->assertSame('123,456', $this->formatter->asInteger(123456.789)); // empty input - $this->assertSame("0", $this->formatter->asInteger(false)); - $this->assertSame("0", $this->formatter->asInteger("")); + $this->assertSame('0', $this->formatter->asInteger(false)); + $this->assertSame('0', $this->formatter->asInteger('')); // null display $this->assertSame($this->formatter->nullDisplay, $this->formatter->asInteger(null)); @@ -122,41 +127,41 @@ class FormatterNumberTest extends TestCase public function testIntlAsDecimal() { $value = 123.12; - $this->assertSame("123.12", $this->formatter->asDecimal($value, 2)); - $this->assertSame("123.1", $this->formatter->asDecimal($value, 1)); - $this->assertSame("123", $this->formatter->asDecimal($value, 0)); + $this->assertSame('123.12', $this->formatter->asDecimal($value, 2)); + $this->assertSame('123.1', $this->formatter->asDecimal($value, 1)); + $this->assertSame('123', $this->formatter->asDecimal($value, 0)); $value = 123; - $this->assertSame("123", $this->formatter->asDecimal($value)); - $this->assertSame("123.00", $this->formatter->asDecimal($value, 2)); + $this->assertSame('123', $this->formatter->asDecimal($value)); + $this->assertSame('123.00', $this->formatter->asDecimal($value, 2)); $this->formatter->decimalSeparator = ','; $this->formatter->thousandSeparator = '.'; $value = 123.12; - $this->assertSame("123,12", $this->formatter->asDecimal($value)); - $this->assertSame("123,1", $this->formatter->asDecimal($value, 1)); - $this->assertSame("123", $this->formatter->asDecimal($value, 0)); + $this->assertSame('123,12', $this->formatter->asDecimal($value)); + $this->assertSame('123,1', $this->formatter->asDecimal($value, 1)); + $this->assertSame('123', $this->formatter->asDecimal($value, 0)); $value = 123123.123; - $this->assertSame("123.123", $this->formatter->asDecimal($value, 0)); - $this->assertSame("123.123,12", $this->formatter->asDecimal($value, 2)); + $this->assertSame('123.123', $this->formatter->asDecimal($value, 0)); + $this->assertSame('123.123,12', $this->formatter->asDecimal($value, 2)); $this->formatter->thousandSeparator = ''; - $this->assertSame("123123,1", $this->formatter->asDecimal($value, 1)); + $this->assertSame('123123,1', $this->formatter->asDecimal($value, 1)); $this->formatter->thousandSeparator = ' '; - $this->assertSame("12 31 23,1", $this->formatter->asDecimal($value, 1, [\NumberFormatter::GROUPING_SIZE => 2])); + $this->assertSame('12 31 23,1', $this->formatter->asDecimal($value, 1, [\NumberFormatter::GROUPING_SIZE => 2])); $value = 123123.123; $this->formatter->decimalSeparator = ','; $this->formatter->thousandSeparator = ' '; - $this->assertSame("123 123", $this->formatter->asDecimal($value, 0)); - $this->assertSame("123 123,12", $this->formatter->asDecimal($value, 2)); + $this->assertSame('123 123', $this->formatter->asDecimal($value, 0)); + $this->assertSame('123 123,12', $this->formatter->asDecimal($value, 2)); $this->formatter->decimalSeparator = null; $this->formatter->thousandSeparator = null; $value = '-123456.123'; - $this->assertSame("-123,456.123", $this->formatter->asDecimal($value)); + $this->assertSame('-123,456.123', $this->formatter->asDecimal($value)); // empty input - $this->assertSame("0", $this->formatter->asDecimal(false)); - $this->assertSame("0", $this->formatter->asDecimal("")); + $this->assertSame('0', $this->formatter->asDecimal(false)); + $this->assertSame('0', $this->formatter->asDecimal('')); // null display $this->assertSame($this->formatter->nullDisplay, $this->formatter->asDecimal(null)); @@ -165,39 +170,39 @@ class FormatterNumberTest extends TestCase public function testAsDecimal() { $value = 123.12; - $this->assertSame("123.12", $this->formatter->asDecimal($value)); - $this->assertSame("123.1", $this->formatter->asDecimal($value, 1)); - $this->assertSame("123", $this->formatter->asDecimal($value, 0)); + $this->assertSame('123.12', $this->formatter->asDecimal($value)); + $this->assertSame('123.1', $this->formatter->asDecimal($value, 1)); + $this->assertSame('123', $this->formatter->asDecimal($value, 0)); $value = 123; - $this->assertSame("123.00", $this->formatter->asDecimal($value)); + $this->assertSame('123.00', $this->formatter->asDecimal($value)); $this->formatter->decimalSeparator = ','; $this->formatter->thousandSeparator = '.'; $value = 123.12; - $this->assertSame("123,12", $this->formatter->asDecimal($value)); - $this->assertSame("123,1", $this->formatter->asDecimal($value, 1)); - $this->assertSame("123", $this->formatter->asDecimal($value, 0)); + $this->assertSame('123,12', $this->formatter->asDecimal($value)); + $this->assertSame('123,1', $this->formatter->asDecimal($value, 1)); + $this->assertSame('123', $this->formatter->asDecimal($value, 0)); $value = 123123.123; - $this->assertSame("123.123,12", $this->formatter->asDecimal($value)); + $this->assertSame('123.123,12', $this->formatter->asDecimal($value)); $value = 123123.123; - $this->assertSame("123.123,12", $this->formatter->asDecimal($value)); - $this->assertSame("123.123,12", $this->formatter->asDecimal($value, 2)); + $this->assertSame('123.123,12', $this->formatter->asDecimal($value)); + $this->assertSame('123.123,12', $this->formatter->asDecimal($value, 2)); $this->formatter->decimalSeparator = ','; $this->formatter->thousandSeparator = ' '; - $this->assertSame("123 123,12", $this->formatter->asDecimal($value)); - $this->assertSame("123 123,12", $this->formatter->asDecimal($value, 2)); + $this->assertSame('123 123,12', $this->formatter->asDecimal($value)); + $this->assertSame('123 123,12', $this->formatter->asDecimal($value, 2)); $this->formatter->thousandSeparator = ''; - $this->assertSame("123123,12", $this->formatter->asDecimal($value)); - $this->assertSame("123123,12", $this->formatter->asDecimal($value, 2)); + $this->assertSame('123123,12', $this->formatter->asDecimal($value)); + $this->assertSame('123123,12', $this->formatter->asDecimal($value, 2)); $this->formatter->decimalSeparator = null; $this->formatter->thousandSeparator = null; $value = '-123456.123'; - $this->assertSame("-123,456.123", $this->formatter->asDecimal($value, 3)); + $this->assertSame('-123,456.123', $this->formatter->asDecimal($value, 3)); // empty input - $this->assertSame("0.00", $this->formatter->asDecimal(false)); - $this->assertSame("0.00", $this->formatter->asDecimal("")); + $this->assertSame('0.00', $this->formatter->asDecimal(false)); + $this->assertSame('0.00', $this->formatter->asDecimal('')); // null display $this->assertSame($this->formatter->nullDisplay, $this->formatter->asDecimal(null)); @@ -212,14 +217,14 @@ class FormatterNumberTest extends TestCase { $this->assertSame('12,300%', $this->formatter->asPercent(123)); $this->assertSame('12,300%', $this->formatter->asPercent('123')); - $this->assertSame("12%", $this->formatter->asPercent(0.1234)); - $this->assertSame("12%", $this->formatter->asPercent('0.1234')); - $this->assertSame("-1%", $this->formatter->asPercent(-0.009343)); - $this->assertSame("-1%", $this->formatter->asPercent('-0.009343')); + $this->assertSame('12%', $this->formatter->asPercent(0.1234)); + $this->assertSame('12%', $this->formatter->asPercent('0.1234')); + $this->assertSame('-1%', $this->formatter->asPercent(-0.009343)); + $this->assertSame('-1%', $this->formatter->asPercent('-0.009343')); // empty input - $this->assertSame("0%", $this->formatter->asPercent(false)); - $this->assertSame("0%", $this->formatter->asPercent("")); + $this->assertSame('0%', $this->formatter->asPercent(false)); + $this->assertSame('0%', $this->formatter->asPercent('')); // null display $this->assertSame($this->formatter->nullDisplay, $this->formatter->asPercent(null)); @@ -301,16 +306,16 @@ class FormatterNumberTest extends TestCase $this->formatter->currencyCode = null; $this->formatter->numberFormatterSymbols = []; $this->formatter->thousandSeparator = null; - $this->assertSame("0,00 €", $this->formatter->asCurrency(false)); - $this->assertSame("0,00 €", $this->formatter->asCurrency("")); + $this->assertSame('0,00 €', $this->formatter->asCurrency(false)); + $this->assertSame('0,00 €', $this->formatter->asCurrency('')); // decimal formatting $this->formatter->locale = 'de-DE'; - $this->assertSame("100 $", \Yii::$app->formatter->asCurrency(100, 'USD', [ + $this->assertSame('100 $', \Yii::$app->formatter->asCurrency(100, 'USD', [ NumberFormatter::MAX_FRACTION_DIGITS => 0, ])); - $this->assertSame("100,00 $", $this->formatter->asCurrency(100, 'USD', [ - NumberFormatter::MAX_FRACTION_DIGITS => 2 + $this->assertSame('100,00 $', $this->formatter->asCurrency(100, 'USD', [ + NumberFormatter::MAX_FRACTION_DIGITS => 2, ])); // null display @@ -360,10 +365,10 @@ class FormatterNumberTest extends TestCase { $this->formatter->locale = 'en-US'; $this->formatter->numberFormatterOptions = [ - \NumberFormatter::FRACTION_DIGITS => 0 + \NumberFormatter::FRACTION_DIGITS => 0, ]; $this->formatter->numberFormatterTextOptions = [ - \NumberFormatter::CURRENCY_CODE => 'EUR' + \NumberFormatter::CURRENCY_CODE => 'EUR', ]; $this->assertSame('€100', $this->formatter->asCurrency(100, 'EUR')); } @@ -385,8 +390,8 @@ class FormatterNumberTest extends TestCase // empty input $this->formatter->currencyCode = 'USD'; $this->formatter->numberFormatterSymbols = []; - $this->assertSame("USD 0.00", $this->formatter->asCurrency(false)); - $this->assertSame("USD 0.00", $this->formatter->asCurrency("")); + $this->assertSame('USD 0.00', $this->formatter->asCurrency(false)); + $this->assertSame('USD 0.00', $this->formatter->asCurrency('')); // null display $this->assertSame($this->formatter->nullDisplay, $this->formatter->asCurrency(null)); @@ -397,13 +402,13 @@ class FormatterNumberTest extends TestCase $value = '123'; $this->assertSame('1.23E2', $this->formatter->asScientific($value)); $value = '123456'; - $this->assertSame("1.23456E5", $this->formatter->asScientific($value)); + $this->assertSame('1.23456E5', $this->formatter->asScientific($value)); $value = '-123456.123'; - $this->assertSame("-1.23456123E5", $this->formatter->asScientific($value)); + $this->assertSame('-1.23456123E5', $this->formatter->asScientific($value)); // empty input - $this->assertSame("0E0", $this->formatter->asScientific(false)); - $this->assertSame("0E0", $this->formatter->asScientific("")); + $this->assertSame('0E0', $this->formatter->asScientific(false)); + $this->assertSame('0E0', $this->formatter->asScientific('')); // null display $this->assertSame($this->formatter->nullDisplay, $this->formatter->asScientific(null)); @@ -414,13 +419,13 @@ class FormatterNumberTest extends TestCase $value = '123'; $this->assertSame('1.23E+2', $this->formatter->asScientific($value, 2)); $value = '123456'; - $this->assertSame("1.234560E+5", $this->formatter->asScientific($value)); + $this->assertSame('1.234560E+5', $this->formatter->asScientific($value)); $value = '-123456.123'; - $this->assertSame("-1.234561E+5", $this->formatter->asScientific($value)); + $this->assertSame('-1.234561E+5', $this->formatter->asScientific($value)); // empty input - $this->assertSame("0.000000E+0", $this->formatter->asScientific(false)); - $this->assertSame("0.000000E+0", $this->formatter->asScientific("")); + $this->assertSame('0.000000E+0', $this->formatter->asScientific(false)); + $this->assertSame('0.000000E+0', $this->formatter->asScientific('')); // null display $this->assertSame($this->formatter->nullDisplay, $this->formatter->asScientific(null)); @@ -479,31 +484,31 @@ class FormatterNumberTest extends TestCase // tests for base 1000 $this->formatter->sizeFormatBase = 1000; - $this->assertSame("999 B", $this->formatter->asShortSize(999)); - $this->assertSame("999 B", $this->formatter->asShortSize('999')); - $this->assertSame("1.05 MB", $this->formatter->asShortSize(1024 * 1024)); - $this->assertSame("1 KB", $this->formatter->asShortSize(1000)); - $this->assertSame("1.02 KB", $this->formatter->asShortSize(1023)); - $this->assertNotEquals("3 PB", $this->formatter->asShortSize(3 * 1000 * 1000 * 1000 * 1000 * 1000 * 1000)); // this is 3 EB not 3 PB + $this->assertSame('999 B', $this->formatter->asShortSize(999)); + $this->assertSame('999 B', $this->formatter->asShortSize('999')); + $this->assertSame('1.05 MB', $this->formatter->asShortSize(1024 * 1024)); + $this->assertSame('1 KB', $this->formatter->asShortSize(1000)); + $this->assertSame('1.02 KB', $this->formatter->asShortSize(1023)); + $this->assertNotEquals('3 PB', $this->formatter->asShortSize(3 * 1000 * 1000 * 1000 * 1000 * 1000 * 1000)); // this is 3 EB not 3 PB // string values - $this->assertSame("28.41 GB", $this->formatter->asShortSize(28406984038)); - $this->assertSame("28.41 GB", $this->formatter->asShortSize((string)28406984038)); - $this->assertSame("56.81 GB", $this->formatter->asShortSize(28406984038 + 28406984038)); - $this->assertSame("56.81 GB", $this->formatter->asShortSize((string)(28406984038 + 28406984038))); + $this->assertSame('28.41 GB', $this->formatter->asShortSize(28406984038)); + $this->assertSame('28.41 GB', $this->formatter->asShortSize((string) 28406984038)); + $this->assertSame('56.81 GB', $this->formatter->asShortSize(28406984038 + 28406984038)); + $this->assertSame('56.81 GB', $this->formatter->asShortSize((string) (28406984038 + 28406984038))); // tests for base 1024 $this->formatter->sizeFormatBase = 1024; - $this->assertSame("1 KiB", $this->formatter->asShortSize(1024)); - $this->assertSame("1 MiB", $this->formatter->asShortSize(1024 * 1024)); + $this->assertSame('1 KiB', $this->formatter->asShortSize(1024)); + $this->assertSame('1 MiB', $this->formatter->asShortSize(1024 * 1024)); // https://github.com/yiisoft/yii2/issues/4960 - $this->assertSame("1023 B", $this->formatter->asShortSize(1023)); - $this->assertSame("5 GiB", $this->formatter->asShortSize(5 * 1024 * 1024 * 1024)); - $this->assertNotEquals("5 PiB", $this->formatter->asShortSize(5 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024)); // this is 5 EiB not 5 PiB + $this->assertSame('1023 B', $this->formatter->asShortSize(1023)); + $this->assertSame('5 GiB', $this->formatter->asShortSize(5 * 1024 * 1024 * 1024)); + $this->assertNotEquals('5 PiB', $this->formatter->asShortSize(5 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024)); // this is 5 EiB not 5 PiB //$this->assertSame("1 YiB", $this->formatter->asShortSize(pow(2, 80))); - $this->assertSame("2 GiB", $this->formatter->asShortSize(2147483647)); // round 1.999 up to 2 + $this->assertSame('2 GiB', $this->formatter->asShortSize(2147483647)); // round 1.999 up to 2 $this->formatter->decimalSeparator = ','; $this->formatter->numberFormatterOptions = []; - $this->assertSame("1,001 KiB", $this->formatter->asShortSize(1025, 3)); + $this->assertSame('1,001 KiB', $this->formatter->asShortSize(1025, 3)); // empty values $this->assertSame('0 B', $this->formatter->asShortSize(0)); @@ -516,31 +521,31 @@ class FormatterNumberTest extends TestCase { // tests for base 1000 $this->formatter->sizeFormatBase = 1000; - $this->assertSame("999 B", $this->formatter->asShortSize(999)); - $this->assertSame("999 B", $this->formatter->asShortSize('999')); - $this->assertSame("1.05 MB", $this->formatter->asShortSize(1024 * 1024)); - $this->assertSame("1.0486 MB", $this->formatter->asShortSize(1024 * 1024, 4)); - $this->assertSame("1.00 KB", $this->formatter->asShortSize(1000)); - $this->assertSame("1.02 KB", $this->formatter->asShortSize(1023)); - $this->assertNotEquals("3 PB", $this->formatter->asShortSize(3 * 1000 * 1000 * 1000 * 1000 * 1000 * 1000)); // this is 3 EB not 3 PB + $this->assertSame('999 B', $this->formatter->asShortSize(999)); + $this->assertSame('999 B', $this->formatter->asShortSize('999')); + $this->assertSame('1.05 MB', $this->formatter->asShortSize(1024 * 1024)); + $this->assertSame('1.0486 MB', $this->formatter->asShortSize(1024 * 1024, 4)); + $this->assertSame('1.00 KB', $this->formatter->asShortSize(1000)); + $this->assertSame('1.02 KB', $this->formatter->asShortSize(1023)); + $this->assertNotEquals('3 PB', $this->formatter->asShortSize(3 * 1000 * 1000 * 1000 * 1000 * 1000 * 1000)); // this is 3 EB not 3 PB // string values - $this->assertSame("28.41 GB", $this->formatter->asShortSize(28406984038)); - $this->assertSame("28.41 GB", $this->formatter->asShortSize((string)28406984038)); - $this->assertSame("56.81 GB", $this->formatter->asShortSize(28406984038 + 28406984038)); - $this->assertSame("56.81 GB", $this->formatter->asShortSize((string)(28406984038 + 28406984038))); + $this->assertSame('28.41 GB', $this->formatter->asShortSize(28406984038)); + $this->assertSame('28.41 GB', $this->formatter->asShortSize((string) 28406984038)); + $this->assertSame('56.81 GB', $this->formatter->asShortSize(28406984038 + 28406984038)); + $this->assertSame('56.81 GB', $this->formatter->asShortSize((string) (28406984038 + 28406984038))); // tests for base 1024 $this->formatter->sizeFormatBase = 1024; - $this->assertSame("1.00 KiB", $this->formatter->asShortSize(1024)); - $this->assertSame("1.00 MiB", $this->formatter->asShortSize(1024 * 1024)); + $this->assertSame('1.00 KiB', $this->formatter->asShortSize(1024)); + $this->assertSame('1.00 MiB', $this->formatter->asShortSize(1024 * 1024)); // https://github.com/yiisoft/yii2/issues/4960 - $this->assertSame("1023 B", $this->formatter->asShortSize(1023)); - $this->assertSame("5.00 GiB", $this->formatter->asShortSize(5 * 1024 * 1024 * 1024)); - $this->assertNotEquals("5.00 PiB", $this->formatter->asShortSize(5 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024)); // this is 5 EiB not 5 PiB + $this->assertSame('1023 B', $this->formatter->asShortSize(1023)); + $this->assertSame('5.00 GiB', $this->formatter->asShortSize(5 * 1024 * 1024 * 1024)); + $this->assertNotEquals('5.00 PiB', $this->formatter->asShortSize(5 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024)); // this is 5 EiB not 5 PiB //$this->assertSame("1 YiB", $this->formatter->asShortSize(pow(2, 80))); - $this->assertSame("2.00 GiB", $this->formatter->asShortSize(2147483647)); // round 1.999 up to 2 + $this->assertSame('2.00 GiB', $this->formatter->asShortSize(2147483647)); // round 1.999 up to 2 $this->formatter->decimalSeparator = ','; - $this->assertSame("1,001 KiB", $this->formatter->asShortSize(1025, 3)); + $this->assertSame('1,001 KiB', $this->formatter->asShortSize(1025, 3)); // empty values $this->assertSame('0 B', $this->formatter->asShortSize(0)); @@ -558,24 +563,24 @@ class FormatterNumberTest extends TestCase // tests for base 1000 $this->formatter->sizeFormatBase = 1000; - $this->assertSame("999 bytes", $this->formatter->asSize(999)); - $this->assertSame("999 bytes", $this->formatter->asSize('999')); - $this->assertSame("1.05 megabytes", $this->formatter->asSize(1024 * 1024)); - $this->assertSame("1 kilobyte", $this->formatter->asSize(1000)); - $this->assertSame("1.02 kilobytes", $this->formatter->asSize(1023)); - $this->assertSame("3 gigabytes", $this->formatter->asSize(3 * 1000 * 1000 * 1000)); - $this->assertNotEquals("3 PB", $this->formatter->asSize(3 * 1000 * 1000 * 1000 * 1000 * 1000 * 1000)); // this is 3 EB not 3 PB + $this->assertSame('999 bytes', $this->formatter->asSize(999)); + $this->assertSame('999 bytes', $this->formatter->asSize('999')); + $this->assertSame('1.05 megabytes', $this->formatter->asSize(1024 * 1024)); + $this->assertSame('1 kilobyte', $this->formatter->asSize(1000)); + $this->assertSame('1.02 kilobytes', $this->formatter->asSize(1023)); + $this->assertSame('3 gigabytes', $this->formatter->asSize(3 * 1000 * 1000 * 1000)); + $this->assertNotEquals('3 PB', $this->formatter->asSize(3 * 1000 * 1000 * 1000 * 1000 * 1000 * 1000)); // this is 3 EB not 3 PB // tests for base 1024 $this->formatter->sizeFormatBase = 1024; - $this->assertSame("1 kibibyte", $this->formatter->asSize(1024)); - $this->assertSame("1 mebibyte", $this->formatter->asSize(1024 * 1024)); - $this->assertSame("1023 bytes", $this->formatter->asSize(1023)); - $this->assertSame("5 gibibytes", $this->formatter->asSize(5 * 1024 * 1024 * 1024)); - $this->assertNotEquals("5 pibibytes", $this->formatter->asSize(5 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024)); // this is 5 EiB not 5 PiB - $this->assertSame("2 gibibytes", $this->formatter->asSize(2147483647)); // round 1.999 up to 2 + $this->assertSame('1 kibibyte', $this->formatter->asSize(1024)); + $this->assertSame('1 mebibyte', $this->formatter->asSize(1024 * 1024)); + $this->assertSame('1023 bytes', $this->formatter->asSize(1023)); + $this->assertSame('5 gibibytes', $this->formatter->asSize(5 * 1024 * 1024 * 1024)); + $this->assertNotEquals('5 pibibytes', $this->formatter->asSize(5 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024)); // this is 5 EiB not 5 PiB + $this->assertSame('2 gibibytes', $this->formatter->asSize(2147483647)); // round 1.999 up to 2 $this->formatter->decimalSeparator = ','; $this->formatter->numberFormatterOptions = []; - $this->assertSame("1,001 kibibytes", $this->formatter->asSize(1025, 3)); + $this->assertSame('1,001 kibibytes', $this->formatter->asSize(1025, 3)); // null display $this->assertSame($this->formatter->nullDisplay, $this->formatter->asSize(null)); @@ -590,49 +595,49 @@ class FormatterNumberTest extends TestCase // tests for base 1000 $this->formatter->sizeFormatBase = 1000; - $this->assertSame("-999 bytes", $this->formatter->asSize(-999)); - $this->assertSame("-999 bytes", $this->formatter->asSize('-999')); - $this->assertSame("-1.05 megabytes", $this->formatter->asSize(-1024 * 1024)); - $this->assertSame("-1 kilobyte", $this->formatter->asSize(-1000)); - $this->assertSame("-1.02 kilobytes", $this->formatter->asSize(-1023)); - $this->assertSame("-3 gigabytes", $this->formatter->asSize(-3 * 1000 * 1000 * 1000)); - $this->assertNotEquals("3 PB", $this->formatter->asSize(-3 * 1000 * 1000 * 1000 * 1000 * 1000 * 1000)); // this is 3 EB not 3 PB + $this->assertSame('-999 bytes', $this->formatter->asSize(-999)); + $this->assertSame('-999 bytes', $this->formatter->asSize('-999')); + $this->assertSame('-1.05 megabytes', $this->formatter->asSize(-1024 * 1024)); + $this->assertSame('-1 kilobyte', $this->formatter->asSize(-1000)); + $this->assertSame('-1.02 kilobytes', $this->formatter->asSize(-1023)); + $this->assertSame('-3 gigabytes', $this->formatter->asSize(-3 * 1000 * 1000 * 1000)); + $this->assertNotEquals('3 PB', $this->formatter->asSize(-3 * 1000 * 1000 * 1000 * 1000 * 1000 * 1000)); // this is 3 EB not 3 PB // tests for base 1024 $this->formatter->sizeFormatBase = 1024; - $this->assertSame("-1 kibibyte", $this->formatter->asSize(-1024)); - $this->assertSame("-1 mebibyte", $this->formatter->asSize(-1024 * 1024)); - $this->assertSame("-1023 bytes", $this->formatter->asSize(-1023)); - $this->assertSame("-5 gibibytes", $this->formatter->asSize(-5 * 1024 * 1024 * 1024)); - $this->assertNotEquals("-5 pibibytes", $this->formatter->asSize(-5 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024)); // this is 5 EiB not 5 PiB - $this->assertSame("-2 gibibytes", $this->formatter->asSize(-2147483647)); // round 1.999 up to 2 + $this->assertSame('-1 kibibyte', $this->formatter->asSize(-1024)); + $this->assertSame('-1 mebibyte', $this->formatter->asSize(-1024 * 1024)); + $this->assertSame('-1023 bytes', $this->formatter->asSize(-1023)); + $this->assertSame('-5 gibibytes', $this->formatter->asSize(-5 * 1024 * 1024 * 1024)); + $this->assertNotEquals('-5 pibibytes', $this->formatter->asSize(-5 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024)); // this is 5 EiB not 5 PiB + $this->assertSame('-2 gibibytes', $this->formatter->asSize(-2147483647)); // round 1.999 up to 2 $this->formatter->decimalSeparator = ','; $this->formatter->numberFormatterOptions = []; - $this->assertSame("-1,001 kibibytes", $this->formatter->asSize(-1025, 3)); + $this->assertSame('-1,001 kibibytes', $this->formatter->asSize(-1025, 3)); } public function testAsSize() { // tests for base 1000 $this->formatter->sizeFormatBase = 1000; - $this->assertSame("999 bytes", $this->formatter->asSize(999)); - $this->assertSame("999 bytes", $this->formatter->asSize('999')); - $this->assertSame("1.05 megabytes", $this->formatter->asSize(1024 * 1024)); - $this->assertSame("1.0486 megabytes", $this->formatter->asSize(1024 * 1024, 4)); - $this->assertSame("1.00 kilobyte", $this->formatter->asSize(1000)); - $this->assertSame("1.02 kilobytes", $this->formatter->asSize(1023)); - $this->assertSame("3.00 gigabytes", $this->formatter->asSize(3 * 1000 * 1000 * 1000)); - $this->assertNotEquals("3 PB", $this->formatter->asSize(3 * 1000 * 1000 * 1000 * 1000 * 1000 * 1000)); // this is 3 EB not 3 PB + $this->assertSame('999 bytes', $this->formatter->asSize(999)); + $this->assertSame('999 bytes', $this->formatter->asSize('999')); + $this->assertSame('1.05 megabytes', $this->formatter->asSize(1024 * 1024)); + $this->assertSame('1.0486 megabytes', $this->formatter->asSize(1024 * 1024, 4)); + $this->assertSame('1.00 kilobyte', $this->formatter->asSize(1000)); + $this->assertSame('1.02 kilobytes', $this->formatter->asSize(1023)); + $this->assertSame('3.00 gigabytes', $this->formatter->asSize(3 * 1000 * 1000 * 1000)); + $this->assertNotEquals('3 PB', $this->formatter->asSize(3 * 1000 * 1000 * 1000 * 1000 * 1000 * 1000)); // this is 3 EB not 3 PB // tests for base 1024 $this->formatter->sizeFormatBase = 1024; - $this->assertSame("1.00 kibibyte", $this->formatter->asSize(1024)); - $this->assertSame("1.00 mebibyte", $this->formatter->asSize(1024 * 1024)); - $this->assertSame("1023 bytes", $this->formatter->asSize(1023)); - $this->assertSame("5.00 gibibytes", $this->formatter->asSize(5 * 1024 * 1024 * 1024)); - $this->assertNotEquals("5.00 pibibytes", $this->formatter->asSize(5 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024)); // this is 5 EiB not 5 PiB - $this->assertSame("2.00 gibibytes", $this->formatter->asSize(2147483647)); // round 1.999 up to 2 + $this->assertSame('1.00 kibibyte', $this->formatter->asSize(1024)); + $this->assertSame('1.00 mebibyte', $this->formatter->asSize(1024 * 1024)); + $this->assertSame('1023 bytes', $this->formatter->asSize(1023)); + $this->assertSame('5.00 gibibytes', $this->formatter->asSize(5 * 1024 * 1024 * 1024)); + $this->assertNotEquals('5.00 pibibytes', $this->formatter->asSize(5 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024)); // this is 5 EiB not 5 PiB + $this->assertSame('2.00 gibibytes', $this->formatter->asSize(2147483647)); // round 1.999 up to 2 $this->formatter->decimalSeparator = ','; $this->formatter->numberFormatterOptions = []; - $this->assertSame("1,001 kibibytes", $this->formatter->asSize(1025, 3)); + $this->assertSame('1,001 kibibytes', $this->formatter->asSize(1025, 3)); // null display $this->assertSame($this->formatter->nullDisplay, $this->formatter->asSize(null)); @@ -642,34 +647,34 @@ class FormatterNumberTest extends TestCase { // tests for base 1000 $this->formatter->sizeFormatBase = 1000; - $this->assertSame("-999 bytes", $this->formatter->asSize(-999)); - $this->assertSame("-999 bytes", $this->formatter->asSize('-999')); - $this->assertSame("-1.05 megabytes", $this->formatter->asSize(-1024 * 1024)); - $this->assertSame("-1.0486 megabytes", $this->formatter->asSize(-1024 * 1024, 4)); - $this->assertSame("-1.00 kilobyte", $this->formatter->asSize(-1000)); - $this->assertSame("-1.02 kilobytes", $this->formatter->asSize(-1023)); - $this->assertSame("-3.00 gigabytes", $this->formatter->asSize(-3 * 1000 * 1000 * 1000)); - $this->assertNotEquals("3 PB", $this->formatter->asSize(-3 * 1000 * 1000 * 1000 * 1000 * 1000 * 1000)); // this is 3 EB not 3 PB + $this->assertSame('-999 bytes', $this->formatter->asSize(-999)); + $this->assertSame('-999 bytes', $this->formatter->asSize('-999')); + $this->assertSame('-1.05 megabytes', $this->formatter->asSize(-1024 * 1024)); + $this->assertSame('-1.0486 megabytes', $this->formatter->asSize(-1024 * 1024, 4)); + $this->assertSame('-1.00 kilobyte', $this->formatter->asSize(-1000)); + $this->assertSame('-1.02 kilobytes', $this->formatter->asSize(-1023)); + $this->assertSame('-3.00 gigabytes', $this->formatter->asSize(-3 * 1000 * 1000 * 1000)); + $this->assertNotEquals('3 PB', $this->formatter->asSize(-3 * 1000 * 1000 * 1000 * 1000 * 1000 * 1000)); // this is 3 EB not 3 PB // tests for base 1024 $this->formatter->sizeFormatBase = 1024; - $this->assertSame("-1.00 kibibyte", $this->formatter->asSize(-1024)); - $this->assertSame("-1.00 mebibyte", $this->formatter->asSize(-1024 * 1024)); - $this->assertSame("-1023 bytes", $this->formatter->asSize(-1023)); - $this->assertSame("-5.00 gibibytes", $this->formatter->asSize(-5 * 1024 * 1024 * 1024)); - $this->assertNotEquals("-5.00 pibibytes", $this->formatter->asSize(-5 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024)); // this is 5 EiB not 5 PiB - $this->assertSame("-2.00 gibibytes", $this->formatter->asSize(-2147483647)); // round 1.999 up to 2 + $this->assertSame('-1.00 kibibyte', $this->formatter->asSize(-1024)); + $this->assertSame('-1.00 mebibyte', $this->formatter->asSize(-1024 * 1024)); + $this->assertSame('-1023 bytes', $this->formatter->asSize(-1023)); + $this->assertSame('-5.00 gibibytes', $this->formatter->asSize(-5 * 1024 * 1024 * 1024)); + $this->assertNotEquals('-5.00 pibibytes', $this->formatter->asSize(-5 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024)); // this is 5 EiB not 5 PiB + $this->assertSame('-2.00 gibibytes', $this->formatter->asSize(-2147483647)); // round 1.999 up to 2 $this->formatter->decimalSeparator = ','; $this->formatter->numberFormatterOptions = []; - $this->assertSame("-1,001 kibibytes", $this->formatter->asSize(-1025, 3)); + $this->assertSame('-1,001 kibibytes', $this->formatter->asSize(-1025, 3)); } public function testIntlAsSizeConfiguration() { - $this->assertSame("1023 bytes", $this->formatter->asSize(1023)); - $this->assertSame("1023 B", $this->formatter->asShortSize(1023)); + $this->assertSame('1023 bytes', $this->formatter->asSize(1023)); + $this->assertSame('1023 B', $this->formatter->asShortSize(1023)); $this->formatter->thousandSeparator = '.'; - $this->assertSame("1023 bytes", $this->formatter->asSize(1023)); - $this->assertSame("1023 B", $this->formatter->asShortSize(1023)); + $this->assertSame('1023 bytes', $this->formatter->asSize(1023)); + $this->assertSame('1023 B', $this->formatter->asShortSize(1023)); } /** @@ -677,10 +682,10 @@ class FormatterNumberTest extends TestCase */ public function testAsSizeConfiguration() { - $this->assertSame("1023 bytes", $this->formatter->asSize(1023)); - $this->assertSame("1023 B", $this->formatter->asShortSize(1023)); + $this->assertSame('1023 bytes', $this->formatter->asSize(1023)); + $this->assertSame('1023 B', $this->formatter->asShortSize(1023)); $this->formatter->thousandSeparator = '.'; - $this->assertSame("1023 bytes", $this->formatter->asSize(1023)); - $this->assertSame("1023 B", $this->formatter->asShortSize(1023)); + $this->assertSame('1023 bytes', $this->formatter->asSize(1023)); + $this->assertSame('1023 B', $this->formatter->asShortSize(1023)); } } diff --git a/tests/framework/i18n/FormatterTest.php b/tests/framework/i18n/FormatterTest.php index 8d53f55..05868aa 100644 --- a/tests/framework/i18n/FormatterTest.php +++ b/tests/framework/i18n/FormatterTest.php @@ -1,9 +1,14 @@ assertSame("$value", $this->formatter->asUrl($value)); $value = 'https://www.yiiframework.com/?name=test&value=5"'; - $this->assertSame("https://www.yiiframework.com/?name=test&value=5"", $this->formatter->asUrl($value)); + $this->assertSame('https://www.yiiframework.com/?name=test&value=5"', $this->formatter->asUrl($value)); $value = 'http://www.yiiframework.com/'; $this->assertSame("$value", $this->formatter->asUrl($value, ['target' => '_blank'])); @@ -173,7 +178,7 @@ class FormatterTest extends TestCase $value = 'http://sample.com/img.jpg'; $this->assertSame("\"\"", $this->formatter->asImage($value)); $value = 'http://sample.com/img.jpg'; - $alt = "Hello!"; + $alt = 'Hello!'; $this->assertSame("\"$alt\"", $this->formatter->asImage($value, ['alt' => $alt])); // null display @@ -184,8 +189,8 @@ class FormatterTest extends TestCase { $this->assertSame('Yes', $this->formatter->asBoolean(true)); $this->assertSame('No', $this->formatter->asBoolean(false)); - $this->assertSame('Yes', $this->formatter->asBoolean("111")); - $this->assertSame('No', $this->formatter->asBoolean("")); + $this->assertSame('Yes', $this->formatter->asBoolean('111')); + $this->assertSame('No', $this->formatter->asBoolean('')); $this->assertSame('No', $this->formatter->asBoolean(0)); // null display diff --git a/tests/framework/i18n/GettextMessageSourceTest.php b/tests/framework/i18n/GettextMessageSourceTest.php index cb586de..036682e 100644 --- a/tests/framework/i18n/GettextMessageSourceTest.php +++ b/tests/framework/i18n/GettextMessageSourceTest.php @@ -1,4 +1,9 @@ assertArrayNotHasKey("Missing\n\r\t\"translation.", $context1); $this->assertArrayHasKey("Aliquam tempus elit vel purus molestie placerat. In sollicitudin tincidunt\naliquet. Integer tincidunt gravida tempor. In convallis blandit dui vel malesuada.\nNunc vel sapien nunc, a pretium nulla.", $context1); - $this->assertArrayHasKey("String number two.", $context1); + $this->assertArrayHasKey('String number two.', $context1); $this->assertArrayHasKey("Nunc vel sapien nunc, a pretium nulla.\nPellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.", $context1); $this->assertArrayHasKey("The other\n\ncontext.\n", $context2); $this->assertArrayHasKey("test1\\ntest2\n\\\ntest3", $context2); // translated messages - $this->assertFalse(in_array("", $context1)); + $this->assertFalse(in_array('', $context1)); $this->assertTrue(in_array("Олицетворение однократно. Представленный лексико-семантический анализ является\nпсихолингвистическим в своей основе, но механизм сочленений полидисперсен. Впечатление\nоднократно. Различное расположение выбирает сюжетный механизм сочленений.", $context1)); $this->assertTrue(in_array('Строка номер два.', $context1)); $this->assertTrue(in_array('Короткий перевод.', $context1)); @@ -83,7 +88,7 @@ class GettextMoFileTest extends TestCase // context2 $this->assertCount(4, $context2); - $this->assertArrayHasKey("\"Quotes\"", $context2); + $this->assertArrayHasKey('"Quotes"', $context2); $this->assertTrue(in_array('"Кавычки"', $context2)); $this->assertArrayHasKey("\nNew lines\n", $context2); diff --git a/tests/framework/i18n/GettextPoFileTest.php b/tests/framework/i18n/GettextPoFileTest.php index b7cf3f8..d32f312 100644 --- a/tests/framework/i18n/GettextPoFileTest.php +++ b/tests/framework/i18n/GettextPoFileTest.php @@ -1,4 +1,9 @@ assertArrayHasKey("Missing\n\r\t\"translation.", $context1); $this->assertArrayHasKey("Aliquam tempus elit vel purus molestie placerat. In sollicitudin tincidunt\naliquet. Integer tincidunt gravida tempor. In convallis blandit dui vel malesuada.\nNunc vel sapien nunc, a pretium nulla.", $context1); - $this->assertArrayHasKey("String number two.", $context1); + $this->assertArrayHasKey('String number two.', $context1); $this->assertArrayHasKey("Nunc vel sapien nunc, a pretium nulla.\nPellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.", $context1); $this->assertArrayHasKey("The other\n\ncontext.\n", $context2); $this->assertArrayHasKey("test1\\\ntest2\n\\\\\ntest3", $context2); // translated messages - $this->assertTrue(in_array("", $context1)); + $this->assertTrue(in_array('', $context1)); $this->assertTrue(in_array("Олицетворение однократно. Представленный лексико-семантический анализ является\nпсихолингвистическим в своей основе, но механизм сочленений полидисперсен. Впечатление\nоднократно. Различное расположение выбирает сюжетный механизм сочленений.", $context1)); $this->assertTrue(in_array('Строка номер два.', $context1)); $this->assertTrue(in_array('Короткий перевод.', $context1)); @@ -90,7 +94,7 @@ class GettextPoFileTest extends TestCase // context2 $this->assertCount(4, $context2); - $this->assertArrayHasKey("\"Quotes\"", $context2); + $this->assertArrayHasKey('"Quotes"', $context2); $this->assertTrue(in_array('"Кавычки"', $context2)); $this->assertArrayHasKey("\nNew lines\n", $context2); diff --git a/tests/framework/i18n/I18NTest.php b/tests/framework/i18n/I18NTest.php index 5b558e5..6c893f3 100644 --- a/tests/framework/i18n/I18NTest.php +++ b/tests/framework/i18n/I18NTest.php @@ -39,8 +39,8 @@ class I18NTest extends TestCase 'test' => [ 'class' => $this->getMessageSourceClass(), 'basePath' => '@yiiunit/data/i18n/messages', - ] - ] + ], + ], ]); } @@ -77,8 +77,8 @@ class I18NTest extends TestCase 'test' => 'test.php', 'foo' => 'test.php', ], - ] - ] + ], + ], ]); $msg = 'The dog runs fast.'; @@ -113,8 +113,8 @@ class I18NTest extends TestCase 'foo' => 'test.php', ], ] - ) - ] + ), + ], ]); $msg = 'The dog runs fast.'; @@ -141,8 +141,8 @@ class I18NTest extends TestCase public function testTranslateParams2() { - if (!extension_loaded("intl")) { - $this->markTestSkipped("intl not installed. Skipping."); + if (!extension_loaded('intl')) { + $this->markTestSkipped('intl not installed. Skipping.'); } $msg = 'His name is {name} and his speed is about {n, number} km/h.'; $params = [ @@ -225,7 +225,7 @@ class I18NTest extends TestCase { return [ ['en-GB'], - ['en'] + ['en'], ]; } diff --git a/tests/framework/i18n/IntlTestHelper.php b/tests/framework/i18n/IntlTestHelper.php index d9a4eb7..18862f0 100644 --- a/tests/framework/i18n/IntlTestHelper.php +++ b/tests/framework/i18n/IntlTestHelper.php @@ -1,11 +1,17 @@ self::N_VALUE, self::SUBJECT => self::SUBJECT_VALUE, - ] + ], ], [ - '{'.self::SUBJECT.'} is {'.self::N.', number, integer}', // pattern - self::SUBJECT_VALUE.' is '.self::N_VALUE, // expected + '{' . self::SUBJECT . '} is {' . self::N . ', number, integer}', // pattern + self::SUBJECT_VALUE . ' is ' . self::N_VALUE, // expected [ // params self::N => self::N_VALUE, self::SUBJECT => self::SUBJECT_VALUE, - ] + ], ], [ - 'Here is a big number: {'.self::F.', number}', // pattern - 'Here is a big number: '.self::F_VALUE_FORMATTED, // expected + 'Here is a big number: {' . self::F . ', number}', // pattern + 'Here is a big number: ' . self::F_VALUE_FORMATTED, // expected [ // params - self::F => self::F_VALUE - ] + self::F => self::F_VALUE, + ], ], [ - 'Here is a big number: {'.self::F.', number, integer}', // pattern - 'Here is a big number: '.self::F_VALUE_FORMATTED, // expected + 'Here is a big number: {' . self::F . ', number, integer}', // pattern + 'Here is a big number: ' . self::F_VALUE_FORMATTED, // expected [ // params - self::F => self::F_VALUE - ] + self::F => self::F_VALUE, + ], ], [ - 'Here is a big number: {'.self::D.', number}', // pattern - 'Here is a big number: '.self::D_VALUE_FORMATTED, // expected + 'Here is a big number: {' . self::D . ', number}', // pattern + 'Here is a big number: ' . self::D_VALUE_FORMATTED, // expected [ // params - self::D => self::D_VALUE - ] + self::D => self::D_VALUE, + ], ], [ - 'Here is a big number: {'.self::D.', number, integer}', // pattern - 'Here is a big number: '.self::D_VALUE_FORMATTED_INTEGER, // expected + 'Here is a big number: {' . self::D . ', number, integer}', // pattern + 'Here is a big number: ' . self::D_VALUE_FORMATTED_INTEGER, // expected [ // params - self::D => self::D_VALUE - ] + self::D => self::D_VALUE, + ], ], // This one was provided by Aura.Intl. Thanks! @@ -108,10 +108,10 @@ _MSG_ 'gender_of_host' => 'male', 'num_guests' => 4, 'host' => 'ralph', - 'guest' => 'beep' + 'guest' => 'beep', ], defined('INTL_ICU_VERSION') && version_compare(INTL_ICU_VERSION, '4.8', '<'), - 'select format is available in ICU > 4.4 and plural format with =X selector is avilable since 4.8' + 'select format is available in ICU > 4.4 and plural format with =X selector is avilable since 4.8', ], [ @@ -122,7 +122,7 @@ _MSG_ 'gender' => 'male', ], defined('INTL_ICU_VERSION') && version_compare(INTL_ICU_VERSION, '4.4.2', '<'), - 'select format is available in ICU > 4.4' + 'select format is available in ICU > 4.4', ], // verify pattern in select does not get replaced @@ -138,7 +138,7 @@ _MSG_ 'it' => 'wtf', ], defined('INTL_ICU_VERSION') && version_compare(INTL_ICU_VERSION, '4.4.2', '<'), - 'select format is available in ICU > 4.4' + 'select format is available in ICU > 4.4', ], // verify pattern in select message gets replaced @@ -152,7 +152,7 @@ _MSG_ 'she' => 'wtf', ], defined('INTL_ICU_VERSION') && version_compare(INTL_ICU_VERSION, '4.8', '<'), - 'parameters in select format do not seem to work in ICU < 4.8' + 'parameters in select format do not seem to work in ICU < 4.8', ], // some parser specific verifications @@ -166,7 +166,7 @@ _MSG_ 'she' => 'wtf', ], defined('INTL_ICU_VERSION') && version_compare(INTL_ICU_VERSION, '4.4.2', '<'), - 'select format is available in ICU > 4.4' + 'select format is available in ICU > 4.4', ], // formatting a message that contains params but they are not provided. @@ -192,7 +192,7 @@ _MSG_ 'totalCount' => 12, 'page' => 1, 'pageCount' => 2, - ] + ], ], [ 'Showing {begin, number}-{end, number} of {totalCount, number} {totalCount, plural, one{item} other{items}}.', @@ -204,7 +204,7 @@ _MSG_ 'totalCount' => 1, 'page' => 1, 'pageCount' => 1, - ] + ], ], [ 'Showing {begin, number}-{end, number} of {totalCount, number} {totalCount, plural, one{item} other{items}}.', @@ -216,19 +216,19 @@ _MSG_ 'totalCount' => 0, 'page' => 1, 'pageCount' => 1, - ] + ], ], [ 'Total {count, number} {count, plural, one{item} other{items}}.', 'Total {count, number} {count, plural, one{item} other{items}}.', - [] + [], ], [ 'Total {count, number} {count, plural, one{item} other{items}}.', 'Total 1 item.', [ 'count' => 1, - ] + ], ], [ 'Total {count, number} {count, plural, one{item} other{items}}.', @@ -237,7 +237,7 @@ _MSG_ 'begin' => 5, 'count' => 1, 'end' => 10, - ] + ], ], [ '{0, plural, one {offer} other {offers}}', @@ -266,69 +266,69 @@ _MSG_ { return [ [ - self::SUBJECT_VALUE.' is {0, number}', // pattern - self::SUBJECT_VALUE.' is '.self::N_VALUE, // expected + self::SUBJECT_VALUE . ' is {0, number}', // pattern + self::SUBJECT_VALUE . ' is ' . self::N_VALUE, // expected [ // params 0 => self::N_VALUE, - ] + ], ], [ - self::SUBJECT_VALUE.' is {'.self::N.', number}', // pattern - self::SUBJECT_VALUE.' is '.self::N_VALUE, // expected + self::SUBJECT_VALUE . ' is {' . self::N . ', number}', // pattern + self::SUBJECT_VALUE . ' is ' . self::N_VALUE, // expected [ // params self::N => self::N_VALUE, - ] + ], ], [ - self::SUBJECT_VALUE.' is {'.self::N.', number, integer}', // pattern - self::SUBJECT_VALUE.' is '.self::N_VALUE, // expected + self::SUBJECT_VALUE . ' is {' . self::N . ', number, integer}', // pattern + self::SUBJECT_VALUE . ' is ' . self::N_VALUE, // expected [ // params self::N => self::N_VALUE, - ] + ], ], [ - "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree", - "4,560 monkeys on 123 trees make 37.073 monkeys per tree", + '{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree', + '4,560 monkeys on 123 trees make 37.073 monkeys per tree', [ 0 => 4560, 1 => 123, - 2 => 37.073 + 2 => 37.073, ], - 'en-US' + 'en-US', ], [ - "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum", - "4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum", + '{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum', + '4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum', [ 0 => 4560, 1 => 123, - 2 => 37.073 + 2 => 37.073, ], 'de', ], [ - "{monkeyCount,number,integer} monkeys on {trees,number,integer} trees make {monkeysPerTree,number} monkeys per tree", - "4,560 monkeys on 123 trees make 37.073 monkeys per tree", + '{monkeyCount,number,integer} monkeys on {trees,number,integer} trees make {monkeysPerTree,number} monkeys per tree', + '4,560 monkeys on 123 trees make 37.073 monkeys per tree', [ 'monkeyCount' => 4560, 'trees' => 123, - 'monkeysPerTree' => 37.073 + 'monkeysPerTree' => 37.073, ], - 'en-US' + 'en-US', ], [ - "{monkeyCount,number,integer} Affen auf {trees,number,integer} Bäumen sind {monkeysPerTree,number} Affen pro Baum", - "4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum", + '{monkeyCount,number,integer} Affen auf {trees,number,integer} Bäumen sind {monkeysPerTree,number} Affen pro Baum', + '4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum', [ 'monkeyCount' => 4560, 'trees' => 123, - 'monkeysPerTree' => 37.073 + 'monkeysPerTree' => 37.073, ], 'de', ], @@ -353,8 +353,8 @@ _MSG_ */ public function testParseNamedArguments($pattern, $expected, $args, $locale = 'en-US') { - if (!extension_loaded("intl")) { - $this->markTestSkipped("intl not installed. Skipping."); + if (!extension_loaded('intl')) { + $this->markTestSkipped('intl not installed. Skipping.'); } $formatter = new MessageFormatter(); @@ -364,10 +364,10 @@ _MSG_ public function testInsufficientArguments() { - $expected = '{'.self::SUBJECT.'} is '.self::N_VALUE; + $expected = '{' . self::SUBJECT . '} is ' . self::N_VALUE; $formatter = new MessageFormatter(); - $result = $formatter->format('{'.self::SUBJECT.'} is {'.self::N.', number}', [ + $result = $formatter->format('{' . self::SUBJECT . '} is {' . self::N . ', number}', [ self::N => self::N_VALUE, ], 'en-US'); @@ -376,7 +376,7 @@ _MSG_ public function testNoParams() { - $pattern = '{'.self::SUBJECT.'} is '.self::N; + $pattern = '{' . self::SUBJECT . '} is ' . self::N; $formatter = new MessageFormatter(); $result = $formatter->format($pattern, [], 'en-US'); $this->assertEquals($pattern, $result, $formatter->getErrorMessage()); diff --git a/tests/framework/log/DbTargetTest.php b/tests/framework/log/DbTargetTest.php index 26b1e8a..c1e92c1 100644 --- a/tests/framework/log/DbTargetTest.php +++ b/tests/framework/log/DbTargetTest.php @@ -1,4 +1,10 @@ runAction($route, $params); - echo "Result is " . $result; + echo 'Result is ' . $result; if ($result !== \yii\console\Controller::EXIT_CODE_NORMAL) { ob_end_flush(); } else { @@ -91,7 +97,7 @@ abstract class DbTargetTest extends TestCase public static function getConnection() { if (static::$db == null) { - $db = new Connection; + $db = new Connection(); $db->dsn = static::$database['dsn']; if (isset(static::$database['username'])) { $db->username = static::$database['username']; @@ -124,7 +130,7 @@ abstract class DbTargetTest extends TestCase Logger::LEVEL_WARNING, 'test', $time, - [] + [], ]; $logger->messages[] = $messsageData; @@ -147,7 +153,7 @@ abstract class DbTargetTest extends TestCase Logger::LEVEL_WARNING, 'test', time(), - [] + [], ]; $logger->messages[] = $messsageData; diff --git a/tests/framework/log/DispatcherTest.php b/tests/framework/log/DispatcherTest.php index ac915a8..a9182f6 100644 --- a/tests/framework/log/DispatcherTest.php +++ b/tests/framework/log/DispatcherTest.php @@ -1,10 +1,13 @@ + * @link http://www.yiiframework.com/ + * @copyright Copyright (c) 2008 Yii Software LLC + * @license http://www.yiiframework.com/license/ */ namespace yii\log { - function microtime($get_as_float) { + function microtime($get_as_float) + { if (\yiiunit\framework\log\DispatcherTest::$microtimeIsMocked) { return \yiiunit\framework\log\DispatcherTest::microtime(func_get_args()); } else { @@ -15,10 +18,10 @@ namespace yii\log { namespace yiiunit\framework\log { + use Yii; use yii\base\UserException; use yii\log\Dispatcher; use yii\log\Logger; - use Yii; use yiiunit\TestCase; /** @@ -39,14 +42,14 @@ namespace yiiunit\framework\log { /** * @var bool */ - static $microtimeIsMocked = false; + public static $microtimeIsMocked = false; /** * Array of static functions * * @var array */ - static $functions = []; + public static $functions = []; protected function setUp() { @@ -86,7 +89,7 @@ namespace yiiunit\framework\log { } /** - * @covers yii\log\Dispatcher::setLogger() + * @covers \yii\log\Dispatcher::setLogger() */ public function testSetLogger() { @@ -106,7 +109,7 @@ namespace yiiunit\framework\log { } /** - * @covers yii\log\Dispatcher::getTraceLevel() + * @covers \yii\log\Dispatcher::getTraceLevel() */ public function testGetTraceLevel() { @@ -116,7 +119,7 @@ namespace yiiunit\framework\log { } /** - * @covers yii\log\Dispatcher::setTraceLevel() + * @covers \yii\log\Dispatcher::setTraceLevel() */ public function testSetTraceLevel() { @@ -126,7 +129,7 @@ namespace yiiunit\framework\log { } /** - * @covers yii\log\Dispatcher::getFlushInterval() + * @covers \yii\log\Dispatcher::getFlushInterval() */ public function testGetFlushInterval() { @@ -136,7 +139,7 @@ namespace yiiunit\framework\log { } /** - * @covers yii\log\Dispatcher::setFlushInterval() + * @covers \yii\log\Dispatcher::setFlushInterval() */ public function testSetFlushInterval() { @@ -146,7 +149,7 @@ namespace yiiunit\framework\log { } /** - * @covers yii\log\Dispatcher::dispatch() + * @covers \yii\log\Dispatcher::dispatch() */ public function testDispatchWithDisabledTarget() { @@ -162,7 +165,7 @@ namespace yiiunit\framework\log { } /** - * @covers yii\log\Dispatcher::dispatch() + * @covers \yii\log\Dispatcher::dispatch() */ public function testDispatchWithSuccessTargetCollect() { @@ -182,7 +185,7 @@ namespace yiiunit\framework\log { } /** - * @covers yii\log\Dispatcher::dispatch() + * @covers \yii\log\Dispatcher::dispatch() */ public function testDispatchWithFakeTarget2ThrowExceptionWhenCollect() { @@ -201,13 +204,13 @@ namespace yiiunit\framework\log { [$this->equalTo('messages'), $this->equalTo(true)], [ [[ - 'Unable to send log via '.get_class($target1).': Exception: some error', + 'Unable to send log via ' . get_class($target1) . ': Exception: some error', Logger::LEVEL_WARNING, 'yii\log\Dispatcher::dispatch', 'time data', [], ]], - true + true, ] ); @@ -229,7 +232,7 @@ namespace yiiunit\framework\log { } /** - * @covers yii\log\Dispatcher::init() + * @covers \yii\log\Dispatcher::init() */ public function testInitWithCreateTargetObject() { @@ -237,9 +240,9 @@ namespace yiiunit\framework\log { [ 'targets' => [ 'syslog' => [ - 'class' => 'yii\log\SyslogTarget' - ] - ] + 'class' => 'yii\log\SyslogTarget', + ], + ], ] ); @@ -251,7 +254,8 @@ namespace yiiunit\framework\log { * @param $arguments * @return mixed */ - public static function __callStatic($name, $arguments) { + public static function __callStatic($name, $arguments) + { if (isset(static::$functions[$name]) && is_callable(static::$functions[$name])) { $arguments = isset($arguments[0]) ? $arguments[0] : $arguments; return forward_static_call(static::$functions[$name], $arguments); diff --git a/tests/framework/log/EmailTargetTest.php b/tests/framework/log/EmailTargetTest.php index c1062a7..acb73f3 100644 --- a/tests/framework/log/EmailTargetTest.php +++ b/tests/framework/log/EmailTargetTest.php @@ -1,6 +1,8 @@ + * @link http://www.yiiframework.com/ + * @copyright Copyright (c) 2008 Yii Software LLC + * @license http://www.yiiframework.com/license/ */ namespace yiiunit\framework\log; @@ -10,7 +12,6 @@ use yiiunit\TestCase; /** * Class EmailTargetTest - * @package yiiunit\framework\log * @group log */ class EmailTargetTest extends TestCase @@ -32,16 +33,16 @@ class EmailTargetTest extends TestCase } /** - * @covers yii\log\EmailTarget::init() + * @covers \yii\log\EmailTarget::init() */ public function testInitWithOptionTo() { - $target = new EmailTarget(['mailer' => $this->mailer, 'message'=> ['to' => 'developer1@example.com']]); - $this->assertTrue(is_object($target)); // should be no exception during `init()` + $target = new EmailTarget(['mailer' => $this->mailer, 'message' => ['to' => 'developer1@example.com']]); + $this->assertInternalType('object', $target); // should be no exception during `init()` } /** - * @covers yii\log\EmailTarget::init() + * @covers \yii\log\EmailTarget::init() * @expectedException \yii\base\InvalidConfigException * @expectedExceptionMessage The "to" option must be set for EmailTarget::message. */ @@ -51,8 +52,8 @@ class EmailTargetTest extends TestCase } /** - * @covers yii\log\EmailTarget::export() - * @covers yii\log\EmailTarget::composeMessage() + * @covers \yii\log\EmailTarget::export() + * @covers \yii\log\EmailTarget::composeMessage() */ public function testExportWithSubject() { @@ -76,11 +77,11 @@ class EmailTargetTest extends TestCase ->setConstructorArgs([ [ 'mailer' => $this->mailer, - 'message'=> [ + 'message' => [ 'to' => 'developer@example.com', - 'subject' => 'Hello world' - ] - ] + 'subject' => 'Hello world', + ], + ], ]) ->getMock(); @@ -95,8 +96,8 @@ class EmailTargetTest extends TestCase } /** - * @covers yii\log\EmailTarget::export() - * @covers yii\log\EmailTarget::composeMessage() + * @covers \yii\log\EmailTarget::export() + * @covers \yii\log\EmailTarget::composeMessage() */ public function testExportWithoutSubject() { @@ -120,10 +121,10 @@ class EmailTargetTest extends TestCase ->setConstructorArgs([ [ 'mailer' => $this->mailer, - 'message'=> [ + 'message' => [ 'to' => 'developer@example.com', - ] - ] + ], + ], ]) ->getMock(); diff --git a/tests/framework/log/FileTargetTest.php b/tests/framework/log/FileTargetTest.php index 9e0e90e..b62e351 100644 --- a/tests/framework/log/FileTargetTest.php +++ b/tests/framework/log/FileTargetTest.php @@ -1,14 +1,16 @@ + * @link http://www.yiiframework.com/ + * @copyright Copyright (c) 2008 Yii Software LLC + * @license http://www.yiiframework.com/license/ */ namespace yiiunit\framework\log; +use Yii; use yii\helpers\FileHelper; use yii\log\Dispatcher; use yii\log\Logger; -use Yii; use yiiunit\TestCase; /** @@ -26,7 +28,7 @@ class FileTargetTest extends TestCase { return [ [true], - [false] + [false], ]; } @@ -50,9 +52,9 @@ class FileTargetTest extends TestCase 'maxFileSize' => 1024, // 1 MB 'maxLogFiles' => 1, // one file for rotation and one normal log file 'logVars' => [], - 'rotateByCopy' => $rotateByCopy - ] - ] + 'rotateByCopy' => $rotateByCopy, + ], + ], ]); // one file @@ -102,4 +104,4 @@ class FileTargetTest extends TestCase $this->assertFileNotExists($logFile . '.3'); $this->assertFileNotExists($logFile . '.4'); } -} \ No newline at end of file +} diff --git a/tests/framework/log/LoggerTest.php b/tests/framework/log/LoggerTest.php index 6725158..ce4932b 100644 --- a/tests/framework/log/LoggerTest.php +++ b/tests/framework/log/LoggerTest.php @@ -1,10 +1,13 @@ + * @link http://www.yiiframework.com/ + * @copyright Copyright (c) 2008 Yii Software LLC + * @license http://www.yiiframework.com/license/ */ namespace yiiunit\framework\log; +use yii\log\Dispatcher; use yii\log\Logger; use yiiunit\TestCase; @@ -19,20 +22,20 @@ class LoggerTest extends TestCase protected $logger; /** - * @var Dispatcher + * @var Dispatcher|\PHPUnit_Framework_MockObject_MockObject */ protected $dispatcher; protected function setUp() { $this->logger = new Logger(); - $this->dispatcher = $this->getMockBuilder('yii\\log\\Dispatcher') + $this->dispatcher = $this->getMockBuilder('yii\log\Dispatcher') ->setMethods(['dispatch']) ->getMock(); } /** - * @covers yii\log\Logger::Log() + * @covers \yii\log\Logger::Log() */ public function testLog() { @@ -55,7 +58,7 @@ class LoggerTest extends TestCase } /** - * @covers yii\log\Logger::Log() + * @covers \yii\log\Logger::Log() */ public function testLogWithTraceLevel() { @@ -68,21 +71,22 @@ class LoggerTest extends TestCase $this->assertEquals('application', $this->logger->messages[0][2]); $this->assertEquals([ 'file' => __FILE__, - 'line' => 64, + 'line' => 67, 'function' => 'log', 'class' => get_class($this->logger), - 'type' => '->' + 'type' => '->', ], $this->logger->messages[0][4][0]); $this->assertCount(3, $this->logger->messages[0][4]); $this->assertGreaterThanOrEqual($memory, $this->logger->messages[0][5]); } /** - * @covers yii\log\Logger::Log() + * @covers \yii\log\Logger::Log() */ public function testLogWithFlush() { - $logger = $this->getMockBuilder('yii\\log\\Logger') + /* @var $logger Logger|\PHPUnit_Framework_MockObject_MockObject */ + $logger = $this->getMockBuilder('yii\log\Logger') ->setMethods(['flush']) ->getMock(); $logger->flushInterval = 1; @@ -91,7 +95,7 @@ class LoggerTest extends TestCase } /** - * @covers yii\log\Logger::Flush() + * @covers \yii\log\Logger::Flush() */ public function testFlushWithoutDispatcher() { @@ -105,7 +109,7 @@ class LoggerTest extends TestCase } /** - * @covers yii\log\Logger::Flush() + * @covers \yii\log\Logger::Flush() */ public function testFlushWithDispatcherAndDefaultParam() { @@ -120,7 +124,7 @@ class LoggerTest extends TestCase } /** - * @covers yii\log\Logger::Flush() + * @covers \yii\log\Logger::Flush() */ public function testFlushWithDispatcherAndDefinedParam() { @@ -135,7 +139,7 @@ class LoggerTest extends TestCase } /** - * @covers yii\log\Logger::getDbProfiling() + * @covers \yii\log\Logger::getDbProfiling() */ public function testGetDbProfiling() { @@ -145,7 +149,8 @@ class LoggerTest extends TestCase ['duration' => 30], ]; - $logger = $this->getMockBuilder('yii\\log\\Logger') + /* @var $logger Logger|\PHPUnit_Framework_MockObject_MockObject */ + $logger = $this->getMockBuilder('yii\log\Logger') ->setMethods(['getProfiling']) ->getMock(); $logger->method('getProfiling')->willReturn($timings); @@ -156,7 +161,7 @@ class LoggerTest extends TestCase } /** - * @covers yii\log\Logger::calculateTimings() + * @covers \yii\log\Logger::calculateTimings() */ public function testCalculateTimingsWithEmptyMessages() { @@ -164,7 +169,7 @@ class LoggerTest extends TestCase } /** - * @covers yii\log\Logger::calculateTimings() + * @covers \yii\log\Logger::calculateTimings() */ public function testCalculateTimingsWithProfileNotBeginOrEnd() { @@ -180,7 +185,7 @@ class LoggerTest extends TestCase } /** - * @covers yii\log\Logger::calculateTimings() + * @covers \yii\log\Logger::calculateTimings() * * See https://github.com/yiisoft/yii2/issues/14264 */ @@ -199,8 +204,8 @@ class LoggerTest extends TestCase 'level' => 0, 'duration' => 5, 'memory' => 2097152, - 'memoryDiff' => 1048576 - ] + 'memoryDiff' => 1048576, + ], ], $this->logger->calculateTimings($messages) ); @@ -218,15 +223,15 @@ class LoggerTest extends TestCase 'level' => 0, 'duration' => 5, 'memory' => 2097152, - 'memoryDiff' => 1048576 - ] + 'memoryDiff' => 1048576, + ], ], $this->logger->calculateTimings($messages) ); } /** - * @covers yii\log\Logger::calculateTimings() + * @covers \yii\log\Logger::calculateTimings() */ public function testCalculateTimingsWithProfileBeginEndAndNestedLevels() { @@ -245,7 +250,7 @@ class LoggerTest extends TestCase 'level' => 0, 'duration' => 70, 'memory' => 4194304, - 'memoryDiff' => 3145728 + 'memoryDiff' => 3145728, ], [ 'info' => 'secondLevel', @@ -255,8 +260,8 @@ class LoggerTest extends TestCase 'level' => 1, 'duration' => 40, 'memory' => 3145728, - 'memoryDiff' => 1048576 - ] + 'memoryDiff' => 1048576, + ], ], $this->logger->calculateTimings($messages) ); @@ -265,7 +270,7 @@ class LoggerTest extends TestCase /** * See https://github.com/yiisoft/yii2/issues/14133 * - * @covers yii\log\Logger::calculateTimings() + * @covers \yii\log\Logger::calculateTimings() */ public function testCalculateTimingsWithProfileBeginEndAndNestedMixedLevels() { @@ -284,7 +289,7 @@ class LoggerTest extends TestCase 'level' => 1, 'duration' => 70, 'memory' => 4194304, - 'memoryDiff' => 3145728 + 'memoryDiff' => 3145728, ], [ 'info' => 'secondLevel', @@ -294,15 +299,15 @@ class LoggerTest extends TestCase 'level' => 0, 'duration' => 40, 'memory' => 3145728, - 'memoryDiff' => 1048576 - ] + 'memoryDiff' => 1048576, + ], ], $this->logger->calculateTimings($messages) ); } /** - * @covers yii\log\Logger::getElapsedTime() + * @covers \yii\log\Logger::getElapsedTime() */ public function testGetElapsedTime() { @@ -317,7 +322,7 @@ class LoggerTest extends TestCase } /** - * @covers yii\log\Logger::getLevelName() + * @covers \yii\log\Logger::getLevelName() */ public function testGetLevelName() { @@ -332,13 +337,14 @@ class LoggerTest extends TestCase } /** - * @covers yii\log\Logger::getProfiling() + * @covers \yii\log\Logger::getProfiling() */ public function testGetProfilingWithEmptyCategoriesAndExcludeCategories() { $messages = ['anyData']; $returnValue = 'return value'; - $logger = $this->getMockBuilder('yii\\log\\Logger') + /* @var $logger Logger|\PHPUnit_Framework_MockObject_MockObject */ + $logger = $this->getMockBuilder('yii\log\Logger') ->setMethods(['calculateTimings']) ->getMock(); @@ -349,7 +355,7 @@ class LoggerTest extends TestCase } /** - * @covers yii\log\Logger::getProfiling() + * @covers \yii\log\Logger::getProfiling() */ public function testGetProfilingWithNotEmptyCategoriesAndNotMatched() { @@ -362,9 +368,10 @@ class LoggerTest extends TestCase 'trace' => 'trace', 'level' => 0, 'duration' => 5, - ] + ], ]; - $logger = $this->getMockBuilder('yii\\log\\Logger') + /* @var $logger Logger|\PHPUnit_Framework_MockObject_MockObject */ + $logger = $this->getMockBuilder('yii\log\Logger') ->setMethods(['calculateTimings']) ->getMock(); @@ -375,7 +382,7 @@ class LoggerTest extends TestCase } /** - * @covers yii\log\Logger::getProfiling() + * @covers \yii\log\Logger::getProfiling() */ public function testGetProfilingWithNotEmptyCategoriesAndMatched() { @@ -398,12 +405,13 @@ class LoggerTest extends TestCase ]; $returnValue = [ 'anyKey' => $matchedByCategoryName, - $secondCategory + $secondCategory, ]; - /** + /* * Matched by category name */ - $logger = $this->getMockBuilder('yii\\log\\Logger') + /* @var $logger Logger|\PHPUnit_Framework_MockObject_MockObject */ + $logger = $this->getMockBuilder('yii\log\Logger') ->setMethods(['calculateTimings']) ->getMock(); @@ -412,10 +420,11 @@ class LoggerTest extends TestCase $logger->expects($this->once())->method('calculateTimings')->with($this->equalTo($messages)); $this->assertEquals([$matchedByCategoryName], $logger->getProfiling(['category'])); - /** + /* * Matched by prefix */ - $logger = $this->getMockBuilder('yii\\log\\Logger') + /* @var $logger Logger|\PHPUnit_Framework_MockObject_MockObject */ + $logger = $this->getMockBuilder('yii\log\Logger') ->setMethods(['calculateTimings']) ->getMock(); @@ -426,7 +435,7 @@ class LoggerTest extends TestCase } /** - * @covers yii\log\Logger::getProfiling() + * @covers \yii\log\Logger::getProfiling() */ public function testGetProfilingWithNotEmptyCategoriesMatchedAndExcludeCategories() { @@ -457,13 +466,14 @@ class LoggerTest extends TestCase 'trace' => 'trace', 'level' => 0, 'duration' => 5, - ] + ], ]; - /** + /* * Exclude by category name */ - $logger = $this->getMockBuilder('yii\\log\\Logger') + /* @var $logger Logger|\PHPUnit_Framework_MockObject_MockObject */ + $logger = $this->getMockBuilder('yii\log\Logger') ->setMethods(['calculateTimings']) ->getMock(); @@ -472,10 +482,11 @@ class LoggerTest extends TestCase $logger->expects($this->once())->method('calculateTimings')->with($this->equalTo($messages)); $this->assertEquals([$fistCategory, $secondCategory], $logger->getProfiling(['cat*'], ['category3'])); - /** + /* * Exclude by category prefix */ - $logger = $this->getMockBuilder('yii\\log\\Logger') + /* @var $logger Logger|\PHPUnit_Framework_MockObject_MockObject */ + $logger = $this->getMockBuilder('yii\log\Logger') ->setMethods(['calculateTimings']) ->getMock(); diff --git a/tests/framework/log/MySQLTargetTest.php b/tests/framework/log/MySQLTargetTest.php index 50fa79b..fc7fd01 100644 --- a/tests/framework/log/MySQLTargetTest.php +++ b/tests/framework/log/MySQLTargetTest.php @@ -1,5 +1,9 @@ + * @link http://www.yiiframework.com/ + * @copyright Copyright (c) 2008 Yii Software LLC + * @license http://www.yiiframework.com/license/ */ namespace yii\log { - function openlog() { + function openlog() + { \yiiunit\framework\log\SyslogTargetTest::openlog(func_get_args()); } - function syslog() { + function syslog() + { \yiiunit\framework\log\SyslogTargetTest::syslog(func_get_args()); } - function closelog() { + function closelog() + { \yiiunit\framework\log\SyslogTargetTest::closelog(func_get_args()); } } @@ -22,13 +27,12 @@ namespace yiiunit\framework\log { use PHPUnit_Framework_MockObject_MockObject; use yii\helpers\VarDumper; - use yiiunit\TestCase; use yii\log\Logger; + use yiiunit\TestCase; /** * Class SyslogTargetTest * - * @package yiiunit\framework\log * @group log */ class SyslogTargetTest extends TestCase @@ -38,7 +42,7 @@ namespace yiiunit\framework\log { * * @var array */ - static $functions = []; + public static $functions = []; /** * @var PHPUnit_Framework_MockObject_MockObject @@ -56,7 +60,7 @@ namespace yiiunit\framework\log { } /** - * @covers yii\log\SyslogTarget::export() + * @covers \yii\log\SyslogTarget::export() */ public function testExport() { @@ -148,7 +152,8 @@ namespace yiiunit\framework\log { * @param $arguments * @return mixed */ - public static function __callStatic($name, $arguments) { + public static function __callStatic($name, $arguments) + { if (isset(static::$functions[$name]) && is_callable(static::$functions[$name])) { $arguments = isset($arguments[0]) ? $arguments[0] : $arguments; return forward_static_call(static::$functions[$name], $arguments); @@ -157,7 +162,7 @@ namespace yiiunit\framework\log { } /** - * @covers yii\log\SyslogTarget::formatMessage() + * @covers \yii\log\SyslogTarget::formatMessage() */ public function testFormatMessageWhereTextIsString() { @@ -174,7 +179,7 @@ namespace yiiunit\framework\log { } /** - * @covers yii\log\SyslogTarget::formatMessage() + * @covers \yii\log\SyslogTarget::formatMessage() */ public function testFormatMessageWhereTextIsException() { @@ -192,7 +197,7 @@ namespace yiiunit\framework\log { } /** - * @covers yii\log\SyslogTarget::formatMessage() + * @covers \yii\log\SyslogTarget::formatMessage() */ public function testFormatMessageWhereTextIsNotStringAndNotThrowable() { diff --git a/tests/framework/log/TargetTest.php b/tests/framework/log/TargetTest.php index 67316da..a30d203 100644 --- a/tests/framework/log/TargetTest.php +++ b/tests/framework/log/TargetTest.php @@ -1,6 +1,8 @@ + * @link http://www.yiiframework.com/ + * @copyright Copyright (c) 2008 Yii Software LLC + * @license http://www.yiiframework.com/license/ */ namespace yiiunit\framework\log; @@ -25,7 +27,7 @@ class TargetTest extends TestCase [['levels' => 0], ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']], [ ['levels' => Logger::LEVEL_INFO | Logger::LEVEL_WARNING | Logger::LEVEL_ERROR | Logger::LEVEL_TRACE], - ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] + ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], ], [['levels' => ['error']], ['B', 'G', 'H']], [['levels' => Logger::LEVEL_ERROR], ['B', 'G', 'H']], @@ -54,7 +56,7 @@ class TargetTest extends TestCase { static::$messages = []; - $logger = new Logger; + $logger = new Logger(); $dispatcher = new Dispatcher([ 'logger' => $logger, 'targets' => [new TestTarget(array_merge($filter, ['logVars' => []]))], diff --git a/tests/framework/mail/BaseMailerTest.php b/tests/framework/mail/BaseMailerTest.php index 11d6bea..4f840b4 100644 --- a/tests/framework/mail/BaseMailerTest.php +++ b/tests/framework/mail/BaseMailerTest.php @@ -1,12 +1,17 @@ mockApplication([ 'components' => [ 'mailer' => $this->createTestMailComponent(), - ] + ], ]); $filePath = $this->getTestFilePath(); if (!file_exists($filePath)) { @@ -76,11 +81,11 @@ class BaseMailerTest extends TestCase 'params' => [ 'param1' => 'value1', 'param2' => 'value2', - ] + ], ]; $mailer->setView($viewConfig); $view = $mailer->getView(); - $this->assertTrue(is_object($view), 'Unable to setup view via config!'); + $this->assertInternalType('object', $view, 'Unable to setup view via config!'); $this->assertEquals($viewConfig['params'], $view->params, 'Unable to configure view via config array!'); } @@ -91,14 +96,14 @@ class BaseMailerTest extends TestCase { $mailer = new Mailer(); $view = $mailer->getView(); - $this->assertTrue(is_object($view), 'Unable to get default view!'); + $this->assertInternalType('object', $view, 'Unable to get default view!'); } public function testCreateMessage() { $mailer = new Mailer(); $message = $mailer->compose(); - $this->assertTrue(is_object($message), 'Unable to create message instance!'); + $this->assertInternalType('object', $message, 'Unable to create message instance!'); $this->assertEquals($mailer->messageClass, get_class($message), 'Invalid message class!'); } @@ -149,7 +154,7 @@ class BaseMailerTest extends TestCase file_put_contents($viewFileName, $viewFileContent); $params = [ - 'testParam' => 'test output' + 'testParam' => 'test output', ]; $renderResult = $mailer->render($viewName, $params); $this->assertEquals($params['testParam'], $renderResult); @@ -432,13 +437,21 @@ class Message extends BaseMessage return $this; } - public function attachContent($content, array $options = []) {} + public function attachContent($content, array $options = []) + { + } - public function attach($fileName, array $options = []) {} + public function attach($fileName, array $options = []) + { + } - public function embed($fileName, array $options = []) {} + public function embed($fileName, array $options = []) + { + } - public function embedContent($content, array $options = []) {} + public function embedContent($content, array $options = []) + { + } public function toString() { diff --git a/tests/framework/mail/BaseMessageTest.php b/tests/framework/mail/BaseMessageTest.php index 539b730..92819e4 100644 --- a/tests/framework/mail/BaseMessageTest.php +++ b/tests/framework/mail/BaseMessageTest.php @@ -1,4 +1,9 @@ mockApplication([ 'components' => [ - 'mailer' => $this->createTestEmailComponent() - ] + 'mailer' => $this->createTestEmailComponent(), + ], ]); } @@ -84,49 +89,63 @@ class TestMessage extends BaseMessage return ''; } - public function setCharset($charset) {} + public function setCharset($charset) + { + } public function getFrom() { return ''; } - public function setFrom($from) {} + public function setFrom($from) + { + } public function getReplyTo() { return ''; } - public function setReplyTo($replyTo) {} + public function setReplyTo($replyTo) + { + } public function getTo() { return ''; } - public function setTo($to) {} + public function setTo($to) + { + } public function getCc() { return ''; } - public function setCc($cc) {} + public function setCc($cc) + { + } public function getBcc() { return ''; } - public function setBcc($bcc) {} + public function setBcc($bcc) + { + } public function getSubject() { return ''; } - public function setSubject($subject) {} + public function setSubject($subject) + { + } public function setTextBody($text) { @@ -138,13 +157,21 @@ class TestMessage extends BaseMessage $this->html = $html; } - public function attachContent($content, array $options = []) {} + public function attachContent($content, array $options = []) + { + } - public function attach($fileName, array $options = []) {} + public function attach($fileName, array $options = []) + { + } - public function embed($fileName, array $options = []) {} + public function embed($fileName, array $options = []) + { + } - public function embedContent($content, array $options = []) {} + public function embedContent($content, array $options = []) + { + } public function toString() { diff --git a/tests/framework/mutex/FileMutexTest.php b/tests/framework/mutex/FileMutexTest.php index 17d36d2..778f0f8 100644 --- a/tests/framework/mutex/FileMutexTest.php +++ b/tests/framework/mutex/FileMutexTest.php @@ -1,4 +1,9 @@ $this->getConnection(), ]); } - } diff --git a/tests/framework/mutex/PgsqlMutexTest.php b/tests/framework/mutex/PgsqlMutexTest.php index b61ca13..fd26360 100644 --- a/tests/framework/mutex/PgsqlMutexTest.php +++ b/tests/framework/mutex/PgsqlMutexTest.php @@ -1,4 +1,9 @@ $this->getConnection(), ]); } - } diff --git a/tests/framework/rbac/ActionRule.php b/tests/framework/rbac/ActionRule.php index 30aefdf..a5fa76b 100644 --- a/tests/framework/rbac/ActionRule.php +++ b/tests/framework/rbac/ActionRule.php @@ -1,4 +1,9 @@ runAction($route, $params); - echo "Result is " . $result; + echo 'Result is ' . $result; if ($result !== Controller::EXIT_CODE_NORMAL) { ob_end_flush(); } else { @@ -106,7 +112,7 @@ abstract class DbManagerTestCase extends ManagerTestCase public static function createConnection() { - $db = new Connection; + $db = new Connection(); $db->dsn = static::$database['dsn']; if (isset(static::$database['username'])) { $db->username = static::$database['username']; diff --git a/tests/framework/rbac/ExposedPhpManager.php b/tests/framework/rbac/ExposedPhpManager.php index bf7c111..a3a97dd 100644 --- a/tests/framework/rbac/ExposedPhpManager.php +++ b/tests/framework/rbac/ExposedPhpManager.php @@ -1,4 +1,10 @@ prepareData(); $rule = $this->auth->getRule('isAuthor'); - $rule->name = "newName"; + $rule->name = 'newName'; $rule->reallyReally = false; $this->auth->update('isAuthor', $rule); @@ -104,7 +109,7 @@ abstract class ManagerTestCase extends TestCase $this->assertEquals(null, $rule); $rule = $this->auth->getRule('newName'); - $this->assertEquals("newName", $rule->name); + $this->assertEquals('newName', $rule->name); $this->assertEquals(false, $rule->reallyReally); $rule->reallyReally = true; @@ -205,7 +210,7 @@ abstract class ManagerTestCase extends TestCase protected function prepareData() { - $rule = new AuthorRule; + $rule = new AuthorRule(); $this->auth->add($rule); $uniqueTrait = $this->auth->createPermission('Fast Metabolism'); diff --git a/tests/framework/rbac/MySQLManagerCacheTest.php b/tests/framework/rbac/MySQLManagerCacheTest.php index 5c2af42..bb3ce87 100644 --- a/tests/framework/rbac/MySQLManagerCacheTest.php +++ b/tests/framework/rbac/MySQLManagerCacheTest.php @@ -1,4 +1,10 @@ $this->getConnection(), 'cache' => new FileCache(['cachePath' => '@yiiunit/runtime/cache']), - 'defaultRoles' => ['myDefaultRole'] + 'defaultRoles' => ['myDefaultRole'], ]); } } diff --git a/tests/framework/rbac/MySQLManagerTest.php b/tests/framework/rbac/MySQLManagerTest.php index 8747242..b37c167 100644 --- a/tests/framework/rbac/MySQLManagerTest.php +++ b/tests/framework/rbac/MySQLManagerTest.php @@ -1,4 +1,10 @@ $this->getConnection(), 'cache' => new FileCache(['cachePath' => '@yiiunit/runtime/cache']), - 'defaultRoles' => ['myDefaultRole'] + 'defaultRoles' => ['myDefaultRole'], ]); } - } diff --git a/tests/framework/rbac/PgSQLManagerTest.php b/tests/framework/rbac/PgSQLManagerTest.php index 1ba965d..bf211ad 100644 --- a/tests/framework/rbac/PgSQLManagerTest.php +++ b/tests/framework/rbac/PgSQLManagerTest.php @@ -1,4 +1,10 @@ $this->getItemFile(), 'assignmentFile' => $this->getAssignmentFile(), 'ruleFile' => $this->getRuleFile(), - 'defaultRoles' => ['myDefaultRole'] + 'defaultRoles' => ['myDefaultRole'], ]); } @@ -121,7 +126,8 @@ class PhpManagerTest extends ManagerTestCase $this->assertTrue($this->auth->update($name, $permission), 'You should be able to update name.'); } - public function testUpdateDescription() { + public function testUpdateDescription() + { $this->prepareData(); $name = 'readPost'; $permission = $this->auth->getPermission($name); @@ -153,6 +159,5 @@ class PhpManagerTest extends ManagerTestCase $this->assertContains('NewAdmin', file_get_contents($this->getAssignmentFile())); $this->auth->remove($role); $this->assertNotContains('NewAdmin', file_get_contents($this->getAssignmentFile())); - } } diff --git a/tests/framework/rbac/SqliteManagerTest.php b/tests/framework/rbac/SqliteManagerTest.php index 7e18a94..c94dcf4 100644 --- a/tests/framework/rbac/SqliteManagerTest.php +++ b/tests/framework/rbac/SqliteManagerTest.php @@ -1,4 +1,10 @@ '/index.php', ], ], - ], 'yii\web\Application'); TestModel::$fields = ['field1', 'field2']; @@ -45,7 +49,7 @@ class SerializerTest extends TestCase [ 'field' => 'field2', 'message' => 'Multiple error 1', - ] + ], ], $serializer->serialize($model)); } @@ -142,7 +146,7 @@ class SerializerTest extends TestCase new ArrayDataProvider([ 'allModels' => [ ['id' => 1, 'username' => 'Bob'], - ['id' => 2, 'username' => 'Tom'] + ['id' => 2, 'username' => 'Tom'], ], 'pagination' => [ 'route' => '/', @@ -150,71 +154,71 @@ class SerializerTest extends TestCase ]), [ ['id' => 1, 'username' => 'Bob'], - ['id' => 2, 'username' => 'Tom'] - ] + ['id' => 2, 'username' => 'Tom'], + ], ], [ new ArrayDataProvider([ 'allModels' => [ ['id' => 1, 'username' => 'Bob'], - ['id' => 2, 'username' => 'Tom'] + ['id' => 2, 'username' => 'Tom'], ], 'pagination' => [ 'route' => '/', 'pageSize' => 1, - 'page' => 0 + 'page' => 0, ], ]), [ ['id' => 1, 'username' => 'Bob'], - ] + ], ], [ new ArrayDataProvider([ 'allModels' => [ ['id' => 1, 'username' => 'Bob'], - ['id' => 2, 'username' => 'Tom'] + ['id' => 2, 'username' => 'Tom'], ], 'pagination' => [ 'route' => '/', 'pageSize' => 1, - 'page' => 1 + 'page' => 1, ], ]), [ - ['id' => 2, 'username' => 'Tom'] - ] + ['id' => 2, 'username' => 'Tom'], + ], ], [ new ArrayDataProvider([ 'allModels' => [ 'Bob' => ['id' => 1, 'username' => 'Bob'], - 'Tom' => ['id' => 2, 'username' => 'Tom'] + 'Tom' => ['id' => 2, 'username' => 'Tom'], ], 'pagination' => [ 'route' => '/', 'pageSize' => 1, - 'page' => 1 + 'page' => 1, ], ]), [ - ['id' => 2, 'username' => 'Tom'] - ] + ['id' => 2, 'username' => 'Tom'], + ], ], [ new ArrayDataProvider([ 'allModels' => [ ['id' => 1, 'username' => 'Bob'], - ['id' => 2, 'username' => 'Tom'] + ['id' => 2, 'username' => 'Tom'], ], 'pagination' => [ 'route' => '/', 'pageSize' => 1, - 'page' => 1 + 'page' => 1, ], ]), [ - 1 => ['id' => 2, 'username' => 'Tom'] + 1 => ['id' => 2, 'username' => 'Tom'], ], true, ], @@ -227,11 +231,11 @@ class SerializerTest extends TestCase 'pagination' => [ 'route' => '/', 'pageSize' => 1, - 'page' => 1 + 'page' => 1, ], ]), [ - 'Tom' => ['id' => 2, 'username' => 'Tom'] + 'Tom' => ['id' => 2, 'username' => 'Tom'], ], true, ], @@ -290,4 +294,4 @@ class TestModel extends Model { return static::$extraFields; } -} \ No newline at end of file +} diff --git a/tests/framework/rest/UrlRuleTest.php b/tests/framework/rest/UrlRuleTest.php index c78d5b5..1d186a7 100644 --- a/tests/framework/rest/UrlRuleTest.php +++ b/tests/framework/rest/UrlRuleTest.php @@ -1,4 +1,9 @@ getTestsForControllerNamePluralization(); foreach ($suites as $i => $suite) { - list ($name, $tests) = $suite; + list($name, $tests) = $suite; foreach ($tests as $j => $test) { - list ($config, $expected) = $test; + list($config, $expected) = $test; $rule = new UrlRule($config); $this->assertEquals($expected, $rule->controller, "Test#$i-$j: $name"); } @@ -37,10 +42,10 @@ class UrlRuleTest extends TestCase public function testParseRequest() { $manager = new UrlManager(['cache' => null]); - $request = new Request(['hostInfo' => 'http://en.example.com', 'methodParam' => '_METHOD',]); + $request = new Request(['hostInfo' => 'http://en.example.com', 'methodParam' => '_METHOD']); $suites = $this->getTestsForParseRequest(); foreach ($suites as $i => $suite) { - list ($name, $config, $tests) = $suite; + list($name, $config, $tests) = $suite; $rule = new UrlRule($config); foreach ($tests as $j => $test) { $request->pathInfo = $test[0]; @@ -78,14 +83,14 @@ class UrlRuleTest extends TestCase ], [ 'prefixed route', - ['controller' => 'post', 'prefix' => 'admin',], + ['controller' => 'post', 'prefix' => 'admin'], [ ['admin/posts', 'post/index'], ], ], [ 'suffixed route', - ['controller' => 'post', 'suffix' => '.json',], + ['controller' => 'post', 'suffix' => '.json'], [ ['posts.json', 'post/index'], ['posts.json', 'post/create', [], 'POST'], @@ -111,12 +116,11 @@ class UrlRuleTest extends TestCase ['posts/123', 'post/delete', ['id' => 123], 'DELETE'], ['posts/new', false], - ], ], [ 'only selected routes', - ['controller' => 'post', 'only' => ['index'],], + ['controller' => 'post', 'only' => ['index']], [ ['posts', 'post/index'], ['posts/123', false], @@ -125,7 +129,7 @@ class UrlRuleTest extends TestCase ], [ 'except routes', - ['controller' => 'post', 'except' => ['delete', 'create'],], + ['controller' => 'post', 'except' => ['delete', 'create']], [ ['posts', 'post/index'], ['posts/123', 'post/view', ['id' => 123]], @@ -135,7 +139,7 @@ class UrlRuleTest extends TestCase ], [ 'extra patterns', - ['controller' => 'post', 'extraPatterns' => ['POST new' => 'create',],], + ['controller' => 'post', 'extraPatterns' => ['POST new' => 'create']], [ ['posts/new', 'post/create', [], 'POST'], ['posts', 'post/create', [], 'POST'], @@ -143,14 +147,14 @@ class UrlRuleTest extends TestCase ], [ 'extra patterns overwrite patterns', - ['controller' => 'post', 'extraPatterns' => ['POST' => 'new',],], + ['controller' => 'post', 'extraPatterns' => ['POST' => 'new']], [ ['posts', 'post/new', [], 'POST'], ], ], [ 'extra patterns rule is higher priority than patterns', - ['controller' => 'post', 'extraPatterns' => ['GET 1337' => 'leet',],], + ['controller' => 'post', 'extraPatterns' => ['GET 1337' => 'leet']], [ ['posts/1337', 'post/leet'], ['posts/1338', 'post/view', ['id' => 1338]], @@ -163,38 +167,43 @@ class UrlRuleTest extends TestCase { return [ [ - 'pluralized automatically', [ + 'pluralized automatically', [ - ['controller' => 'user'], - ['users' => 'user'] - ], - [ - ['controller' => 'admin/user'], - ['admin/users' => 'admin/user'] - ], - [ - ['controller' => ['admin/user', 'post']], - ['admin/users' => 'admin/user', 'posts' => 'post'] + [ + ['controller' => 'user'], + ['users' => 'user'], + ], + [ + ['controller' => 'admin/user'], + ['admin/users' => 'admin/user'], + ], + [ + ['controller' => ['admin/user', 'post']], + ['admin/users' => 'admin/user', 'posts' => 'post'], + ], ], - ]], + ], [ - 'explicitly specified', [ + 'explicitly specified', [ - ['controller' => ['customer' => 'user']], - ['customer' => 'user'] - ] - ]], + [ + ['controller' => ['customer' => 'user']], + ['customer' => 'user'], + ], + ], + ], [ - 'do not pluralize', [ + 'do not pluralize', [ [ - 'pluralize' => false, - 'controller' => ['admin/user', 'post'], + [ + 'pluralize' => false, + 'controller' => ['admin/user', 'post'], + ], + ['admin/user' => 'admin/user', 'post' => 'post'], ], - ['admin/user' => 'admin/user', 'post' => 'post',] - ] - ]], - + ], + ], ]; } @@ -216,12 +225,12 @@ class UrlRuleTest extends TestCase 'pluralize' => true, ], [ // test cases: route, expected - [ ['v1/channel/index'], 'v1/channels' ], - [ ['v1/channel/index', 'offset' => 1], 'v1/channels?offset=1' ], - [ ['v1/channel/view', 'id' => 42], 'v1/channels/42' ], - [ ['v1/channel/options'], 'v1/channels' ], - [ ['v1/channel/options', 'id' => 42], 'v1/channels/42' ], - [ ['v1/channel/delete'], false ], + [['v1/channel/index'], 'v1/channels'], + [['v1/channel/index', 'offset' => 1], 'v1/channels?offset=1'], + [['v1/channel/view', 'id' => 42], 'v1/channels/42'], + [['v1/channel/options'], 'v1/channels'], + [['v1/channel/options', 'id' => 42], 'v1/channels/42'], + [['v1/channel/delete'], false], ], ], [ @@ -230,12 +239,12 @@ class UrlRuleTest extends TestCase 'pluralize' => true, ], [ // test cases: route, expected - [ ['v1/channel/index'], 'v1/channels' ], - [ ['v1/channel/index', 'offset' => 1], 'v1/channels?offset=1' ], - [ ['v1/channel/view', 'id' => 42], 'v1/channels/42' ], - [ ['v1/channel/options'], 'v1/channels' ], - [ ['v1/channel/options', 'id' => 42], 'v1/channels/42' ], - [ ['v1/channel/delete'], false ], + [['v1/channel/index'], 'v1/channels'], + [['v1/channel/index', 'offset' => 1], 'v1/channels?offset=1'], + [['v1/channel/view', 'id' => 42], 'v1/channels/42'], + [['v1/channel/options'], 'v1/channels'], + [['v1/channel/options', 'id' => 42], 'v1/channels/42'], + [['v1/channel/delete'], false], ], ], [ @@ -244,16 +253,16 @@ class UrlRuleTest extends TestCase 'pluralize' => true, ], [ // test cases: route, expected - [ ['v1/channel/index'], 'v1/channels' ], - [ ['v1/channel/view', 'id' => 42], 'v1/channels/42' ], - [ ['v1/channel/options'], 'v1/channels' ], - [ ['v1/channel/options', 'id' => 42], 'v1/channels/42' ], - [ ['v1/channel/delete'], false ], - [ ['v1/user/index'], 'v1/u' ], - [ ['v1/user/view', 'id' => 1], 'v1/u/1' ], - [ ['v1/channel/options'], 'v1/channels' ], - [ ['v1/channel/options', 'id' => 42], 'v1/channels/42' ], - [ ['v1/user/delete'], false ], + [['v1/channel/index'], 'v1/channels'], + [['v1/channel/view', 'id' => 42], 'v1/channels/42'], + [['v1/channel/options'], 'v1/channels'], + [['v1/channel/options', 'id' => 42], 'v1/channels/42'], + [['v1/channel/delete'], false], + [['v1/user/index'], 'v1/u'], + [['v1/user/view', 'id' => 1], 'v1/u/1'], + [['v1/channel/options'], 'v1/channels'], + [['v1/channel/options', 'id' => 42], 'v1/channels/42'], + [['v1/user/delete'], false], ], ], @@ -265,12 +274,12 @@ class UrlRuleTest extends TestCase 'pluralize' => false, ], [ // test cases: route, expected - [ ['v1/channel/index'], 'v1/channel' ], - [ ['v1/channel/index', 'offset' => 1], 'v1/channel?offset=1' ], - [ ['v1/channel/view', 'id' => 42], 'v1/channel/42' ], - [ ['v1/channel/options'], 'v1/channel' ], - [ ['v1/channel/options', 'id' => 42], 'v1/channel/42' ], - [ ['v1/channel/delete'], false ], + [['v1/channel/index'], 'v1/channel'], + [['v1/channel/index', 'offset' => 1], 'v1/channel?offset=1'], + [['v1/channel/view', 'id' => 42], 'v1/channel/42'], + [['v1/channel/options'], 'v1/channel'], + [['v1/channel/options', 'id' => 42], 'v1/channel/42'], + [['v1/channel/delete'], false], ], ], [ @@ -279,12 +288,12 @@ class UrlRuleTest extends TestCase 'pluralize' => false, ], [ // test cases: route, expected - [ ['v1/channel/index'], 'v1/channel' ], - [ ['v1/channel/index', 'offset' => 1], 'v1/channel?offset=1' ], - [ ['v1/channel/view', 'id' => 42], 'v1/channel/42' ], - [ ['v1/channel/options'], 'v1/channel' ], - [ ['v1/channel/options', 'id' => 42], 'v1/channel/42' ], - [ ['v1/channel/delete'], false ], + [['v1/channel/index'], 'v1/channel'], + [['v1/channel/index', 'offset' => 1], 'v1/channel?offset=1'], + [['v1/channel/view', 'id' => 42], 'v1/channel/42'], + [['v1/channel/options'], 'v1/channel'], + [['v1/channel/options', 'id' => 42], 'v1/channel/42'], + [['v1/channel/delete'], false], ], ], [ @@ -293,16 +302,16 @@ class UrlRuleTest extends TestCase 'pluralize' => false, ], [ // test cases: route, expected - [ ['v1/channel/index'], 'v1/channel' ], - [ ['v1/channel/view', 'id' => 42], 'v1/channel/42' ], - [ ['v1/channel/options'], 'v1/channel' ], - [ ['v1/channel/options', 'id' => 42], 'v1/channel/42' ], - [ ['v1/channel/delete'], false ], - [ ['v1/user/index'], 'v1/u' ], - [ ['v1/user/view', 'id' => 1], 'v1/u/1' ], - [ ['v1/user/options'], 'v1/u' ], - [ ['v1/user/options', 'id' => 42], 'v1/u/42' ], - [ ['v1/user/delete'], false ], + [['v1/channel/index'], 'v1/channel'], + [['v1/channel/view', 'id' => 42], 'v1/channel/42'], + [['v1/channel/options'], 'v1/channel'], + [['v1/channel/options', 'id' => 42], 'v1/channel/42'], + [['v1/channel/delete'], false], + [['v1/user/index'], 'v1/u'], + [['v1/user/view', 'id' => 1], 'v1/u/1'], + [['v1/user/options'], 'v1/u'], + [['v1/user/options', 'id' => 42], 'v1/u/42'], + [['v1/user/delete'], false], ], ], @@ -320,20 +329,19 @@ class UrlRuleTest extends TestCase ], [ // test cases: route, expected // normal actions should behave as before - [ ['v1/channel/index'], 'v1/channels' ], - [ ['v1/channel/index', 'offset' => 1], 'v1/channels?offset=1' ], - [ ['v1/channel/view', 'id' => 42], 'v1/channels/42' ], - [ ['v1/channel/options'], 'v1/channels' ], - [ ['v1/channel/options', 'id' => 42], 'v1/channels/42' ], - [ ['v1/channel/delete'], false ], + [['v1/channel/index'], 'v1/channels'], + [['v1/channel/index', 'offset' => 1], 'v1/channels?offset=1'], + [['v1/channel/view', 'id' => 42], 'v1/channels/42'], + [['v1/channel/options'], 'v1/channels'], + [['v1/channel/options', 'id' => 42], 'v1/channels/42'], + [['v1/channel/delete'], false], - [ ['v1/channel/my'], 'v1/channels/my' ], - [ ['v1/channel/my', 'id' => 42], 'v1/channels/42/my' ], - [ ['v1/channel/my2'], false ], - [ ['v1/channel/my2', 'id' => 42], false ], + [['v1/channel/my'], 'v1/channels/my'], + [['v1/channel/my', 'id' => 42], 'v1/channels/42/my'], + [['v1/channel/my2'], false], + [['v1/channel/my2', 'id' => 42], false], ], ], - ]; } diff --git a/tests/framework/test/ActiveFixtureTest.php b/tests/framework/test/ActiveFixtureTest.php index 8955ecd..c078a63 100644 --- a/tests/framework/test/ActiveFixtureTest.php +++ b/tests/framework/test/ActiveFixtureTest.php @@ -1,11 +1,15 @@ initFixtures(); + $this->initFixtures(); } public function tearDown() diff --git a/tests/framework/test/ArrayFixtureTest.php b/tests/framework/test/ArrayFixtureTest.php index 9d6061e..2ccd51e 100644 --- a/tests/framework/test/ArrayFixtureTest.php +++ b/tests/framework/test/ArrayFixtureTest.php @@ -8,15 +8,14 @@ namespace yiiunit\framework\test; -use yiiunit\TestCase; use yii\test\ArrayFixture; +use yiiunit\TestCase; /** * @group fixture */ class ArrayFixtureTest extends TestCase { - /** * @var \yii\test\ArrayFixture */ @@ -57,5 +56,4 @@ class ArrayFixtureTest extends TestCase $this->_fixture->dataFile = 'wrong/fixtures/data/path/alias'; $this->_fixture->load(); } - } diff --git a/tests/framework/test/data/array_fixture.php b/tests/framework/test/data/array_fixture.php index c5ccd4b..39cc75f 100644 --- a/tests/framework/test/data/array_fixture.php +++ b/tests/framework/test/data/array_fixture.php @@ -1,4 +1,9 @@ [ diff --git a/tests/framework/test/data/customer.php b/tests/framework/test/data/customer.php index 2eb7e6c..aeb1fcb 100644 --- a/tests/framework/test/data/customer.php +++ b/tests/framework/test/data/customer.php @@ -1,4 +1,9 @@ [ @@ -6,13 +11,13 @@ return [ 'name' => 'customer1', 'address' => 'address1', 'status' => 1, - 'profile_id' => 1 + 'profile_id' => 1, ], 'customer2' => [ 'email' => 'customer2@example.com', 'name' => 'customer2', 'address' => 'address2', 'status' => 2, - 'profile_id' => 2 + 'profile_id' => 2, ], ]; diff --git a/tests/framework/test/data/profile.php b/tests/framework/test/data/profile.php index 91ebe4c..42be091 100644 --- a/tests/framework/test/data/profile.php +++ b/tests/framework/test/data/profile.php @@ -1,4 +1,9 @@ [ diff --git a/tests/framework/validators/BooleanValidatorTest.php b/tests/framework/validators/BooleanValidatorTest.php index 29b008f..9835422 100644 --- a/tests/framework/validators/BooleanValidatorTest.php +++ b/tests/framework/validators/BooleanValidatorTest.php @@ -1,9 +1,15 @@ assertTrue($val->validate(true)); $this->assertTrue($val->validate(false)); $this->assertTrue($val->validate('0')); @@ -44,12 +50,12 @@ class BooleanValidatorTest extends TestCase public function testValidateAttributeAndError() { - $obj = new FakedValidationModel; + $obj = new FakedValidationModel(); $obj->attrA = true; $obj->attrB = '1'; $obj->attrC = '0'; $obj->attrD = []; - $val = new BooleanValidator; + $val = new BooleanValidator(); $val->validateAttribute($obj, 'attrA'); $this->assertFalse($obj->hasErrors('attrA')); $val->validateAttribute($obj, 'attrC'); @@ -72,7 +78,7 @@ class BooleanValidatorTest extends TestCase $this->assertEquals('the input value must be either "true" or "false".', $errorMessage); - $obj = new FakedValidationModel; + $obj = new FakedValidationModel(); $obj->attrA = true; $obj->attrB = '1'; $obj->attrC = '0'; @@ -80,15 +86,14 @@ class BooleanValidatorTest extends TestCase $this->assertEquals( 'yii.validation.boolean(value, messages, {"trueValue":true,"falseValue":false,"message":"attrB must be either \"true\" or \"false\".","skipOnEmpty":1,"strict":1});', - $validator->clientValidateAttribute($obj, 'attrB', new ViewStub) + $validator->clientValidateAttribute($obj, 'attrB', new ViewStub()) ); } } -class ViewStub extends \yii\web\View +class ViewStub extends View { public function registerAssetBundle($name, $position = null) { - return; } } diff --git a/tests/framework/validators/CompareValidatorTest.php b/tests/framework/validators/CompareValidatorTest.php index e831cb1..c65cc0a 100644 --- a/tests/framework/validators/CompareValidatorTest.php +++ b/tests/framework/validators/CompareValidatorTest.php @@ -1,4 +1,10 @@ expectException('yii\base\InvalidConfigException'); - $val = new CompareValidator; + $val = new CompareValidator(); $val->validate('val'); } @@ -96,40 +102,40 @@ class CompareValidatorTest extends TestCase public function testValidateAttribute() { // invalid-array - $val = new CompareValidator; - $model = new FakedValidationModel; + $val = new CompareValidator(); + $model = new FakedValidationModel(); $model->attr = ['test_val']; $val->validateAttribute($model, 'attr'); $this->assertTrue($model->hasErrors('attr')); $val = new CompareValidator(['compareValue' => 'test-string']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_test = 'test-string'; $val->validateAttribute($model, 'attr_test'); $this->assertFalse($model->hasErrors('attr_test')); $val = new CompareValidator(['compareAttribute' => 'attr_test_val']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_test = 'test-string'; $model->attr_test_val = 'test-string'; $val->validateAttribute($model, 'attr_test'); $this->assertFalse($model->hasErrors('attr_test')); $this->assertFalse($model->hasErrors('attr_test_val')); $val = new CompareValidator(['compareAttribute' => 'attr_test_val']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_test = 'test-string'; $model->attr_test_val = 'test-string-false'; $val->validateAttribute($model, 'attr_test'); $this->assertTrue($model->hasErrors('attr_test')); $this->assertFalse($model->hasErrors('attr_test_val')); // assume: _repeat - $val = new CompareValidator; - $model = new FakedValidationModel; + $val = new CompareValidator(); + $model = new FakedValidationModel(); $model->attr_test = 'test-string'; $model->attr_test_repeat = 'test-string'; $val->validateAttribute($model, 'attr_test'); $this->assertFalse($model->hasErrors('attr_test')); $this->assertFalse($model->hasErrors('attr_test_repeat')); - $val = new CompareValidator; - $model = new FakedValidationModel; + $val = new CompareValidator(); + $model = new FakedValidationModel(); $model->attr_test = 'test-string'; $model->attr_test_repeat = 'test-string2'; $val->validateAttribute($model, 'attr_test'); @@ -193,12 +199,11 @@ class CompareValidatorTest extends TestCase foreach ($this->getOperationTestData($value) as $operator => $tests) { $val = new CompareValidator(['operator' => $operator, 'compareValue' => $value]); foreach ($tests as $test) { - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_test = $test[0]; $val->validateAttribute($model, 'attr_test'); $this->assertEquals($test[1], !$model->hasErrors('attr_test')); } - } } diff --git a/tests/framework/validators/DateValidatorTest.php b/tests/framework/validators/DateValidatorTest.php index bbf39d3..cb2b99c 100644 --- a/tests/framework/validators/DateValidatorTest.php +++ b/tests/framework/validators/DateValidatorTest.php @@ -1,12 +1,17 @@ assertTrue($val->message !== null && strlen($val->message) > 1); } @@ -50,8 +55,8 @@ class DateValidatorTest extends TestCase 'components' => [ 'formatter' => [ 'dateFormat' => 'short', - ] - ] + ], + ], ]); $val = new DateValidator(); $this->assertTrue($val->validate('31/5/2017')); @@ -65,8 +70,8 @@ class DateValidatorTest extends TestCase 'components' => [ 'formatter' => [ 'dateFormat' => 'short', - ] - ] + ], + ], ]); $val = new DateValidator(); $this->assertTrue($val->validate('31.5.2017')); @@ -135,17 +140,17 @@ class DateValidatorTest extends TestCase // error-array-add $val = new DateValidator(['format' => 'php:Y-m-d']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '2013-09-13'; $val->validateAttribute($model, 'attr_date'); $this->assertFalse($model->hasErrors('attr_date')); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '1375293913'; $val->validateAttribute($model, 'attr_date'); $this->assertTrue($model->hasErrors('attr_date')); //// timestamp attribute $val = new DateValidator(['format' => 'php:Y-m-d', 'timestampAttribute' => 'attr_timestamp']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '2013-09-13'; $model->attr_timestamp = true; $val->validateAttribute($model, 'attr_date'); @@ -179,17 +184,17 @@ class DateValidatorTest extends TestCase // error-array-add $val = new DateValidator(['format' => 'yyyy-MM-dd']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '2013-09-13'; $val->validateAttribute($model, 'attr_date'); $this->assertFalse($model->hasErrors('attr_date')); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '1375293913'; $val->validateAttribute($model, 'attr_date'); $this->assertTrue($model->hasErrors('attr_date')); //// timestamp attribute $val = new DateValidator(['format' => 'yyyy-MM-dd', 'timestampAttribute' => 'attr_timestamp']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '2013-09-13'; $model->attr_timestamp = true; $val->validateAttribute($model, 'attr_date'); @@ -243,7 +248,7 @@ class DateValidatorTest extends TestCase $return[] = ['yyyy-MM-dd HH:mm:ss', '2013-09-13', '2013-09-13 00:00:00', $tz[0], $appTz[0]]; $return[] = ['php:Y-m-d', '2013-09-13', '2013-09-13', $tz[0], $appTz[0]]; $return[] = ['php:Y-m-d H:i:s', '2013-09-13', '2013-09-13 00:00:00', $tz[0], $appTz[0]]; - $return[] = ['php:U', '2013-09-13', "1379030400", $tz[0], $appTz[0]]; + $return[] = ['php:U', '2013-09-13', '1379030400', $tz[0], $appTz[0]]; $return[] = [null, '2013-09-13', 1379030400, $tz[0], $appTz[0]]; } } @@ -266,7 +271,7 @@ class DateValidatorTest extends TestCase date_default_timezone_set($timezone); $val = new DateValidator(['format' => 'yyyy-MM-dd', 'timestampAttribute' => 'attr_timestamp', 'timestampAttributeFormat' => $format, 'timeZone' => $appTimezone]); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = $date; $model->attr_timestamp = true; $val->validateAttribute($model, 'attr_date'); @@ -288,8 +293,8 @@ class DateValidatorTest extends TestCase 'formatter' => [ 'dateFormat' => 'long', 'datetimeFormat' => 'short', // this is the format to be used by the validator by default - ] - ] + ], + ], ]); $val = new DateValidator(['type' => DateValidator::TYPE_DATETIME]); $this->assertTrue($val->validate('31/5/2017 12:30')); @@ -303,8 +308,8 @@ class DateValidatorTest extends TestCase 'formatter' => [ 'dateFormat' => 'long', 'datetimeFormat' => 'short', // this is the format to be used by the validator by default - ] - ] + ], + ], ]); $val = new DateValidator(['type' => DateValidator::TYPE_DATETIME]); $this->assertTrue($val->validate('31.5.2017 12:30')); @@ -322,7 +327,7 @@ class DateValidatorTest extends TestCase date_default_timezone_set($timezone); $val = new DateValidator(['format' => 'yyyy-MM-dd HH:mm:ss', 'timestampAttribute' => 'attr_timestamp', 'timeZone' => 'UTC']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '2013-09-13 14:23:15'; $model->attr_timestamp = true; $val->validateAttribute($model, 'attr_date'); @@ -331,7 +336,7 @@ class DateValidatorTest extends TestCase $this->assertSame(1379082195, $model->attr_timestamp); $val = new DateValidator(['format' => 'yyyy-MM-dd HH:mm:ss', 'timestampAttribute' => 'attr_timestamp', 'timeZone' => 'Europe/Berlin']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '2013-09-13 16:23:15'; $model->attr_timestamp = true; $val->validateAttribute($model, 'attr_date'); @@ -340,7 +345,7 @@ class DateValidatorTest extends TestCase $this->assertSame(1379082195, $model->attr_timestamp); $val = new DateValidator(['format' => 'yyyy-MM-dd HH:mm:ss', 'timestampAttribute' => 'attr_timestamp', 'timestampAttributeFormat' => 'yyyy-MM-dd HH:mm:ss', 'timeZone' => 'UTC']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '2013-09-13 14:23:15'; $model->attr_timestamp = true; $val->validateAttribute($model, 'attr_date'); @@ -349,7 +354,7 @@ class DateValidatorTest extends TestCase $this->assertSame('2013-09-13 14:23:15', $model->attr_timestamp); $val = new DateValidator(['format' => 'yyyy-MM-dd HH:mm:ss', 'timestampAttribute' => 'attr_timestamp', 'timestampAttributeFormat' => 'yyyy-MM-dd HH:mm:ss', 'timeZone' => 'Europe/Berlin']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '2013-09-13 16:23:15'; $model->attr_timestamp = true; $val->validateAttribute($model, 'attr_date'); @@ -358,7 +363,7 @@ class DateValidatorTest extends TestCase $this->assertSame('2013-09-13 14:23:15', $model->attr_timestamp); $val = new DateValidator(['format' => 'yyyy-MM-dd HH:mm:ss', 'timestampAttribute' => 'attr_timestamp', 'timestampAttributeFormat' => 'php:Y-m-d H:i:s', 'timeZone' => 'UTC']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '2013-09-13 14:23:15'; $model->attr_timestamp = true; $val->validateAttribute($model, 'attr_date'); @@ -367,7 +372,7 @@ class DateValidatorTest extends TestCase $this->assertSame('2013-09-13 14:23:15', $model->attr_timestamp); $val = new DateValidator(['format' => 'yyyy-MM-dd HH:mm:ss', 'timestampAttribute' => 'attr_timestamp', 'timestampAttributeFormat' => 'php:Y-m-d H:i:s', 'timeZone' => 'Europe/Berlin']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '2013-09-13 16:23:15'; $model->attr_timestamp = true; $val->validateAttribute($model, 'attr_date'); @@ -392,7 +397,7 @@ class DateValidatorTest extends TestCase date_default_timezone_set($timezone); $val = new DateValidator(['format' => 'yyyy-MM-dd HH:mm:ss', 'timestampAttribute' => 'attr_timestamp', 'timestampAttributeFormat' => 'yyyy-MM-dd HH:mm:ss', 'timestampAttributeTimeZone' => 'Europe/Berlin', 'timeZone' => 'UTC']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '2013-09-13 14:23:15'; $model->attr_timestamp = true; $val->validateAttribute($model, 'attr_date'); @@ -400,7 +405,7 @@ class DateValidatorTest extends TestCase $this->assertFalse($model->hasErrors('attr_timestamp')); $this->assertSame('2013-09-13 16:23:15', $model->attr_timestamp); $val = new DateValidator(['format' => 'php:Y-m-d H:i:s', 'timestampAttribute' => 'attr_timestamp', 'timestampAttributeFormat' => 'yyyy-MM-dd HH:mm:ss', 'timestampAttributeTimeZone' => 'Europe/Berlin', 'timeZone' => 'UTC']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '2013-09-13 14:23:15'; $model->attr_timestamp = true; $val->validateAttribute($model, 'attr_date'); @@ -409,7 +414,7 @@ class DateValidatorTest extends TestCase $this->assertSame('2013-09-13 16:23:15', $model->attr_timestamp); $val = new DateValidator(['format' => 'yyyy-MM-dd HH:mm:ss', 'timestampAttribute' => 'attr_timestamp', 'timestampAttributeFormat' => 'yyyy-MM-dd HH:mm:ss', 'timestampAttributeTimeZone' => 'Europe/Berlin', 'timeZone' => 'Europe/Berlin']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '2013-09-13 16:23:15'; $model->attr_timestamp = true; $val->validateAttribute($model, 'attr_date'); @@ -417,7 +422,7 @@ class DateValidatorTest extends TestCase $this->assertFalse($model->hasErrors('attr_timestamp')); $this->assertSame('2013-09-13 16:23:15', $model->attr_timestamp); $val = new DateValidator(['format' => 'php:Y-m-d H:i:s', 'timestampAttribute' => 'attr_timestamp', 'timestampAttributeFormat' => 'yyyy-MM-dd HH:mm:ss', 'timestampAttributeTimeZone' => 'Europe/Berlin', 'timeZone' => 'Europe/Berlin']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '2013-09-13 16:23:15'; $model->attr_timestamp = true; $val->validateAttribute($model, 'attr_date'); @@ -426,7 +431,7 @@ class DateValidatorTest extends TestCase $this->assertSame('2013-09-13 16:23:15', $model->attr_timestamp); $val = new DateValidator(['format' => 'yyyy-MM-dd HH:mm:ss', 'timestampAttribute' => 'attr_timestamp', 'timestampAttributeFormat' => 'yyyy-MM-dd HH:mm:ss', 'timestampAttributeTimeZone' => 'America/New_York', 'timeZone' => 'Europe/Berlin']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '2013-09-13 16:23:15'; $model->attr_timestamp = true; $val->validateAttribute($model, 'attr_date'); @@ -434,7 +439,7 @@ class DateValidatorTest extends TestCase $this->assertFalse($model->hasErrors('attr_timestamp')); $this->assertSame('2013-09-13 10:23:15', $model->attr_timestamp); $val = new DateValidator(['format' => 'php:Y-m-d H:i:s', 'timestampAttribute' => 'attr_timestamp', 'timestampAttributeFormat' => 'yyyy-MM-dd HH:mm:ss', 'timestampAttributeTimeZone' => 'America/New_York', 'timeZone' => 'Europe/Berlin']); - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = '2013-09-13 16:23:15'; $model->attr_timestamp = true; $val->validateAttribute($model, 'attr_date'); @@ -465,26 +470,26 @@ class DateValidatorTest extends TestCase } $val = new DateValidator(['format' => 'yyyy-MM-dd', 'min' => $min]); - $date = "1958-01-12"; + $date = '1958-01-12'; $this->assertTrue($val->validate($date), "$date is valid"); $val = new DateValidator(['format' => 'yyyy-MM-dd', 'max' => '2000-01-01']); $date = '2014-09-13'; $this->assertFalse($val->validate($date), "$date is too big"); - $date = "1958-01-12"; + $date = '1958-01-12'; $this->assertTrue($val->validate($date), "$date is valid"); $val = new DateValidator(['format' => 'yyyy-MM-dd', 'min' => $min, 'max' => '2000-01-01']); - $this->assertTrue($val->validate('1999-12-31'), "max -1 day is valid"); - $this->assertTrue($val->validate('2000-01-01'), "max is inside range"); - $this->assertTrue($val->validate($min), "min is inside range"); - $this->assertFalse($val->validate($beforeMin), "min -1 day is invalid"); - $this->assertFalse($val->validate('2000-01-02'), "max +1 day is invalid"); + $this->assertTrue($val->validate('1999-12-31'), 'max -1 day is valid'); + $this->assertTrue($val->validate('2000-01-01'), 'max is inside range'); + $this->assertTrue($val->validate($min), 'min is inside range'); + $this->assertFalse($val->validate($beforeMin), 'min -1 day is invalid'); + $this->assertFalse($val->validate('2000-01-02'), 'max +1 day is invalid'); } private function validateModelAttribute($validator, $date, $expected, $message = '') { - $model = new FakedValidationModel; + $model = new FakedValidationModel(); $model->attr_date = $date; $validator->validateAttribute($model, 'attr_date'); if (!$expected) { @@ -494,7 +499,8 @@ class DateValidatorTest extends TestCase } } - public function testIntlValidateAttributeRange() { + public function testIntlValidateAttributeRange() + { $this->testValidateAttributeRange(); } @@ -525,17 +531,17 @@ class DateValidatorTest extends TestCase $this->validateModelAttribute($val, $date, true, "$date is valid"); $val = new DateValidator(['format' => 'yyyy-MM-dd', 'min' => $min, 'max' => '2000-01-01']); - $this->validateModelAttribute($val, '1999-12-31', true, "max -1 day is valid"); - $this->validateModelAttribute($val, '2000-01-01', true, "max is inside range"); - $this->validateModelAttribute($val, $min, true, "min is inside range"); - $this->validateModelAttribute($val, $beforeMin, false, "min -1 day is invalid"); - $this->validateModelAttribute($val, '2000-01-02', false, "max +1 day is invalid"); + $this->validateModelAttribute($val, '1999-12-31', true, 'max -1 day is valid'); + $this->validateModelAttribute($val, '2000-01-01', true, 'max is inside range'); + $this->validateModelAttribute($val, $min, true, 'min is inside range'); + $this->validateModelAttribute($val, $beforeMin, false, 'min -1 day is invalid'); + $this->validateModelAttribute($val, '2000-01-02', false, 'max +1 day is invalid'); } public function testIntlValidateValueRangeOld() { if ($this->checkOldIcuBug()) { - $this->markTestSkipped("ICU is too old."); + $this->markTestSkipped('ICU is too old.'); } $date = '14-09-13'; $val = new DateValidator(['format' => 'yyyy-MM-dd', 'min' => '1920-01-01']); @@ -545,7 +551,7 @@ class DateValidatorTest extends TestCase public function testIntlValidateAttributeRangeOld() { if ($this->checkOldIcuBug()) { - $this->markTestSkipped("ICU is too old."); + $this->markTestSkipped('ICU is too old.'); } $date = '14-09-13'; $val = new DateValidator(['format' => 'yyyy-MM-dd', 'min' => '1920-01-01']); diff --git a/tests/framework/validators/DefaultValueValidatorTest.php b/tests/framework/validators/DefaultValueValidatorTest.php index 5699415..cdd6831 100644 --- a/tests/framework/validators/DefaultValueValidatorTest.php +++ b/tests/framework/validators/DefaultValueValidatorTest.php @@ -1,4 +1,9 @@ value = 'test_value'; - $obj = new \stdclass; + $obj = new \stdclass(); $obj->attrA = 'attrA'; $obj->attrB = null; $obj->attrC = ''; diff --git a/tests/framework/validators/EachValidatorTest.php b/tests/framework/validators/EachValidatorTest.php index a2757d8..515f63c 100644 --- a/tests/framework/validators/EachValidatorTest.php +++ b/tests/framework/validators/EachValidatorTest.php @@ -1,4 +1,9 @@ [ - ' to be trimmed ' + ' to be trimmed ', ], ]); $validator = new EachValidator(['rule' => ['trim']]); @@ -60,7 +65,7 @@ class EachValidatorTest extends TestCase { $model = FakedValidationModel::createWithAttributes([ 'attr_one' => [ - 'text' + 'text', ], ]); $validator = new EachValidator(['rule' => ['integer']]); @@ -112,7 +117,7 @@ class EachValidatorTest extends TestCase $model = FakedValidationModel::createWithAttributes([ 'attr_one' => [ - '' + '', ], ]); $validator = new EachValidator(['rule' => ['integer', 'skipOnEmpty' => true]]); @@ -165,7 +170,7 @@ class EachValidatorTest extends TestCase { $model = FakedValidationModel::createWithAttributes([ 'attr_one' => [ - 'one', 2, 'three' + 'one', 2, 'three', ], ]); $validator = new EachValidator(['rule' => ['integer']]); @@ -179,4 +184,4 @@ class EachValidatorTest extends TestCase $validator->validateAttribute($model, 'attr_one'); $this->assertCount(2, $model->getErrors('attr_one')); } -} \ No newline at end of file +} diff --git a/tests/framework/validators/EmailValidatorTest.php b/tests/framework/validators/EmailValidatorTest.php index 5fa88ae..3786505 100644 --- a/tests/framework/validators/EmailValidatorTest.php +++ b/tests/framework/validators/EmailValidatorTest.php @@ -1,4 +1,10 @@ ', ]; foreach ($emails as $email) { - $this->assertTrue($validator->validate($email),"Email: '$email' failed to validate(checkDNS=true, allowName=true)"); + $this->assertTrue($validator->validate($email), "Email: '$email' failed to validate(checkDNS=true, allowName=true)"); } } diff --git a/tests/framework/validators/ExistValidatorTest.php b/tests/framework/validators/ExistValidatorTest.php index db5eaeb..385c723 100644 --- a/tests/framework/validators/ExistValidatorTest.php +++ b/tests/framework/validators/ExistValidatorTest.php @@ -1,4 +1,9 @@ assertTrue(is_string($val->$attr)); + $this->assertInternalType('string', $val->$attr); } } @@ -126,15 +131,15 @@ class FileValidatorTest extends TestCase 'error' => UPLOAD_ERR_NO_FILE, ], ] - ) + ), ] ); $val->validateAttribute($m, 'attr_files'); $this->assertFalse($m->hasErrors('attr_files')); $m = FakedValidationModel::createWithAttributes([ 'attr_files' => $this->createTestFiles([ - [''], [''], [''] - ]) + [''], [''], [''], + ]), ]); $val->validateAttribute($m, 'attr_files'); $this->assertTrue($m->hasErrors()); @@ -152,19 +157,19 @@ class FileValidatorTest extends TestCase [ 'name' => 'image.png', 'size' => 1024, - 'type' => 'image/png' + 'type' => 'image/png', ], [ 'name' => 'image.png', 'size' => 1024, - 'type' => 'image/png' + 'type' => 'image/png', ], [ 'name' => 'text.txt', - 'size' => 1024 + 'size' => 1024, ], ] - ) + ), ] ); $m->setScenario('validateMultipleFiles'); @@ -179,15 +184,15 @@ class FileValidatorTest extends TestCase [ 'name' => 'image.png', 'size' => 1024, - 'type' => 'image/png' + 'type' => 'image/png', ], [ 'name' => 'image.png', 'size' => 1024, - 'type' => 'image/png' + 'type' => 'image/png', ], ] - ) + ), ] ); $m->setScenario('validateMultipleFiles'); @@ -202,7 +207,7 @@ class FileValidatorTest extends TestCase 'size' => 1024, ], ] - ) + ), ] ); $m->setScenario('validateFile'); @@ -250,7 +255,7 @@ class FileValidatorTest extends TestCase 'tempName' => $tempName, 'type' => $type, 'size' => $size, - 'error' => $error + 'error' => $error, ]); } $files[] = new UploadedFile([ @@ -258,7 +263,7 @@ class FileValidatorTest extends TestCase 'tempName' => $tempName, 'type' => $type, 'size' => $size, - 'error' => $error + 'error' => $error, ]); } @@ -278,7 +283,7 @@ class FileValidatorTest extends TestCase 'tempName' => $filePath, 'type' => FileHelper::getMimeType($filePath), 'size' => filesize($filePath), - 'error' => UPLOAD_ERR_OK + 'error' => UPLOAD_ERR_OK, ]); } @@ -390,7 +395,7 @@ class FileValidatorTest extends TestCase ['test.png', 'IMAGE/*'], ['test.txt', 'text/*'], ['test.xml', '*/xml'], - ['test.odt', 'application/vnd*'] + ['test.odt', 'application/vnd*'], ]; } diff --git a/tests/framework/validators/FilterValidatorTest.php b/tests/framework/validators/FilterValidatorTest.php index 9512c2f..f0b25ab 100644 --- a/tests/framework/validators/FilterValidatorTest.php +++ b/tests/framework/validators/FilterValidatorTest.php @@ -1,4 +1,9 @@ '', 'attr_empty2' => null, 'attr_array' => ['Maria', 'Anna', 'Elizabeth'], - 'attr_array_skipped' => ['John', 'Bill'] + 'attr_array_skipped' => ['John', 'Bill'], ]); $val = new FilterValidator(['filter' => 'trim']); $val->validateAttribute($m, 'attr_one'); @@ -48,8 +53,7 @@ class FilterValidatorTest extends TestCase $val->skipOnEmpty = true; $val->validateAttribute($m, 'attr_empty2'); $this->assertNotNull($m->attr_empty2); - $val->filter = function($value) { - + $val->filter = function ($value) { return implode(',', $value); }; $val->skipOnArray = false; diff --git a/tests/framework/validators/IpValidatorTest.php b/tests/framework/validators/IpValidatorTest.php index 54880f0..118dc0b 100644 --- a/tests/framework/validators/IpValidatorTest.php +++ b/tests/framework/validators/IpValidatorTest.php @@ -1,4 +1,10 @@ false, 'ipv6' => false]); } - public function provideRangesForSubstitution() { + public function provideRangesForSubstitution() + { return [ ['10.0.0.1', ['10.0.0.1']], [['192.168.0.32', 'fa::/32', 'any'], ['192.168.0.32', 'fa::/32', '0.0.0.0/0', '::/0']], [['10.0.0.1', '!private'], ['10.0.0.1', '!10.0.0.0/8', '!172.16.0.0/12', '!192.168.0.0/16', '!fd00::/8']], - [['private', '!system'], ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fd00::/8', '!224.0.0.0/4', '!ff00::/8', '!169.254.0.0/16', '!fe80::/10', '!127.0.0.0/8', '!::1', '!192.0.2.0/24', '!198.51.100.0/24', '!203.0.113.0/24', '!2001:db8::/32']] + [['private', '!system'], ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fd00::/8', '!224.0.0.0/4', '!ff00::/8', '!169.254.0.0/16', '!fe80::/10', '!127.0.0.0/8', '!::1', '!192.0.2.0/24', '!198.51.100.0/24', '!203.0.113.0/24', '!2001:db8::/32']], ]; } @@ -46,7 +53,7 @@ class IpValidatorTest extends TestCase public function testValidateOrder() { $validator = new IpValidator([ - 'ranges' => ['10.0.0.1', '!10.0.0.0/8', '!babe::/8', 'any'] + 'ranges' => ['10.0.0.1', '!10.0.0.0/8', '!babe::/8', 'any'], ]); $this->assertTrue($validator->validate('10.0.0.1')); @@ -56,7 +63,8 @@ class IpValidatorTest extends TestCase $this->assertFalse($validator->validate('babe::cafe')); } - public function provideBadIps() { + public function provideBadIps() + { return [['not.an.ip'], [['what an array', '??']], [123456], [true], [false], ['bad:forSure']]; } @@ -230,7 +238,7 @@ class IpValidatorTest extends TestCase public function testValidateRangeIPv4() { $validator = new IpValidator([ - 'ranges' => ['10.0.1.0/24'] + 'ranges' => ['10.0.1.0/24'], ]); $this->assertTrue($validator->validate('10.0.1.2')); $this->assertFalse($validator->validate('192.5.1.1')); @@ -255,7 +263,7 @@ class IpValidatorTest extends TestCase public function testValidateRangeIPv6() { $validator = new IpValidator([ - 'ranges' => '2001:db0:1:1::/64' + 'ranges' => '2001:db0:1:1::/64', ]); $this->assertTrue($validator->validate('2001:db0:1:1::6')); $this->assertFalse($validator->validate('2001:db0:1:2::7')); @@ -263,7 +271,7 @@ class IpValidatorTest extends TestCase $validator->ranges = ['2001:db0:1:2::/64']; $this->assertTrue($validator->validate('2001:db0:1:2::7')); - $validator->ranges = ['!2001:db0::/32', '2001:db0:1:2::/64', ]; + $validator->ranges = ['!2001:db0::/32', '2001:db0:1:2::/64']; $this->assertFalse($validator->validate('2001:db0:1:2::7')); $validator->subnet = null; diff --git a/tests/framework/validators/NumberValidatorTest.php b/tests/framework/validators/NumberValidatorTest.php index b4456a5..af20efa 100644 --- a/tests/framework/validators/NumberValidatorTest.php +++ b/tests/framework/validators/NumberValidatorTest.php @@ -1,4 +1,9 @@ assertTrue(is_string($val->message)); - $this->assertTrue(is_null($val->max)); + $val = new NumberValidator(); + $this->assertInternalType('string', $val->message); + $this->assertTrue($val->max === null); $val = new NumberValidator(['min' => -1, 'max' => 20, 'integerOnly' => true]); - $this->assertTrue(is_string($val->message)); - $this->assertTrue(is_string($val->tooSmall)); - $this->assertTrue(is_string($val->tooBig)); + $this->assertInternalType('string', $val->message); + $this->assertInternalType('string', $val->tooSmall); + $this->assertInternalType('string', $val->tooBig); } public function testValidateValueSimple() @@ -210,7 +215,6 @@ class NumberValidatorTest extends TestCase $model->attr_number = new \stdClass(); $val->validateAttribute($model, 'attr_number'); $this->assertTrue($model->hasErrors('attr_number')); - } public function testValidateAttributeWithLocaleWhereDecimalPointIsComma() @@ -234,7 +238,7 @@ class NumberValidatorTest extends TestCase { $val = new NumberValidator([ 'tooSmall' => '{attribute} is to small.', - 'min' => 5 + 'min' => 5, ]); $model = new FakedValidationModel(); $model->attr_number = 0; diff --git a/tests/framework/validators/RangeValidatorTest.php b/tests/framework/validators/RangeValidatorTest.php index f995740..7990dd4 100644 --- a/tests/framework/validators/RangeValidatorTest.php +++ b/tests/framework/validators/RangeValidatorTest.php @@ -1,4 +1,9 @@ []]); - $this->assertTrue(is_string($val->message)); + $this->assertInternalType('string', $val->message); } public function testValidateValue() @@ -40,8 +45,8 @@ class RangeValidatorTest extends TestCase $this->assertFalse($val->validate(11)); $this->assertFalse($val->validate(5.5)); $this->assertTrue($val->validate(10)); - $this->assertTrue($val->validate("10")); - $this->assertTrue($val->validate("5")); + $this->assertTrue($val->validate('10')); + $this->assertTrue($val->validate('5')); } public function testValidateValueEmpty() @@ -63,7 +68,7 @@ class RangeValidatorTest extends TestCase $this->assertTrue($val->validate([6, 7, 8, 9, 10])); $this->assertFalse($val->validate([0, 1, 2])); $this->assertFalse($val->validate([10, 11, 12])); - $this->assertTrue($val->validate(["1", "2", "3", 4, 5, 6])); + $this->assertTrue($val->validate(['1', '2', '3', 4, 5, 6])); } public function testValidateValueStrict() @@ -72,17 +77,17 @@ class RangeValidatorTest extends TestCase $this->assertTrue($val->validate(1)); $this->assertTrue($val->validate(5)); $this->assertTrue($val->validate(10)); - $this->assertFalse($val->validate("1")); - $this->assertFalse($val->validate("10")); - $this->assertFalse($val->validate("5.5")); + $this->assertFalse($val->validate('1')); + $this->assertFalse($val->validate('10')); + $this->assertFalse($val->validate('5.5')); } public function testValidateArrayValueStrict() { $val = new RangeValidator(['range' => range(1, 10, 1), 'strict' => true]); $val->allowArray = true; - $this->assertFalse($val->validate(["1", "2", "3", "4", "5", "6"])); - $this->assertFalse($val->validate(["1", "2", "3", 4, 5, 6])); + $this->assertFalse($val->validate(['1', '2', '3', '4', '5', '6'])); + $this->assertFalse($val->validate(['1', '2', '3', 4, 5, 6])); } public function testValidateValueNot() @@ -93,8 +98,8 @@ class RangeValidatorTest extends TestCase $this->assertTrue($val->validate(11)); $this->assertTrue($val->validate(5.5)); $this->assertFalse($val->validate(10)); - $this->assertFalse($val->validate("10")); - $this->assertFalse($val->validate("5")); + $this->assertFalse($val->validate('10')); + $this->assertFalse($val->validate('5')); } public function testValidateAttribute() @@ -111,25 +116,24 @@ class RangeValidatorTest extends TestCase public function testValidateSubsetArrayable() { - // Test in array, values are arrays. IE: ['a'] in [['a'], ['b']] $val = new RangeValidator([ 'range' => [['a'], ['b']], - 'allowArray' => false + 'allowArray' => false, ]); $this->assertTrue($val->validate(['a'])); // Test in array, values are arrays. IE: ['a', 'b'] subset [['a', 'b', 'c'] $val = new RangeValidator([ 'range' => ['a', 'b', 'c'], - 'allowArray' => true + 'allowArray' => true, ]); $this->assertTrue($val->validate(['a', 'b'])); // Test in array, values are arrays. IE: ['a', 'b'] subset [['a', 'b', 'c'] $val = new RangeValidator([ 'range' => ['a', 'b', 'c'], - 'allowArray' => true + 'allowArray' => true, ]); $this->assertTrue($val->validate(new \ArrayObject(['a', 'b']))); @@ -137,10 +141,8 @@ class RangeValidatorTest extends TestCase // Test range as ArrayObject. $val = new RangeValidator([ 'range' => new \ArrayObject(['a', 'b']), - 'allowArray' => false + 'allowArray' => false, ]); $this->assertTrue($val->validate('a')); - - } } diff --git a/tests/framework/validators/RegularExpressionValidatorTest.php b/tests/framework/validators/RegularExpressionValidatorTest.php index bafb1bc..8c19390 100644 --- a/tests/framework/validators/RegularExpressionValidatorTest.php +++ b/tests/framework/validators/RegularExpressionValidatorTest.php @@ -1,4 +1,9 @@ '/^[a-zA-Z0-9](\.)?([^\/]*)$/m']); - $this->assertTrue(is_string($val->message)); + $this->assertInternalType('string', $val->message); } public function testInitException() diff --git a/tests/framework/validators/RequiredValidatorTest.php b/tests/framework/validators/RequiredValidatorTest.php index 6f43bff..1d4fde0 100644 --- a/tests/framework/validators/RequiredValidatorTest.php +++ b/tests/framework/validators/RequiredValidatorTest.php @@ -1,4 +1,10 @@ 55]); $this->assertTrue($val->validate(55)); - $this->assertTrue($val->validate("55")); - $this->assertFalse($val->validate("should fail")); + $this->assertTrue($val->validate('55')); + $this->assertFalse($val->validate('should fail')); $this->assertTrue($val->validate(true)); $val->strict = true; $this->assertTrue($val->validate(55)); - $this->assertFalse($val->validate("55")); - $this->assertFalse($val->validate("0x37")); - $this->assertFalse($val->validate("should fail")); + $this->assertFalse($val->validate('55')); + $this->assertFalse($val->validate('0x37')); + $this->assertFalse($val->validate('should fail')); $this->assertFalse($val->validate(true)); } diff --git a/tests/framework/validators/StringValidatorTest.php b/tests/framework/validators/StringValidatorTest.php index eadf4fa..01e4045 100644 --- a/tests/framework/validators/StringValidatorTest.php +++ b/tests/framework/validators/StringValidatorTest.php @@ -1,4 +1,9 @@ 1, 'max' => 2]); - $this->assertTrue(is_string($val->message)); - $this->assertTrue(is_string($val->tooLong)); - $this->assertTrue(is_string($val->tooShort)); + $this->assertInternalType('string', $val->message); + $this->assertInternalType('string', $val->tooLong); + $this->assertInternalType('string', $val->tooShort); } public function testCustomErrorMessageInValidateAttribute() diff --git a/tests/framework/validators/UniqueValidatorTest.php b/tests/framework/validators/UniqueValidatorTest.php index b6b6d64..2ceb40b 100644 --- a/tests/framework/validators/UniqueValidatorTest.php +++ b/tests/framework/validators/UniqueValidatorTest.php @@ -1,9 +1,14 @@ assertTrue(is_string($val->message)); + $this->assertInternalType('string', $val->message); } public function testCustomMessage() @@ -81,7 +86,7 @@ abstract class UniqueValidatorTest extends DatabaseTestCase $customerModel->clearErrors(); $customerModel->name = 'test data'; - $customerModel->email = ['email@mail.com', 'email2@mail.com',]; + $customerModel->email = ['email@mail.com', 'email2@mail.com']; $validator->targetAttribute = ['email', 'name']; $validator->validateAttribute($customerModel, 'name'); $this->assertEquals($messageError, $customerModel->getFirstError('name')); @@ -206,7 +211,7 @@ abstract class UniqueValidatorTest extends DatabaseTestCase // Check whether "Description" and "address" aren't equal $val = new UniqueValidator([ 'targetClass' => Customer::className(), - 'targetAttribute' => ['description'=>'address'], + 'targetAttribute' => ['description' => 'address'], ]); /** @var Profile $m */ @@ -235,7 +240,7 @@ abstract class UniqueValidatorTest extends DatabaseTestCase $validator = new UniqueValidator(); /** @var Profile $profileModel */ - $profileModel = new Profile(['description'=>'profile customer 1']); + $profileModel = new Profile(['description' => 'profile customer 1']); $validator->validateAttribute($profileModel, 'description'); $this->assertTrue($profileModel->hasErrors('description')); @@ -381,8 +386,8 @@ abstract class UniqueValidatorTest extends DatabaseTestCase $this->assertEquals($expected, $query->createCommand()->getSql()); $params = ['val_attr_b' => 'test value b']; - $query = $this->invokeMethod(new UniqueValidator(['filter' => function($query) { - $query->orWhere('val_attr_a > 0'); + $query = $this->invokeMethod(new UniqueValidator(['filter' => function ($query) { + $query->orWhere('val_attr_a > 0'); }]), 'prepareQuery', [$model, $params]); $expected = "SELECT * FROM {$schema->quoteTableName('validator_main')} WHERE ({$schema->quoteColumnName('val_attr_b')}=:qp0) OR (val_attr_a > 0)"; $this->assertEquals($expected, $query->createCommand()->getSql()); @@ -395,7 +400,7 @@ abstract class UniqueValidatorTest extends DatabaseTestCase public function testAmbiguousColumnName() { $validator = new UniqueValidator([ - 'filter' => function($query) { + 'filter' => function ($query) { $query->joinWith('items', false); }, ]); diff --git a/tests/framework/validators/UrlValidatorTest.php b/tests/framework/validators/UrlValidatorTest.php index 1448866..3243e8b 100644 --- a/tests/framework/validators/UrlValidatorTest.php +++ b/tests/framework/validators/UrlValidatorTest.php @@ -1,9 +1,14 @@ assertFalse($val->validate('google.de')); $this->assertTrue($val->validate('http://google.de')); $this->assertTrue($val->validate('https://google.de')); $this->assertFalse($val->validate('htp://yiiframework.com')); $this->assertTrue($val->validate('https://www.google.de/search?q=yii+framework&ie=utf-8&oe=utf-8' - .'&rls=org.mozilla:de:official&client=firefox-a&gws_rd=cr')); + . '&rls=org.mozilla:de:official&client=firefox-a&gws_rd=cr')); $this->assertFalse($val->validate('ftp://ftp.ruhr-uni-bochum.de/')); $this->assertFalse($val->validate('http://invalid,domain')); $this->assertFalse($val->validate('http://example.com,')); @@ -96,25 +101,25 @@ class UrlValidatorTest extends TestCase public function testValidateLength() { $url = 'http://' . str_pad('base', 2000, 'url') . '.de'; - $val = new UrlValidator; + $val = new UrlValidator(); $this->assertFalse($val->validate($url)); } public function testValidateAttributeAndError() { - $obj = new FakedValidationModel; + $obj = new FakedValidationModel(); $obj->attr_url = 'http://google.de'; - $val = new UrlValidator; + $val = new UrlValidator(); $val->validateAttribute($obj, 'attr_url'); $this->assertFalse($obj->hasErrors('attr_url')); $this->assertSame('http://google.de', $obj->attr_url); - $obj = new FakedValidationModel; + $obj = new FakedValidationModel(); $val->defaultScheme = 'http'; $obj->attr_url = 'google.de'; $val->validateAttribute($obj, 'attr_url'); $this->assertFalse($obj->hasErrors('attr_url')); $this->assertNotFalse(stripos($obj->attr_url, 'http')); - $obj = new FakedValidationModel; + $obj = new FakedValidationModel(); $obj->attr_url = 'gttp;/invalid string'; $val->validateAttribute($obj, 'attr_url'); $this->assertTrue($obj->hasErrors('attr_url')); diff --git a/tests/framework/validators/ValidatorTest.php b/tests/framework/validators/ValidatorTest.php index 8e9dcbe..9ed2e10 100644 --- a/tests/framework/validators/ValidatorTest.php +++ b/tests/framework/validators/ValidatorTest.php @@ -1,4 +1,9 @@ + * @link http://www.yiiframework.com/ + * @copyright Copyright (c) 2008 Yii Software LLC + * @license http://www.yiiframework.com/license/ */ namespace yiiunit\framework\web; use Yii; use yii\helpers\FileHelper; -use yii\web\View; use yii\web\AssetBundle; use yii\web\AssetManager; +use yii\web\View; /** * @group web @@ -103,7 +103,7 @@ class AssetBundleTest extends \yiiunit\TestCase 'linkAssets' => true, 'hashCallback' => function ($path) { return sprintf('%x/%x', crc32($path), crc32(Yii::getVersion())); - } + }, ]); $bundle = $this->verifySourcesPublishedBySymlink($view); $this->assertTrue(is_dir(dirname($bundle->basePath))); @@ -114,7 +114,7 @@ class AssetBundleTest extends \yiiunit\TestCase $view = $this->getView([ 'beforeCopy' => function ($from, $to) { return false; - } + }, ]); $am = $view->assetManager; @@ -137,7 +137,7 @@ class AssetBundleTest extends \yiiunit\TestCase $bundle->publishOptions = [ 'beforeCopy' => function ($from, $to) { return false; - } + }, ]; $bundle->publish($am); @@ -156,8 +156,8 @@ class AssetBundleTest extends \yiiunit\TestCase $bundle = new TestSourceAsset([ 'publishOptions' => [ 'only' => [ - 'js/*' - ] + 'js/*', + ], ], ]); $bundle->publish($am); @@ -441,46 +441,46 @@ EOF; [ 'js', '@web/assetSources/js/missing-file1.js', true, '1234', - '/backend' + '/backend', ], [ 'js', 'http://full-url.example.com/backend/assetSources/js/missing-file.js', true, '1234', - '/backend' + '/backend', ], [ 'css', '//backend/backend/assetSources/js/missing-file.js', true, '1234', - '/backend' + '/backend', ], [ 'css', '@web/assetSources/css/stub.css', false, '1234', - '/en/blog/backend' + '/en/blog/backend', ], // UTF-8 chars [ 'css', '@web/assetSources/css/stub.css', false, '1234', - '/рус/сайт' + '/рус/сайт', ], [ 'js', '@web/assetSources/js/jquery.js', false, '1234', - '/汉语/漢語' + '/汉语/漢語', ], // Custom alias repeats in the asset URL [ 'css', '@web/assetSources/repeat/css/stub.css', false, '1234', - '/repeat' + '/repeat', ], [ 'js', '@web/assetSources/repeat/js/jquery.js', false, '1234', - '/repeat' + '/repeat', ], ]; } @@ -541,7 +541,7 @@ class TestAssetBundle extends AssetBundle 'jsFile.js', ]; public $depends = [ - 'yiiunit\\framework\\web\\TestJqueryAsset' + 'yiiunit\\framework\\web\\TestJqueryAsset', ]; } @@ -553,7 +553,7 @@ class TestJqueryAsset extends AssetBundle 'jquery.js', ]; public $depends = [ - 'yiiunit\\framework\\web\\TestAssetLevel3' + 'yiiunit\\framework\\web\\TestAssetLevel3', ]; } @@ -571,7 +571,7 @@ class TestAssetCircleA extends AssetBundle 'jquery.js', ]; public $depends = [ - 'yiiunit\\framework\\web\\TestAssetCircleB' + 'yiiunit\\framework\\web\\TestAssetCircleB', ]; } @@ -583,7 +583,7 @@ class TestAssetCircleB extends AssetBundle 'jquery.js', ]; public $depends = [ - 'yiiunit\\framework\\web\\TestAssetCircleA' + 'yiiunit\\framework\\web\\TestAssetCircleA', ]; } @@ -594,7 +594,7 @@ class TestAssetPerFileOptions extends AssetBundle public $css = [ 'default_options.css', ['tv.css', 'media' => 'tv'], - ['screen_and_print.css', 'media' => 'screen, print'] + ['screen_and_print.css', 'media' => 'screen, print'], ]; public $js = [ 'normal.js', diff --git a/tests/framework/web/AssetConverterTest.php b/tests/framework/web/AssetConverterTest.php index 97fe56e..aa47c88 100644 --- a/tests/framework/web/AssetConverterTest.php +++ b/tests/framework/web/AssetConverterTest.php @@ -1,6 +1,8 @@ + * @link http://www.yiiframework.com/ + * @copyright Copyright (c) 2008 Yii Software LLC + * @license http://www.yiiframework.com/license/ */ namespace yiiunit\framework\web; diff --git a/tests/framework/web/CacheSessionTest.php b/tests/framework/web/CacheSessionTest.php index 3cb9383..c73a960 100644 --- a/tests/framework/web/CacheSessionTest.php +++ b/tests/framework/web/CacheSessionTest.php @@ -1,4 +1,9 @@ controller, 'actionAksi1'); $params = ['fromGet' => 'from query params', 'q' => 'd426', 'validator' => 'avaliable']; @@ -32,7 +30,6 @@ class ControllerTest extends TestCase list($fromGet, $other) = $this->controller->bindActionParams($aksi1, $params); $this->assertEquals('from query params', $fromGet); $this->assertEquals('avaliable', $other); - } public function testAsJson() @@ -76,7 +73,6 @@ class ControllerTest extends TestCase $this->assertEquals($this->controller->redirect(['//controller/index', 'id' => 3])->headers->get('location'), '/index.php?r=controller%2Findex&id=3'); $this->assertEquals($this->controller->redirect(['//controller/index', 'id_1' => 3, 'id_2' => 4])->headers->get('location'), '/index.php?r=controller%2Findex&id_1=3&id_2=4'); $this->assertEquals($this->controller->redirect(['//controller/index', 'slug' => 'äöüß!"§$%&/()'])->headers->get('location'), '/index.php?r=controller%2Findex&slug=%C3%A4%C3%B6%C3%BC%C3%9F%21%22%C2%A7%24%25%26%2F%28%29'); - } protected function setUp() @@ -92,9 +88,8 @@ class ControllerTest extends TestCase 'scriptFile' => __DIR__ . '/index.php', 'scriptUrl' => '/index.php', ], - ] + ], ])); $this->mockWebApplication(['controller' => $this->controller]); } - } diff --git a/tests/framework/web/DbSessionTest.php b/tests/framework/web/DbSessionTest.php index eefc0ad..0702e04 100644 --- a/tests/framework/web/DbSessionTest.php +++ b/tests/framework/web/DbSessionTest.php @@ -1,4 +1,9 @@ writeCallback = function ($session) { return [ - 'user_id' => 15 + 'user_id' => 15, ]; }; @@ -113,7 +118,7 @@ class DbSessionTest extends TestCase $migrate->run($action, $params); ob_get_clean(); - return array_map(function($version) { + return array_map(function ($version) { return substr($version, 15); }, (new Query())->select(['version'])->from('migration')->column()); } @@ -125,7 +130,7 @@ class DbSessionTest extends TestCase 'db' => [ 'class' => Connection::className(), 'dsn' => 'sqlite::memory:', - ] + ], ], ]); @@ -133,7 +138,7 @@ class DbSessionTest extends TestCase $this->assertEquals(['base'], $history); $history = $this->runMigrate('up'); - $this->assertEquals(['base','session_init'], $history); + $this->assertEquals(['base', 'session_init'], $history); $history = $this->runMigrate('down'); $this->assertEquals(['base'], $history); diff --git a/tests/framework/web/ErrorActionTest.php b/tests/framework/web/ErrorActionTest.php index f6e57f2..9cd82ce 100644 --- a/tests/framework/web/ErrorActionTest.php +++ b/tests/framework/web/ErrorActionTest.php @@ -1,4 +1,9 @@ getController()->runAction('error') $controller = $this->getController([ 'defaultName' => 'Oops...', - 'defaultMessage' => 'The system is drunk' + 'defaultMessage' => 'The system is drunk', ]); $this->assertEquals('Name: Oops... @@ -103,8 +108,6 @@ Exception: yii\web\NotFoundHttpException', $this->getController()->runAction('er $this->expectExceptionMessageRegExp('#The view file does not exist: .*?views' . $ds . 'test' . $ds . 'error.php#'); $this->invokeMethod($action, 'renderHtmlResponse'); } - - } class TestController extends Controller diff --git a/tests/framework/web/ErrorHandlerTest.php b/tests/framework/web/ErrorHandlerTest.php index 2cdd1de..4077efb 100644 --- a/tests/framework/web/ErrorHandlerTest.php +++ b/tests/framework/web/ErrorHandlerTest.php @@ -1,4 +1,9 @@ getErrorHandler(); - ob_start(); // suppress response output + ob_start(); // suppress response output $this->invokeMethod($handler, 'renderException', [new NotFoundHttpException('This message is displayed to end user')]); - ob_get_clean(); - $out = Yii::$app->response->data; - $this->assertEquals('Code: 404 + ob_get_clean(); + $out = Yii::$app->response->data; + $this->assertEquals('Code: 404 Message: This message is displayed to end user Exception: yii\web\NotFoundHttpException', $out); - } + } } class ErrorHandler extends \yii\web\ErrorHandler @@ -44,4 +49,4 @@ class ErrorHandler extends \yii\web\ErrorHandler { return false; } -} \ No newline at end of file +} diff --git a/tests/framework/web/FakeController.php b/tests/framework/web/FakeController.php index 6bd9202..572d169 100644 --- a/tests/framework/web/FakeController.php +++ b/tests/framework/web/FakeController.php @@ -20,5 +20,4 @@ class FakeController extends Controller public function actionAksi1($fromGet, $other = 'default') { } - } diff --git a/tests/framework/web/FormatterTest.php b/tests/framework/web/FormatterTest.php index b67052b..abaa04b 100644 --- a/tests/framework/web/FormatterTest.php +++ b/tests/framework/web/FormatterTest.php @@ -1,5 +1,9 @@ mockApplication(); - $this->response = new Response; + $this->response = new Response(); $this->formatter = $this->getFormatterInstance(); } @@ -36,7 +40,7 @@ abstract class FormatterTest extends \yiiunit\TestCase { $this->response->data = null; $this->formatter->format($this->response); - $this->assertEquals(null, $this->response->content); + $this->assertNull($this->response->content); } /** diff --git a/tests/framework/web/GroupUrlRuleTest.php b/tests/framework/web/GroupUrlRuleTest.php index 414e16a..138eeaf 100644 --- a/tests/framework/web/GroupUrlRuleTest.php +++ b/tests/framework/web/GroupUrlRuleTest.php @@ -1,10 +1,15 @@ null]); $suites = $this->getTestsForCreateUrl(); foreach ($suites as $i => $suite) { - list ($name, $config, $tests) = $suite; + list($name, $config, $tests) = $suite; $rule = new GroupUrlRule($config); foreach ($tests as $j => $test) { - list ($route, $params, $expected, $status) = $test; + list($route, $params, $expected, $status) = $test; $url = $rule->createUrl($manager, $route, $params); $this->assertEquals($expected, $url, "Test#$i-$j: $name"); $this->assertSame($status, $rule->getCreateUrlStatus(), "Test#$i-$j: $name"); @@ -41,7 +46,7 @@ class GroupUrlRuleTest extends TestCase $request = new Request(['hostInfo' => 'http://en.example.com']); $suites = $this->getTestsForParseRequest(); foreach ($suites as $i => $suite) { - list ($name, $config, $tests) = $suite; + list($name, $config, $tests) = $suite; $rule = new GroupUrlRule($config); foreach ($tests as $j => $test) { $request->pathInfo = $test[0]; @@ -120,7 +125,7 @@ class GroupUrlRuleTest extends TestCase 'routePrefix' => 'admin', 'ruleConfig' => [ 'suffix' => '.html', - 'class' => 'yii\\web\\UrlRule' + 'class' => 'yii\\web\\UrlRule', ], 'rules' => [ 'login' => 'user/login', @@ -140,7 +145,7 @@ class GroupUrlRuleTest extends TestCase 'routePrefix' => 'admin', 'ruleConfig' => [ 'suffix' => '.html', - 'class' => 'yii\web\UrlRule' + 'class' => 'yii\web\UrlRule', ], 'rules' => [ 'login' => 'user/login', @@ -158,7 +163,7 @@ class GroupUrlRuleTest extends TestCase [ [ 'admin/user/logout', [], false, - UrlRule::CREATE_STATUS_PARSING_ONLY | UrlRule::CREATE_STATUS_ROUTE_MISMATCH | UrlRule::CREATE_STATUS_PARAMS_MISMATCH + UrlRule::CREATE_STATUS_PARSING_ONLY | UrlRule::CREATE_STATUS_ROUTE_MISMATCH | UrlRule::CREATE_STATUS_PARAMS_MISMATCH, ], ], ], @@ -229,7 +234,7 @@ class GroupUrlRuleTest extends TestCase 'routePrefix' => 'admin', 'ruleConfig' => [ 'suffix' => '.html', - 'class' => 'yii\\web\\UrlRule' + 'class' => 'yii\\web\\UrlRule', ], 'rules' => [ 'login' => 'user/login', diff --git a/tests/framework/web/JsonResponseFormatterTest.php b/tests/framework/web/JsonResponseFormatterTest.php index 89f75f9..07a1c1d 100644 --- a/tests/framework/web/JsonResponseFormatterTest.php +++ b/tests/framework/web/JsonResponseFormatterTest.php @@ -32,7 +32,7 @@ class JsonResponseFormatterTest extends FormatterTest [1, 1], ['abc', '"abc"'], [true, 'true'], - ["<>", '"<>"'], + ['<>', '"<>"'], ]; } @@ -40,25 +40,36 @@ class JsonResponseFormatterTest extends FormatterTest { return [ // input, json, pretty json - [[], "[]", "[]"], + [[], '[]', '[]'], [[1, 'abc'], '[1,"abc"]', "[\n 1,\n \"abc\"\n]"], - [[ - 'a' => 1, - 'b' => 'abc', - ], '{"a":1,"b":"abc"}', "{\n \"a\": 1,\n \"b\": \"abc\"\n}"], - [[ - 1, - 'abc', - [2, 'def'], - true, - ], '[1,"abc",[2,"def"],true]', "[\n 1,\n \"abc\",\n [\n 2,\n \"def\"\n ],\n true\n]"], - [[ - 'a' => 1, - 'b' => 'abc', - 'c' => [2, '<>'], - true, - ], '{"a":1,"b":"abc","c":[2,"<>"],"0":true}', - "{\n \"a\": 1,\n \"b\": \"abc\",\n \"c\": [\n 2,\n \"<>\"\n ],\n \"0\": true\n}"], + [ + [ + 'a' => 1, + 'b' => 'abc', + ], + '{"a":1,"b":"abc"}', + "{\n \"a\": 1,\n \"b\": \"abc\"\n}", + ], + [ + [ + 1, + 'abc', + [2, 'def'], + true, + ], + '[1,"abc",[2,"def"],true]', + "[\n 1,\n \"abc\",\n [\n 2,\n \"def\"\n ],\n true\n]", + ], + [ + [ + 'a' => 1, + 'b' => 'abc', + 'c' => [2, '<>'], + true, + ], + '{"a":1,"b":"abc","c":[2,"<>"],"0":true}', + "{\n \"a\": 1,\n \"b\": \"abc\",\n \"c\": [\n 2,\n \"<>\"\n ],\n \"0\": true\n}", + ], ]; } @@ -84,14 +95,14 @@ class JsonResponseFormatterTest extends FormatterTest $postsStack->push(new Post(456, 'record2')); return [ - [$postsStack, '{"1":{"id":456,"title":"record2"},"0":{"id":915,"title":"record1"}}'] + [$postsStack, '{"1":{"id":456,"title":"record2"},"0":{"id":915,"title":"record1"}}'], ]; } public function formatModelDataProvider() { return [ - [new ModelStub(['id' => 123, 'title' => 'abc', 'hidden' => 'hidden']), '{"id":123,"title":"abc"}'] + [new ModelStub(['id' => 123, 'title' => 'abc', 'hidden' => 'hidden']), '{"id":123,"title":"abc"}'], ]; } @@ -108,5 +119,4 @@ class JsonResponseFormatterTest extends FormatterTest $this->formatter->format($this->response); $this->assertEquals($prettyJson, $this->response->content); } - } diff --git a/tests/framework/web/MultipartFormDataParserTest.php b/tests/framework/web/MultipartFormDataParserTest.php index 3f9e867..68375eb 100644 --- a/tests/framework/web/MultipartFormDataParserTest.php +++ b/tests/framework/web/MultipartFormDataParserTest.php @@ -1,4 +1,9 @@ 'test-title', 'Item' => [ - 'name' => 'test-name' - ] + 'name' => 'test-name', + ], ]; $this->assertEquals($expectedBodyParams, $bodyParams); @@ -55,7 +60,7 @@ class MultipartFormDataParserTest extends TestCase $parser = new MultipartFormDataParser(); $_POST = [ - 'name' => 'value' + 'name' => 'value', ]; $bodyParams = $parser->parse('should not matter', 'multipart/form-data; boundary=---12345'); @@ -74,7 +79,7 @@ class MultipartFormDataParserTest extends TestCase 'file' => [ 'name' => 'file.txt', 'type' => 'text/plain', - ] + ], ]; $boundary = '---------------------------22472926011618'; @@ -123,4 +128,4 @@ class MultipartFormDataParserTest extends TestCase $this->assertCount(3, $_FILES); $this->assertEquals(UPLOAD_ERR_INI_SIZE, $_FILES['thirdFile']['error']); } -} \ No newline at end of file +} diff --git a/tests/framework/web/Post.php b/tests/framework/web/Post.php index d6ebc68..0f27868 100644 --- a/tests/framework/web/Post.php +++ b/tests/framework/web/Post.php @@ -1,4 +1,10 @@ id = $id; $this->title = $title; } -} \ No newline at end of file +} diff --git a/tests/framework/web/RequestTest.php b/tests/framework/web/RequestTest.php index 667f7d7..c8e765e 100644 --- a/tests/framework/web/RequestTest.php +++ b/tests/framework/web/RequestTest.php @@ -17,7 +17,7 @@ class RequestTest extends TestCase { public function testParseAcceptHeader() { - $request = new Request; + $request = new Request(); $this->assertEquals([], $request->parseAcceptHeader(' ')); @@ -149,7 +149,6 @@ class RequestTest extends TestCase $request->setBodyParams([$request->csrfParam => $token]); $this->assertTrue($request->validateCsrfToken()); } - } /** @@ -179,7 +178,6 @@ class RequestTest extends TestCase $request->headers->add(Request::CSRF_HEADER, $token); $this->assertTrue($request->validateCsrfToken()); } - } public function testResolve() @@ -194,8 +192,8 @@ class RequestTest extends TestCase 'posts' => 'post/list', 'post/' => 'post/view', ], - ] - ] + ], + ], ]); $request = new Request(); diff --git a/tests/framework/web/ResponseTest.php b/tests/framework/web/ResponseTest.php index edfe170..902fac3 100644 --- a/tests/framework/web/ResponseTest.php +++ b/tests/framework/web/ResponseTest.php @@ -1,10 +1,15 @@ mockWebApplication(); - $this->response = new \yii\web\Response; + $this->response = new \yii\web\Response(); } public function rightRanges() @@ -51,8 +56,8 @@ class ResponseTest extends \yiiunit\TestCase $this->assertEquals($expectedContent, $content); $this->assertEquals(206, $this->response->statusCode); $headers = $this->response->headers; - $this->assertEquals("bytes", $headers->get('Accept-Ranges')); - $this->assertEquals("bytes " . $expectedHeader . '/' . StringHelper::byteLength($fullContent), $headers->get('Content-Range')); + $this->assertEquals('bytes', $headers->get('Accept-Ranges')); + $this->assertEquals('bytes ' . $expectedHeader . '/' . StringHelper::byteLength($fullContent), $headers->get('Content-Range')); $this->assertEquals('text/plain', $headers->get('Content-Type')); $this->assertEquals("$length", $headers->get('Content-Length')); } @@ -62,10 +67,10 @@ class ResponseTest extends \yiiunit\TestCase // TODO test more cases for range requests and check for rfc compatibility // http://www.w3.org/Protocols/rfc2616/rfc2616.txt return [ - ['1-2,3-5,6-10'], // multiple range request not supported - ['5-1'], // last-byte-pos value is less than its first-byte-pos value - ['-100000'], // last-byte-pos bigger then content length - ['10000-'], // first-byte-pos bigger then content length + ['1-2,3-5,6-10'], // multiple range request not supported + ['5-1'], // last-byte-pos value is less than its first-byte-pos value + ['-100000'], // last-byte-pos bigger then content length + ['10000-'], // first-byte-pos bigger then content length ]; } @@ -93,7 +98,7 @@ class ResponseTest extends \yiiunit\TestCase { ob_start(); $this->response->sendContentAsFile('test', 'test.txt')->send([ - 'mimeType' => 'text/plain' + 'mimeType' => 'text/plain', ]); $content = ob_get_clean(); @@ -124,7 +129,6 @@ class ResponseTest extends \yiiunit\TestCase /** * @dataProvider dataProviderSetStatusCodeByException - * */ public function testSetStatusCodeByException($exception, $statusCode) { diff --git a/tests/framework/web/SessionTest.php b/tests/framework/web/SessionTest.php index 370d1aa..c5d353d 100644 --- a/tests/framework/web/SessionTest.php +++ b/tests/framework/web/SessionTest.php @@ -1,4 +1,9 @@ md5(mt_rand()), 'type' => 'image/jpeg', 'size' => mt_rand(1000, 10000), - 'error' => 0 + 'error' => 0, ]; } @@ -67,4 +72,4 @@ class UploadedFileTest extends TestCase $this->assertInstanceOf(VendorImage::className(), $vendorImage); } } -} \ No newline at end of file +} diff --git a/tests/framework/web/UrlManagerCreateUrlTest.php b/tests/framework/web/UrlManagerCreateUrlTest.php index 004db57..0c0cf04 100644 --- a/tests/framework/web/UrlManagerCreateUrlTest.php +++ b/tests/framework/web/UrlManagerCreateUrlTest.php @@ -1,4 +1,9 @@ '', 'route' => 'site/index', 'defaults' => [ - 'language' => 'en' + 'language' => 'en', ], ], ]; @@ -434,7 +439,7 @@ class UrlManagerCreateUrlTest extends TestCase */ public function testWithEmptyPattern($method, $showScriptName, $prefix, $config) { - $assertations = function($manager) use ($method, $prefix) { + $assertations = function ($manager) use ($method, $prefix) { // match first rule $url = $manager->$method(['front/site/index']); $this->assertEquals("$prefix/", $url); @@ -551,7 +556,6 @@ class UrlManagerCreateUrlTest extends TestCase $this->assertEquals("$prefix/post/index?page=1#testhash", $manager->createUrl($urlParams)); $expected = "http://www.example.com$prefix/post/index?page=1#testhash"; $this->assertEquals($expected, $manager->createAbsoluteUrl($urlParams)); - } /** @@ -754,5 +758,4 @@ class UrlManagerCreateUrlTest extends TestCase $this->assertEquals(2, $rules[0]->createCounter); $this->assertEquals(1, $rules[1]->createCounter); } - } diff --git a/tests/framework/web/UrlManagerParseUrlTest.php b/tests/framework/web/UrlManagerParseUrlTest.php index 805b5c2..439e659 100644 --- a/tests/framework/web/UrlManagerParseUrlTest.php +++ b/tests/framework/web/UrlManagerParseUrlTest.php @@ -1,4 +1,9 @@ getUrlManager($config); // matching pathinfo - $result = $manager->parseRequest($this->getRequest("book/123/this+is+sample")); + $result = $manager->parseRequest($this->getRequest('book/123/this+is+sample')); $this->assertFalse($result); $result = $manager->parseRequest($this->getRequest("book/123/this+is+sample$suffix")); $this->assertEquals(['book/view', ['id' => '123', 'title' => 'this+is+sample']], $result); // trailing slash is significant, no match - $result = $manager->parseRequest($this->getRequest("book/123/this+is+sample/")); + $result = $manager->parseRequest($this->getRequest('book/123/this+is+sample/')); if ($suffix === '/') { $this->assertEquals(['book/view', ['id' => '123', 'title' => 'this+is+sample']], $result); } else { @@ -224,12 +229,12 @@ class UrlManagerParseUrlTest extends TestCase $result = $manager->parseRequest($this->getRequest('')); $this->assertEquals(['', []], $result); // normal pathinfo - $result = $manager->parseRequest($this->getRequest("site/index")); + $result = $manager->parseRequest($this->getRequest('site/index')); $this->assertFalse($result); $result = $manager->parseRequest($this->getRequest("site/index$suffix")); $this->assertEquals(['site/index', []], $result); // pathinfo with module - $result = $manager->parseRequest($this->getRequest("module/site/index")); + $result = $manager->parseRequest($this->getRequest('module/site/index')); $this->assertFalse($result); $result = $manager->parseRequest($this->getRequest("module/site/index$suffix")); $this->assertEquals(['module/site/index', []], $result); @@ -252,12 +257,12 @@ class UrlManagerParseUrlTest extends TestCase $manager->enableStrictParsing = true; // matching pathinfo - $result = $manager->parseRequest($this->getRequest("book/123/this+is+sample")); + $result = $manager->parseRequest($this->getRequest('book/123/this+is+sample')); $this->assertFalse($result); $result = $manager->parseRequest($this->getRequest("book/123/this+is+sample$suffix")); $this->assertEquals(['book/view', ['id' => '123', 'title' => 'this+is+sample']], $result); // trailing slash is significant, no match - $result = $manager->parseRequest($this->getRequest("book/123/this+is+sample/")); + $result = $manager->parseRequest($this->getRequest('book/123/this+is+sample/')); if ($suffix === '/') { $this->assertEquals(['book/view', ['id' => '123', 'title' => 'this+is+sample']], $result); } else { @@ -269,12 +274,12 @@ class UrlManagerParseUrlTest extends TestCase $result = $manager->parseRequest($this->getRequest('')); $this->assertFalse($result); // normal pathinfo - $result = $manager->parseRequest($this->getRequest("site/index")); + $result = $manager->parseRequest($this->getRequest('site/index')); $this->assertFalse($result); $result = $manager->parseRequest($this->getRequest("site/index$suffix")); $this->assertFalse($result); // pathinfo with module - $result = $manager->parseRequest($this->getRequest("module/site/index")); + $result = $manager->parseRequest($this->getRequest('module/site/index')); $this->assertFalse($result); $result = $manager->parseRequest($this->getRequest("module/site/index$suffix")); $this->assertFalse($result); @@ -288,7 +293,7 @@ class UrlManagerParseUrlTest extends TestCase public function testParseRESTRequest() { - $request = new Request; + $request = new Request(); // pretty URL rules $manager = new UrlManager([ @@ -328,16 +333,13 @@ class UrlManagerParseUrlTest extends TestCase 'components' => [ 'request' => [ 'hostInfo' => 'http://localhost/', - 'baseUrl' => '/app' - ] - ] + 'baseUrl' => '/app', + ], + ], ], \yii\web\Application::className()); $this->assertEquals('/app/post/delete?id=123', $manager->createUrl(['post/delete', 'id' => 123])); $this->destroyApplication(); unset($_SERVER['REQUEST_METHOD']); } - - - -} \ No newline at end of file +} diff --git a/tests/framework/web/UrlManagerTest.php b/tests/framework/web/UrlManagerTest.php index 9993ea0..ee5f8b7 100644 --- a/tests/framework/web/UrlManagerTest.php +++ b/tests/framework/web/UrlManagerTest.php @@ -1,4 +1,10 @@ mockApplication(); - Yii::$app->set('request', function() { + Yii::$app->set('request', function () { $this->fail('Request component should not be accessed by UrlManager with current settings.'); }); @@ -214,7 +220,7 @@ class UrlManagerTest extends TestCase public function testParseRequest($routeParam) { $manager = $this->getUrlManager(['routeParam' => $routeParam]); - $request = new Request; + $request = new Request(); // default setting without 'r' param $request->setQueryParams([]); diff --git a/tests/framework/web/UrlRuleTest.php b/tests/framework/web/UrlRuleTest.php index 2e9846a..69bcfac 100644 --- a/tests/framework/web/UrlRuleTest.php +++ b/tests/framework/web/UrlRuleTest.php @@ -1,15 +1,20 @@ null]); $suites = $this->getTestsForCreateUrl(); foreach ($suites as $i => $suite) { - list ($name, $config, $tests) = $suite; + list($name, $config, $tests) = $suite; $rule = new UrlRule($config); foreach ($tests as $j => $test) { - list ($route, $params, $expected) = $test; + list($route, $params, $expected) = $test; $url = $rule->createUrl($manager, $route, $params); $this->assertSame($expected, $url, "Test#$i-$j: $name"); } @@ -47,7 +52,7 @@ class UrlRuleTest extends TestCase $request = new Request(['hostInfo' => 'http://en.example.com']); $suites = $this->getTestsForParseRequest(); foreach ($suites as $i => $suite) { - list ($name, $config, $tests) = $suite; + list($name, $config, $tests) = $suite; $rule = new UrlRule($config); foreach ($tests as $j => $test) { $request->pathInfo = $test[0]; @@ -71,7 +76,7 @@ class UrlRuleTest extends TestCase $request = new Request(['hostInfo' => 'http://en.example.com']); $suites = $this->getTestsForParseRequest(); foreach ($suites as $i => $suite) { - list ($name, $config, $tests) = $suite; + list($name, $config, $tests) = $suite; $rule = new UrlRule($config); foreach ($tests as $j => $test) { $request->pathInfo = $test[0]; @@ -102,7 +107,7 @@ class UrlRuleTest extends TestCase $request = new Request(['hostInfo' => 'http://en.example.com']); $suites = $this->getTestsForParseRequest(); foreach ($suites as $i => $suite) { - list ($name, $config, $tests) = $suite; + list($name, $config, $tests) = $suite; $rule = new UrlRule($config); foreach ($tests as $j => $test) { $request->pathInfo = $test[0]; @@ -131,7 +136,7 @@ class UrlRuleTest extends TestCase $request = new Request(['hostInfo' => 'http://en.example.com']); $suites = $this->getTestsForParseRequest(); foreach ($suites as $i => $suite) { - list ($name, $config, $tests) = $suite; + list($name, $config, $tests) = $suite; $rule = new UrlRule($config); foreach ($tests as $j => $test) { $request->pathInfo = $test[0]; @@ -160,7 +165,7 @@ class UrlRuleTest extends TestCase $request = new Request(['hostInfo' => 'http://en.example.com']); $suites = $this->getTestsForParseRequest(); foreach ($suites as $i => $suite) { - list ($name, $config, $tests) = $suite; + list($name, $config, $tests) = $suite; $rule = new UrlRule($config); foreach ($tests as $j => $test) { $request->pathInfo = $test[0]; @@ -188,7 +193,7 @@ class UrlRuleTest extends TestCase $request = new Request(['hostInfo' => 'http://en.example.com']); $suites = $this->getTestsForParseRequest(); foreach ($suites as $i => $suite) { - list ($name, $config, $tests) = $suite; + list($name, $config, $tests) = $suite; $rule = new UrlRule($config); foreach ($tests as $j => $test) { $request->pathInfo = $test[0]; @@ -217,7 +222,7 @@ class UrlRuleTest extends TestCase $request = new Request(['hostInfo' => 'http://en.example.com']); $suites = $this->getTestsForParseRequest(); foreach ($suites as $i => $suite) { - list ($name, $config, $tests) = $suite; + list($name, $config, $tests) = $suite; $rule = new UrlRule($config); foreach ($tests as $j => $test) { $request->pathInfo = $test[0]; @@ -278,7 +283,7 @@ class UrlRuleTest extends TestCase { $suites = $this->getTestsForToString(); foreach ($suites as $i => $suite) { - list ($name, $config, $test) = $suite; + list($name, $config, $test) = $suite; $rule = new UrlRule($config); $this->assertEquals($rule->__toString(), $test, "Test#$i: $name"); } @@ -494,7 +499,7 @@ class UrlRuleTest extends TestCase 'pattern' => '', 'route' => 'page/view', 'defaults' => ['page' => 'index'], - 'suffix' => '/' + 'suffix' => '/', ], [ ['page/view', ['page' => 'index'], ''], @@ -1236,7 +1241,7 @@ class UrlRuleTest extends TestCase 'pattern' => '', 'route' => 'post/index', ], - '/' + '/', ], [ 'multiple params with special chars', @@ -1244,7 +1249,7 @@ class UrlRuleTest extends TestCase 'pattern' => 'post///', 'route' => 'post/index', ], - 'post///' + 'post///', ], [ 'with host info', @@ -1254,7 +1259,7 @@ class UrlRuleTest extends TestCase 'defaults' => ['page' => 1], 'host' => 'http://.example.com', ], - 'http://.example.com/post//' + 'http://.example.com/post//', ], [ 'with host info in pattern', @@ -1263,28 +1268,26 @@ class UrlRuleTest extends TestCase 'route' => 'post/index', 'defaults' => ['page' => 1], ], - 'http://.example.com/post//' + 'http://.example.com/post//', ], [ 'with verb', [ 'verb' => ['POST'], 'pattern' => 'post/', - 'route' => 'post/index' + 'route' => 'post/index', ], - 'POST post/' + 'POST post/', ], [ 'with verbs', [ 'verb' => ['PUT', 'POST'], 'pattern' => 'post/', - 'route' => 'post/index' + 'route' => 'post/index', ], - 'PUT,POST post/' + 'PUT,POST post/', ], - - ]; } diff --git a/tests/framework/web/UserTest.php b/tests/framework/web/UserTest.php index 0b2e4db..9880566 100644 --- a/tests/framework/web/UserTest.php +++ b/tests/framework/web/UserTest.php @@ -1,5 +1,9 @@ '@runtime/user_test_rbac_items.php', 'assignmentFile' => '@runtime/user_test_rbac_assignments.php', 'ruleFile' => '@runtime/user_test_rbac_rules.php', - ] + ], ], ]; $this->mockWebApplication($appConfig); @@ -91,7 +95,6 @@ class UserTest extends TestCase $this->mockWebApplication($appConfig); $this->assertTrue(Yii::$app->user->isGuest); $this->assertFalse(Yii::$app->user->can('doSomething')); - } public function testCookieCleanup() @@ -124,12 +127,12 @@ class UserTest extends TestCase Yii::$app->user->getIdentity(); $this->assertEquals(strlen($cookiesMock->getValue(Yii::$app->user->identityCookie['name'])), 0); - Yii::$app->user->login(UserIdentity::findIdentity('user1'),3600); + Yii::$app->user->login(UserIdentity::findIdentity('user1'), 3600); $this->assertFalse(Yii::$app->user->isGuest); $this->assertSame(Yii::$app->user->id, 'user1'); $this->assertNotEquals(strlen($cookiesMock->getValue(Yii::$app->user->identityCookie['name'])), 0); - Yii::$app->user->login(UserIdentity::findIdentity('user2'),0); + Yii::$app->user->login(UserIdentity::findIdentity('user2'), 0); $this->assertFalse(Yii::$app->user->isGuest); $this->assertSame(Yii::$app->user->id, 'user2'); $this->assertEquals(strlen($cookiesMock->getValue(Yii::$app->user->identityCookie['name'])), 0); @@ -150,9 +153,9 @@ class UserTest extends TestCase Yii::$app->set('response', ['class' => 'yii\web\Response']); Yii::$app->set('request', [ 'class' => 'yii\web\Request', - 'scriptFile' => __DIR__ .'/index.php', + 'scriptFile' => __DIR__ . '/index.php', 'scriptUrl' => '/index.php', - 'url' => '' + 'url' => '', ]); Yii::$app->user->setReturnUrl(null); } @@ -168,7 +171,7 @@ class UserTest extends TestCase 'itemFile' => '@runtime/user_test_rbac_items.php', 'assignmentFile' => '@runtime/user_test_rbac_assignments.php', 'ruleFile' => '@runtime/user_test_rbac_rules.php', - ] + ], ], ]; $this->mockWebApplication($appConfig); @@ -222,7 +225,8 @@ class UserTest extends TestCase $_SERVER['HTTP_ACCEPT'] = 'text/json, */*; q=0.1'; try { $user->loginRequired(); - } catch (ForbiddenHttpException $e) {} + } catch (ForbiddenHttpException $e) { + } $this->assertFalse(Yii::$app->response->getIsRedirection()); $this->reset(); @@ -259,7 +263,8 @@ class UserTest extends TestCase $_SERVER['HTTP_ACCEPT'] = 'text/json;q=0.1'; try { $user->loginRequired(); - } catch (ForbiddenHttpException $e) {} + } catch (ForbiddenHttpException $e) { + } $this->assertNotEquals('json-only', $user->getReturnUrl()); $this->reset(); @@ -280,7 +285,7 @@ class UserTest extends TestCase 'itemFile' => '@runtime/user_test_rbac_items.php', 'assignmentFile' => '@runtime/user_test_rbac_assignments.php', 'ruleFile' => '@runtime/user_test_rbac_rules.php', - ] + ], ], ]; @@ -290,7 +295,6 @@ class UserTest extends TestCase $this->expectException('yii\\web\\ForbiddenHttpException'); Yii::$app->user->loginRequired(); } - } class UserIdentity extends Component implements IdentityInterface @@ -342,7 +346,7 @@ class MockRequest extends \yii\web\Request global $cookiesMock; return $cookiesMock; - } + } } class MockResponse extends \yii\web\Response diff --git a/tests/framework/web/ViewTest.php b/tests/framework/web/ViewTest.php index d780526..9064352 100644 --- a/tests/framework/web/ViewTest.php +++ b/tests/framework/web/ViewTest.php @@ -1,4 +1,9 @@ mockWebApplication([ 'components' => [ 'request' => [ - 'scriptFile' => __DIR__ .'/baseUrl/index.php', + 'scriptFile' => __DIR__ . '/baseUrl/index.php', 'scriptUrl' => '/baseUrl/index.php', - ] - ] + ], + ], ]); $view = new View(); @@ -34,7 +39,7 @@ class ViewTest extends TestCase $view = new View(); $view->registerJsFile('@web/js/somefile.js', ['position' => View::POS_BEGIN]); $html = $view->render('@yiiunit/data/views/layout.php', ['content' => 'content']); - $this->assertContains(''."\n".'', $html); + $this->assertContains('' . "\n" . '', $html); $view = new View(); $view->registerJsFile('@web/js/somefile.js', ['position' => View::POS_END]); @@ -47,10 +52,10 @@ class ViewTest extends TestCase $this->mockWebApplication([ 'components' => [ 'request' => [ - 'scriptFile' => __DIR__ .'/baseUrl/index.php', + 'scriptFile' => __DIR__ . '/baseUrl/index.php', 'scriptUrl' => '/baseUrl/index.php', - ] - ] + ], + ], ]); $view = new View(); @@ -58,5 +63,4 @@ class ViewTest extends TestCase $html = $view->render('@yiiunit/data/views/layout.php', ['content' => 'content']); $this->assertContains('', $html); } - -} \ No newline at end of file +} diff --git a/tests/framework/web/XmlResponseFormatterTest.php b/tests/framework/web/XmlResponseFormatterTest.php index 046f2bb..6d07b30 100644 --- a/tests/framework/web/XmlResponseFormatterTest.php +++ b/tests/framework/web/XmlResponseFormatterTest.php @@ -44,7 +44,7 @@ class XmlResponseFormatterTest extends FormatterTest ['abc', "abc\n"], [true, "true\n"], [false, "false\n"], - ["<>", "<>\n"], + ['<>', "<>\n"], ]); } @@ -77,7 +77,7 @@ class XmlResponseFormatterTest extends FormatterTest '2015-06-18' => '2015-06-18', 'b:c' => 'b:c', 'a b c' => 'a b c', - 'äøñ' => 'äøñ' + 'äøñ' => 'äøñ', ], "12015-06-18b:ca b c<äøñ>äøñ\n"], ]); } @@ -97,7 +97,7 @@ class XmlResponseFormatterTest extends FormatterTest $expectedXmlForStack; $data = [ - [$postsStack, "$expectedXmlForStack\n"] + [$postsStack, "$expectedXmlForStack\n"], ]; return $this->addXmlHead($data); @@ -123,8 +123,8 @@ class XmlResponseFormatterTest extends FormatterTest return $this->addXmlHead([ [ new ModelStub(['id' => 123, 'title' => 'abc', 'hidden' => 'hidden']), - "123abc\n" - ] + "123abc\n", + ], ]); } diff --git a/tests/framework/web/stubs/CachedUrlRule.php b/tests/framework/web/stubs/CachedUrlRule.php index 3611644..9444fff 100644 --- a/tests/framework/web/stubs/CachedUrlRule.php +++ b/tests/framework/web/stubs/CachedUrlRule.php @@ -1,4 +1,9 @@ mockWebApplication(); @@ -78,7 +83,7 @@ EOD; { // field will be the html of the model's attribute wrapped with the return string below. $field = $this->attributeName; - $content = function($field) { + $content = function ($field) { return "
            $field
            "; }; @@ -119,7 +124,7 @@ EOD; public function testBeginHasErrors() { - $this->helperModel->addError($this->attributeName, "Error Message"); + $this->helperModel->addError($this->attributeName, 'Error Message'); $expectedValue = '
            '; $actualValue = $this->activeField->begin(); @@ -139,7 +144,7 @@ EOD; public function testBeginHasErrorAndRequired() { - $this->helperModel->addError($this->attributeName, "Error Message"); + $this->helperModel->addError($this->attributeName, 'Error Message'); $this->helperModel->addRule($this->attributeName, 'required'); $expectedValue = '
            '; @@ -156,13 +161,13 @@ EOD; $this->assertEquals($expectedValue, $actualValue); - $expectedValue = ""; + $expectedValue = ''; $this->activeField->options['tag'] = null; $actualValue = $this->activeField->begin(); $this->assertEquals($expectedValue, $actualValue); - $expectedValue = ""; + $expectedValue = ''; $this->activeField->options['tag'] = false; $actualValue = $this->activeField->begin(); @@ -177,19 +182,19 @@ EOD; $this->assertEquals($expectedValue, $actualValue); // other tag - $expectedValue = ""; + $expectedValue = ''; $this->activeField->options['tag'] = 'article'; $actualValue = $this->activeField->end(); $this->assertEquals($expectedValue, $actualValue); - $expectedValue = ""; + $expectedValue = ''; $this->activeField->options['tag'] = false; $actualValue = $this->activeField->end(); $this->assertEquals($expectedValue, $actualValue); - $expectedValue = ""; + $expectedValue = ''; $this->activeField->options['tag'] = null; $actualValue = $this->activeField->end(); @@ -266,7 +271,7 @@ EOT; $expectedValue = << EOD; - $this->activeField->input("password"); + $this->activeField->input('password'); $this->assertEquals($expectedValue, $this->activeField->parts['{input}']); @@ -274,7 +279,7 @@ EOD; $expectedValue = << EOD; - $this->activeField->input("password", ['weird' => 'value']); + $this->activeField->input('password', ['weird' => 'value']); $this->assertEquals($expectedValue, $this->activeField->parts['{input}']); } @@ -305,7 +310,7 @@ EOD; EOD; - $this->activeField->listBox(["1" => "Item One", "2" => "Item 2"]); + $this->activeField->listBox(['1' => 'Item One', '2' => 'Item 2']); $this->assertEqualsWithoutLE($expectedValue, $this->activeField->parts['{input}']); // https://github.com/yiisoft/yii2/issues/8848 @@ -315,7 +320,7 @@ EOD; EOD; - $this->activeField->listBox(["value1" => "Item One", "value2" => "Item 2"], ['options' => [ + $this->activeField->listBox(['value1' => 'Item One', 'value2' => 'Item 2'], ['options' => [ 'value1' => ['disabled' => true], 'value2' => ['label' => 'value 2'], ]]); @@ -328,7 +333,7 @@ EOD; EOD; $this->activeField->model->{$this->attributeName} = 'value2'; - $this->activeField->listBox(["value1" => "Item One", "value2" => "Item 2"], ['options' => [ + $this->activeField->listBox(['value1' => 'Item One', 'value2' => 'Item 2'], ['options' => [ 'value1' => ['disabled' => true], 'value2' => ['label' => 'value 2'], ]]); @@ -355,7 +360,6 @@ EOD; // expected empty $actualValue = $this->activeField->getClientOptions(); $this->assertEmpty($actualValue); - } public function testGetClientOptionsClientValidation() @@ -365,7 +369,7 @@ EOD; $this->activeField->model->addRule($this->attributeName, 'yiiunit\framework\widgets\TestValidator'); $this->activeField->enableClientValidation = true; $actualValue = $this->activeField->getClientOptions(); - $expectedJsExpression = "function (attribute, value, messages, deferred, \$form) {return true;}"; + $expectedJsExpression = 'function (attribute, value, messages, deferred, $form) {return true;}'; $this->assertEquals($expectedJsExpression, $actualValue['validate']); $this->assertNotTrue(isset($actualValue['validateOnChange'])); @@ -400,7 +404,7 @@ EOD; } $actualValue = $this->activeField->getClientOptions(); - $expectedJsExpression = "function (attribute, value, messages, deferred, \$form) {if ((function (attribute, value) " + $expectedJsExpression = 'function (attribute, value, messages, deferred, $form) {if ((function (attribute, value) ' . "{ return 'yii2' == 'yii2'; })(attribute, value)) { return true; }}"; $this->assertEquals($expectedJsExpression, $actualValue['validate']->expression); @@ -534,7 +538,6 @@ EOD; return $view; } - } class ActiveFieldTestModel extends DynamicModel @@ -576,10 +579,9 @@ class ActiveFieldExtend extends ActiveField class TestValidator extends \yii\validators\Validator { - public function clientValidateAttribute($object, $attribute, $view) { - return "return true;"; + return 'return true;'; } public function setWhenClient($js) @@ -605,4 +607,4 @@ class TestInputWidget extends InputWidget { return 'Render: ' . get_class($this); } -} \ No newline at end of file +} diff --git a/tests/framework/widgets/ActiveFormTest.php b/tests/framework/widgets/ActiveFormTest.php index 9496bca..0123e5e 100644 --- a/tests/framework/widgets/ActiveFormTest.php +++ b/tests/framework/widgets/ActiveFormTest.php @@ -1,6 +1,8 @@ + * @link http://www.yiiframework.com/ + * @copyright Copyright (c) 2008 Yii Software LLC + * @license http://www.yiiframework.com/license/ */ namespace yiiunit\framework\widgets; @@ -52,7 +54,6 @@ EOF
            EOF , (string) $form->field($model, 'name', $o)->input('email', ['required' => 'test'])); - } public function testIssue5356() @@ -105,7 +106,6 @@ EOF HTML , $content); - } public function testRegisterClientScript() diff --git a/tests/framework/widgets/BreadcrumbsTest.php b/tests/framework/widgets/BreadcrumbsTest.php index 17a816e..d2d0f3e 100644 --- a/tests/framework/widgets/BreadcrumbsTest.php +++ b/tests/framework/widgets/BreadcrumbsTest.php @@ -1,4 +1,9 @@ mockWebApplication(); $this->breadcrumbs = new Breadcrumbs(); @@ -33,7 +38,7 @@ class BreadcrumbsTest extends \yiiunit\TestCase $expectedHtml = "
            • Home
            • \n" . "
            • My Home Page
            • \n" . "
            • http://my.example.com/yii2/link/page
            • \n" - . "
            "; + . ''; ob_start(); $this->breadcrumbs->run(); @@ -55,7 +60,7 @@ class BreadcrumbsTest extends \yiiunit\TestCase $expectedHtml = "
            • My Home Page
            • \n" . "
            • http://my.example.com/yii2/link/page
            • \n" - . "
            "; + . ''; ob_start(); $this->breadcrumbs->run(); @@ -74,7 +79,7 @@ class BreadcrumbsTest extends \yiiunit\TestCase $expectedHtml = "
            • home-link
            • \n" . "
            • My Home Page
            • \n" . "
            • http://my.example.com/yii2/link/page
            • \n" - . "
            "; + . ''; ob_start(); $this->breadcrumbs->run(); diff --git a/tests/framework/widgets/DetailViewTest.php b/tests/framework/widgets/DetailViewTest.php index 0fb2949..ea0b505 100644 --- a/tests/framework/widgets/DetailViewTest.php +++ b/tests/framework/widgets/DetailViewTest.php @@ -1,6 +1,8 @@ + * @link http://www.yiiframework.com/ + * @copyright Copyright (c) 2008 Yii Software LLC + * @license http://www.yiiframework.com/license/ */ namespace yiiunit\framework\widgets; @@ -164,7 +166,7 @@ class DetailViewTest extends \yiiunit\TestCase 'label' => 'Id', 'value' => 'Displayed id', 'visible' => true, - ] + ], ], $this->detailView->attributes); $this->assertEquals(5, $model->getDisplayedIdCallCount()); } @@ -211,13 +213,13 @@ class DetailViewTest extends \yiiunit\TestCase 'attribute' => 'id', 'format' => 'text', 'label' => 'Id', - 'value' => 1 + 'value' => 1, ], [ 'attribute' => 'text', 'format' => 'text', 'label' => 'Text', - 'value' => 'I`m arrayable' + 'value' => 'I`m arrayable', ], ]; @@ -239,13 +241,13 @@ class DetailViewTest extends \yiiunit\TestCase 'attribute' => 'id', 'format' => 'text', 'label' => 'Id', - 'value' => 1 + 'value' => 1, ], [ 'attribute' => 'text', 'format' => 'text', 'label' => 'Text', - 'value' => 'I`m an object' + 'value' => 'I`m an object', ], ]; @@ -267,19 +269,19 @@ class DetailViewTest extends \yiiunit\TestCase 'attribute' => 'id', 'format' => 'text', 'label' => 'Id', - 'value' => 1 + 'value' => 1, ], [ 'attribute' => 'text', 'format' => 'text', 'label' => 'Text', - 'value' => 'I`m an array' + 'value' => 'I`m an array', ], ]; $model = [ 'id' => 1, - 'text' => 'I`m an array' + 'text' => 'I`m an array', ]; $this->detailView = new DetailView([ @@ -307,7 +309,7 @@ class DetailViewTest extends \yiiunit\TestCase ], ]); - foreach ($this->detailView->attributes as $index=>$attribute) { + foreach ($this->detailView->attributes as $index => $attribute) { $a = $this->detailView->renderAttribute($attribute, $index); $this->assertEquals($expectedValue, $a); } diff --git a/tests/framework/widgets/FragmentCacheTest.php b/tests/framework/widgets/FragmentCacheTest.php index 0800c6b..90d6f35 100644 --- a/tests/framework/widgets/FragmentCacheTest.php +++ b/tests/framework/widgets/FragmentCacheTest.php @@ -1,10 +1,15 @@ assertTrue($view->beginCache('test')); - echo "cached fragment"; + echo 'cached fragment'; $view->endCache(); ob_start(); ob_implicit_flush(false); $this->assertFalse($view->beginCache('test')); - $this->assertEquals("cached fragment", ob_get_clean()); + $this->assertEquals('cached fragment', ob_get_clean()); ob_end_clean(); $this->assertEquals($expectedLevel, ob_get_level(), 'Output buffer not closed correctly.'); @@ -49,15 +54,15 @@ class FragmentCacheTest extends \yiiunit\TestCase $view = new View(); $this->assertTrue($view->beginCache('test', ['enabled' => false])); - echo "cached fragment"; + echo 'cached fragment'; $view->endCache(); ob_start(); ob_implicit_flush(false); $this->assertTrue($view->beginCache('test', ['enabled' => false])); - echo "cached fragment"; + echo 'cached fragment'; $view->endCache(); - $this->assertEquals("cached fragment", ob_get_clean()); + $this->assertEquals('cached fragment', ob_get_clean()); ob_end_clean(); $this->assertEquals($expectedLevel, ob_get_level(), 'Output buffer not closed correctly.'); @@ -71,15 +76,15 @@ class FragmentCacheTest extends \yiiunit\TestCase $view = new View(); $this->assertTrue($view->beginCache('test')); - echo "cached fragment"; + echo 'cached fragment'; $view->endCache(); ob_start(); ob_implicit_flush(false); $this->assertTrue($view->beginCache('test', ['enabled' => false])); - echo "cached fragment other"; + echo 'cached fragment other'; $view->endCache(); - $this->assertEquals("cached fragment other", ob_get_clean()); + $this->assertEquals('cached fragment other', ob_get_clean()); ob_end_clean(); $this->assertEquals($expectedLevel, ob_get_level(), 'Output buffer not closed correctly.'); diff --git a/tests/framework/widgets/LinkPagerTest.php b/tests/framework/widgets/LinkPagerTest.php index 90acf13..e3af651 100644 --- a/tests/framework/widgets/LinkPagerTest.php +++ b/tests/framework/widgets/LinkPagerTest.php @@ -1,4 +1,9 @@ mockApplication([ 'components' => [ 'urlManager' => [ - 'scriptUrl' => '/' - ] - ] + 'scriptUrl' => '/', + ], + ], ]); } @@ -32,7 +37,7 @@ class LinkPagerTest extends \yiiunit\TestCase $output = LinkPager::widget([ 'pagination' => $pagination, 'firstPageLabel' => true, - 'lastPageLabel' => true + 'lastPageLabel' => true, ]); static::assertContains('
          • 1
          • ', $output); @@ -41,7 +46,7 @@ class LinkPagerTest extends \yiiunit\TestCase $output = LinkPager::widget([ 'pagination' => $pagination, 'firstPageLabel' => 'First', - 'lastPageLabel' => 'Last' + 'lastPageLabel' => 'Last', ]); static::assertContains('
          • First
          • ', $output); @@ -50,7 +55,7 @@ class LinkPagerTest extends \yiiunit\TestCase $output = LinkPager::widget([ 'pagination' => $pagination, 'firstPageLabel' => false, - 'lastPageLabel' => false + 'lastPageLabel' => false, ]); static::assertNotContains('
          • ', $output); diff --git a/tests/framework/widgets/LinkSorterTest.php b/tests/framework/widgets/LinkSorterTest.php index b770356..f0fd9a6 100644 --- a/tests/framework/widgets/LinkSorterTest.php +++ b/tests/framework/widgets/LinkSorterTest.php @@ -1,4 +1,9 @@ $dataProvider, - 'layout' => "{sorter}", + 'layout' => '{sorter}', ]); $actualHtml = ob_get_clean(); @@ -64,7 +69,7 @@ class LinkSorterTest extends DatabaseTestCase ob_start(); echo ListView::widget([ 'dataProvider' => $dataProvider, - 'layout' => "{sorter}", + 'layout' => '{sorter}', ]); $actualHtml = ob_get_clean(); @@ -73,5 +78,4 @@ class LinkSorterTest extends DatabaseTestCase $this->assertNotFalse(strpos($actualHtml, 'Invoice Total')); } - } diff --git a/tests/framework/widgets/ListViewTest.php b/tests/framework/widgets/ListViewTest.php index 7013527..b1d069c 100644 --- a/tests/framework/widgets/ListViewTest.php +++ b/tests/framework/widgets/ListViewTest.php @@ -1,4 +1,9 @@ getListView([ 'dataProvider' => new ArrayDataProvider(['allModels' => []]), - 'emptyText' => "Nothing at all", + 'emptyText' => 'Nothing at all', ])->run(); $this->expectOutputString('
            Nothing at all
            '); @@ -160,7 +165,6 @@ HTML 'index' => $index, 'id' => $model['id'], ], - ]; }, '
            Showing 1-3 of 3 items.
            @@ -196,7 +200,7 @@ HTML }; $this->getListView([ 'beforeItem' => $before, - 'afterItem' => $after + 'afterItem' => $after, ])->run(); $this->expectOutputString(<< [ [ 'encode' => false, - 'label' => ' Users', - 'url' => '#', + 'label' => ' Users', + 'url' => '#', ], [ 'encode' => true, - 'label' => 'Authors & Publications', - 'url' => '#', + 'label' => 'Authors & Publications', + 'url' => '#', ], - ] + ], ]); $expected = << [ [ 'encode' => false, - 'label' => ' Users', - 'url' => '#', + 'label' => ' Users', + 'url' => '#', ], [ 'encode' => true, - 'label' => 'Authors & Publications', - 'url' => '#', + 'label' => 'Authors & Publications', + 'url' => '#', ], - ] + ], ]); $expected = << [ [ - 'label' => 'item1', - 'url' => '#', + 'label' => 'item1', + 'url' => '#', 'options' => ['tag' => 'div'], ], [ - 'label' => 'item2', - 'url' => '#', + 'label' => 'item2', + 'url' => '#', 'options' => ['tag' => false], ], - ] + ], ]); $expected = << [ [ - 'label' => 'item1', - 'url' => '#', + 'label' => 'item1', + 'url' => '#', ], [ - 'label' => 'item2', - 'url' => '#', + 'label' => 'item2', + 'url' => '#', ], ], - 'itemOptions' => ['tag' => false] + 'itemOptions' => ['tag' => false], ]); $expected = << '', 'items' => [ [ - 'label' => 'item1', - 'url' => '#', - 'template' => 'label: {label}; url: {url}' + 'label' => 'item1', + 'url' => '#', + 'template' => 'label: {label}; url: {url}', ], [ - 'label' => 'item2', - 'template' => 'label: {label}' + 'label' => 'item2', + 'template' => 'label: {label}', ], [ - 'label' => 'item3 (no template)', + 'label' => 'item3 (no template)', ], - ] + ], ]); $expected = << '', 'items' => [ [ - 'label' => 'item1', - 'url' => '#', + 'label' => 'item1', + 'url' => '#', 'template' => 'label: {label}; url: {url}', 'active' => function ($item, $hasActiveChild, $isItemActive, $widget) { return isset($item, $hasActiveChild, $isItemActive, $widget); - } + }, ], [ - 'label' => 'item2', + 'label' => 'item2', 'template' => 'label: {label}', - 'active' => false + 'active' => false, ], [ - 'label' => 'item3 (no template)', - 'active' => 'somestring' + 'label' => 'item3 (no template)', + 'active' => 'somestring', ], - ] + ], ]); $expected = <<mockWebApplication(); } - } diff --git a/tests/framework/widgets/SpacelessTest.php b/tests/framework/widgets/SpacelessTest.php index ae41b4c..a8ae7fb 100644 --- a/tests/framework/widgets/SpacelessTest.php +++ b/tests/framework/widgets/SpacelessTest.php @@ -1,4 +1,9 @@ Bye!

            \n"; echo "\n"; - $expected = "\n

            This is a left bar!

            ". + $expected = "\n

            This is a left bar!

            " . "

            This is a right bar!

            \t

            Bye!

            \n\n"; $this->assertEquals($expected, ob_get_clean()); }