From d2098d7e5dbcc151dcfcc99ac363a8ac84bc48e9 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Wed, 16 Jan 2019 21:35:37 +0100 Subject: [PATCH] fixed CS --- .php_cs.dist | 16 +- ...gisterEventListenersAndSubscribersPass.php | 14 +- .../Doctrine/Form/DoctrineOrmTypeGuesser.php | 40 +- ...erEventListenersAndSubscribersPassTest.php | 140 +++---- .../DoctrineExtensionTest.php | 182 ++++----- .../PropertyInfo/DoctrineExtractorTest.php | 66 ++-- src/Symfony/Bridge/Monolog/Logger.php | 2 +- .../Bridge/Monolog/Tests/LoggerTest.php | 16 +- .../LazyProxy/PhpDumper/ProxyDumperTest.php | 28 +- .../Bridge/Twig/Command/DebugCommand.php | 60 +-- .../Bridge/Twig/Extension/CodeExtension.php | 32 +- .../Twig/Extension/TranslationExtension.php | 24 +- .../Twig/Tests/Command/DebugCommandTest.php | 84 ++-- .../AbstractBootstrap3LayoutTest.php | 8 +- .../AbstractBootstrap4LayoutTest.php | 8 +- .../Tests/Extension/DumpExtensionTest.php | 48 +-- .../Extension/Fixtures/StubTranslator.php | 2 +- .../Extension/FormExtensionDivLayoutTest.php | 98 ++--- .../FormExtensionTableLayoutTest.php | 42 +- .../Tests/Translation/TwigExtractorTest.php | 74 ++-- .../TokenParser/TransChoiceTokenParser.php | 6 +- .../Twig/TokenParser/TransTokenParser.php | 6 +- .../FrameworkBundle/Command/AboutCommand.php | 54 +-- .../Command/ContainerDebugCommand.php | 30 +- .../Command/DebugAutowiringCommand.php | 10 +- .../Command/TranslationDebugCommand.php | 30 +- .../Command/TranslationUpdateCommand.php | 20 +- .../Console/Descriptor/TextDescriptor.php | 152 +++---- .../Controller/ControllerTrait.php | 2 +- .../DependencyInjection/Configuration.php | 128 +++--- .../FrameworkExtension.php | 210 +++++----- .../Routing/DelegatingLoader.php | 2 +- .../Templating/Helper/StopwatchHelper.php | 2 +- .../Templating/Helper/TranslatorHelper.php | 4 +- .../CacheWarmer/SerializerCacheWarmerTest.php | 6 +- .../Command/TranslationDebugCommandTest.php | 56 +-- .../Command/TranslationUpdateCommandTest.php | 4 +- .../Descriptor/AbstractDescriptorTest.php | 12 +- .../Console/Descriptor/ObjectsProvider.php | 4 +- .../Compiler/CachePoolClearerPassTest.php | 14 +- .../Compiler/CachePoolPassTest.php | 4 +- .../DataCollectorTranslatorPassTest.php | 22 +- .../DependencyInjection/ConfigurationTest.php | 246 ++++++------ ...messenger_amqp_transport_no_serializer.php | 12 +- .../Fixtures/php/messenger_multiple_buses.php | 30 +- .../Fixtures/php/messenger_routing.php | 24 +- .../Fixtures/php/messenger_transport.php | 18 +- .../php/messenger_transport_no_serializer.php | 16 +- .../Fixtures/php/messenger_transports.php | 18 +- .../Fixtures/php/serializer_disabled.php | 8 +- .../php/session_cookie_secure_auto.php | 8 +- .../FrameworkExtensionTest.php | 296 +++++++------- .../Functional/ContainerDebugCommandTest.php | 12 +- .../Functional/DebugAutowiringCommandTest.php | 4 +- .../Tests/Routing/DelegatingLoaderTest.php | 14 +- .../Helper/Fixtures/StubTranslator.php | 2 +- .../Helper/FormHelperDivLayoutTest.php | 56 +-- .../Helper/FormHelperTableLayoutTest.php | 8 +- .../Tests/Translation/TranslatorTest.php | 18 +- .../DataCollector/SecurityDataCollector.php | 6 +- .../SecurityBundle/Debug/WrappedListener.php | 4 +- .../AddExpressionLanguageProvidersPass.php | 2 +- .../Compiler/AddSecurityVotersPass.php | 2 +- .../Security/Factory/JsonLoginLdapFactory.php | 2 +- .../Security/Factory/RememberMeFactory.php | 4 +- .../DependencyInjection/SecurityExtension.php | 92 ++--- .../EventListener/VoteListener.php | 2 +- .../SecurityDataCollectorTest.php | 192 ++++----- .../Debug/TraceableFirewallListenerTest.php | 2 +- .../Compiler/AddSecurityVotersPassTest.php | 4 +- .../AddSessionDomainConstraintPassTest.php | 26 +- .../CompleteConfigurationTest.php | 204 +++++----- .../Fixtures/php/container1.php | 128 +++--- .../Fixtures/php/simple_auth.php | 32 +- .../SecurityExtensionTest.php | 36 +- .../Tests/EventListener/VoteListenerTest.php | 6 +- .../Tests/Functional/JsonLoginLdapTest.php | 2 +- .../Functional/app/JsonLoginLdap/bundles.php | 4 +- .../Tests/Security/FirewallContextTest.php | 2 +- .../DependencyInjection/Configuration.php | 16 +- .../DependencyInjection/TwigExtension.php | 24 +- .../DependencyInjection/TwigExtensionTest.php | 124 +++--- .../Functional/NoTemplatingEntryTest.php | 12 +- .../Bundle/WebServerBundle/WebServer.php | 6 +- .../Component/Asset/Tests/UrlPackageTest.php | 80 ++-- src/Symfony/Component/BrowserKit/Client.php | 6 +- src/Symfony/Component/BrowserKit/Cookie.php | 8 +- .../Component/BrowserKit/Tests/ClientTest.php | 40 +- .../Cache/Adapter/AbstractAdapter.php | 36 +- .../Component/Cache/Adapter/ArrayAdapter.php | 2 +- .../Component/Cache/Adapter/ChainAdapter.php | 10 +- .../Component/Cache/Adapter/PdoAdapter.php | 2 +- .../Component/Cache/Adapter/ProxyAdapter.php | 2 +- .../Cache/Adapter/TagAwareAdapter.php | 2 +- src/Symfony/Component/Cache/CacheItem.php | 12 +- .../CacheCollectorPass.php | 6 +- .../CachePoolClearerPass.php | 2 +- .../DependencyInjection/CachePoolPass.php | 14 +- .../CachePoolPrunerPass.php | 2 +- src/Symfony/Component/Cache/LockRegistry.php | 10 +- .../Cache/Marshaller/DefaultMarshaller.php | 2 +- .../Component/Cache/Simple/ArrayCache.php | 4 +- .../Component/Cache/Simple/PdoCache.php | 2 +- .../Component/Cache/Simple/Psr6Cache.php | 2 +- .../Cache/Tests/Adapter/AdapterTestCase.php | 4 +- .../Cache/Tests/Adapter/ArrayAdapterTest.php | 4 +- .../Cache/Tests/Adapter/ChainAdapterTest.php | 16 +- .../Tests/Adapter/MaxIdLengthAdapterTest.php | 28 +- .../Tests/Adapter/MemcachedAdapterTest.php | 28 +- .../Tests/Adapter/PdoDbalAdapterTest.php | 4 +- .../Tests/Adapter/PhpArrayAdapterTest.php | 42 +- .../Cache/Tests/Adapter/PredisAdapterTest.php | 8 +- .../Adapter/PredisRedisClusterAdapterTest.php | 2 +- .../Cache/Tests/Adapter/RedisAdapterTest.php | 2 +- .../Tests/Adapter/RedisClusterAdapterTest.php | 12 +- .../Tests/Adapter/TagAwareAdapterTest.php | 2 +- .../Component/Cache/Tests/CacheItemTest.php | 40 +- .../CacheCollectorPassTest.php | 8 +- .../CachePoolClearerPassTest.php | 14 +- .../DependencyInjection/CachePoolPassTest.php | 10 +- .../CachePoolPrunerPassTest.php | 8 +- .../Cache/Tests/Fixtures/ArrayCache.php | 6 +- .../Cache/Tests/LockRegistryTest.php | 2 +- .../Marshaller/DefaultMarshallerTest.php | 8 +- .../Cache/Tests/Simple/PhpArrayCacheTest.php | 42 +- .../Component/Cache/Traits/AbstractTrait.php | 34 +- .../Component/Cache/Traits/ApcuTrait.php | 4 +- .../Component/Cache/Traits/ArrayTrait.php | 10 +- .../Component/Cache/Traits/ContractsTrait.php | 2 +- .../Component/Cache/Traits/MemcachedTrait.php | 32 +- .../Component/Cache/Traits/PdoTrait.php | 20 +- .../Component/Cache/Traits/PhpArrayTrait.php | 10 +- .../Component/Cache/Traits/PhpFilesTrait.php | 14 +- .../Component/Cache/Traits/RedisTrait.php | 62 +-- .../Component/Config/Definition/ArrayNode.php | 2 +- .../Component/Config/Loader/FileLoader.php | 2 +- .../Config/Resource/GlobResource.php | 6 +- .../Resource/ReflectionClassResource.php | 2 +- .../Config/Tests/Definition/ArrayNodeTest.php | 4 +- .../Builder/ArrayNodeDefinitionTest.php | 66 ++-- .../Definition/Builder/TreeBuilderTest.php | 2 +- .../Tests/Resource/GlobResourceTest.php | 6 +- .../Console/Helper/ProcessHelper.php | 6 +- .../Component/Console/Helper/Table.php | 62 +-- .../Component/Console/Tester/TesterTrait.php | 2 +- .../Console/Tests/ApplicationTest.php | 268 ++++++------- .../Tests/Helper/ProcessHelperTest.php | 42 +- .../Console/Tests/Helper/TableTest.php | 36 +- .../Tests/Tester/ApplicationTesterTest.php | 4 +- .../Tests/Tester/CommandTesterTest.php | 4 +- .../Component/Debug/DebugClassLoader.php | 44 +-- src/Symfony/Component/Debug/ErrorHandler.php | 92 ++--- .../Compiler/AbstractRecursivePass.php | 2 +- .../Compiler/AnalyzeServiceReferencesPass.php | 2 +- ...xceptionOnInvalidReferenceBehaviorPass.php | 6 +- .../Compiler/InlineServiceDefinitionsPass.php | 14 +- .../Compiler/PassConfig.php | 48 +-- .../Compiler/RegisterEnvVarProcessorsPass.php | 6 +- .../Compiler/RemoveUnusedDefinitionsPass.php | 8 +- .../ReplaceAliasByActualDefinitionPass.php | 2 +- .../ResolveInstanceofConditionalsPass.php | 30 +- .../Compiler/ServiceLocatorTagPass.php | 4 +- .../DependencyInjection/Container.php | 42 +- .../DependencyInjection/ContainerBuilder.php | 72 ++-- .../DependencyInjection/Dumper/PhpDumper.php | 116 +++--- .../Loader/Configurator/Traits/LazyTrait.php | 2 +- .../Loader/XmlFileLoader.php | 46 +-- .../Loader/YamlFileLoader.php | 66 ++-- .../DependencyInjection/ServiceLocator.php | 6 +- .../AnalyzeServiceReferencesPassTest.php | 20 +- .../Tests/Compiler/AutowirePassTest.php | 10 +- ...tionOnInvalidReferenceBehaviorPassTest.php | 4 +- .../CustomExpressionLanguageFunctionTest.php | 6 +- .../InlineServiceDefinitionsPassTest.php | 40 +- .../RegisterEnvVarProcessorsPassTest.php | 32 +- .../RegisterServiceSubscribersPassTest.php | 44 +-- .../RemoveUnusedDefinitionsPassTest.php | 12 +- .../Compiler/ResolveBindingsPassTest.php | 12 +- .../ResolveInstanceofConditionalsPassTest.php | 10 +- .../Compiler/ServiceLocatorTagPassTest.php | 16 +- .../Tests/Dumper/PhpDumperTest.php | 2 +- .../Tests/EnvVarProcessorTest.php | 48 +-- .../Tests/Loader/FileLoaderTest.php | 36 +- .../Tests/Loader/PhpFileLoaderTest.php | 20 +- .../Tests/Loader/XmlFileLoaderTest.php | 12 +- .../Tests/Loader/YamlFileLoaderTest.php | 6 +- .../Tests/ServiceLocatorTest.php | 14 +- .../DomCrawler/AbstractUriElement.php | 4 +- src/Symfony/Component/Dotenv/Dotenv.php | 4 +- .../Component/Dotenv/Tests/DotenvTest.php | 2 +- .../Debug/TraceableEventDispatcher.php | 22 +- .../Filesystem/Tests/FilesystemTest.php | 18 +- .../Finder/Iterator/SortableIterator.php | 3 +- .../Component/Finder/Tests/FinderTest.php | 322 +++++++-------- .../Iterator/DateRangeFilterIteratorTest.php | 22 +- .../Iterator/DepthRangeFilterIteratorTest.php | 30 +- .../ExcludeDirectoryFilterIteratorTest.php | 22 +- .../Iterator/FileTypeFilterIteratorTest.php | 16 +- .../Tests/Iterator/RealIteratorTestCase.php | 8 +- .../Tests/Iterator/SortableIteratorTest.php | 72 ++-- .../Component/Form/AbstractExtension.php | 4 +- .../Component/Form/Command/DebugCommand.php | 2 +- .../Form/Console/Descriptor/Descriptor.php | 42 +- .../Console/Descriptor/JsonDescriptor.php | 16 +- .../Console/Descriptor/TextDescriptor.php | 40 +- .../Form/Extension/Core/Type/FormType.php | 24 +- .../Form/Extension/Core/Type/IntegerType.php | 10 +- .../Type/TransformationFailureExtension.php | 2 +- .../EventListener/CsrfValidationListener.php | 2 +- .../Csrf/Type/FormTypeCsrfExtension.php | 2 +- .../Type/DataCollectorTypeExtension.php | 2 +- .../DependencyInjectionExtension.php | 4 +- .../Type/FormTypeHttpFoundationExtension.php | 2 +- .../Type/FormTypeValidatorExtension.php | 2 +- .../Type/RepeatedTypeValidatorExtension.php | 2 +- .../Type/SubmitTypeValidatorExtension.php | 2 +- .../Type/UploadValidatorExtension.php | 2 +- src/Symfony/Component/Form/Form.php | 2 +- .../Component/Form/FormConfigBuilder.php | 12 +- .../Form/Tests/Command/DebugCommandTest.php | 36 +- .../Descriptor/AbstractDescriptorTest.php | 44 +-- .../DependencyInjection/FormPassTest.php | 242 ++++++------ .../Csrf/Type/FormTypeCsrfExtensionTest.php | 2 +- .../DependencyInjectionExtensionTest.php | 32 +- .../Tests/Fixtures/ChoiceTypeExtension.php | 2 +- .../Tests/Fixtures/FooTypeBarExtension.php | 2 +- .../Tests/Fixtures/FooTypeBazExtension.php | 2 +- .../Fixtures/LazyChoiceTypeExtension.php | 2 +- .../Form/Tests/Fixtures/TestExtension.php | 8 +- .../Component/HttpFoundation/HeaderUtils.php | 4 +- .../Component/HttpFoundation/Request.php | 104 ++--- .../HttpFoundation/RequestMatcher.php | 16 +- .../HttpFoundation/ResponseHeaderBag.php | 30 +- .../HttpFoundation/Session/SessionUtils.php | 2 +- .../Handler/AbstractSessionHandler.php | 2 +- .../HttpFoundation/Tests/HeaderUtilsTest.php | 32 +- .../Tests/RequestMatcherTest.php | 4 +- .../Tests/ResponseHeaderBagTest.php | 66 ++-- .../Session/Attribute/AttributeBagTest.php | 48 +-- .../Handler/Fixtures/with_samesite.php | 4 +- .../Fixtures/with_samesite_and_migration.php | 4 +- .../CacheWarmer/CacheWarmerAggregate.php | 8 +- .../DataCollector/DumpDataCollector.php | 22 +- .../DataCollector/RequestDataCollector.php | 44 +-- .../AbstractTestSessionListener.php | 4 +- .../EventListener/ExceptionListener.php | 20 +- .../EventListener/SessionListener.php | 2 +- .../EventListener/TestSessionListener.php | 2 +- ...ntrollerDoesNotReturnResponseException.php | 20 +- src/Symfony/Component/HttpKernel/Kernel.php | 52 +-- ...sterControllerArgumentLocatorsPassTest.php | 86 ++-- .../Tests/Fragment/FragmentHandlerTest.php | 6 +- .../HttpKernel/Tests/HttpCache/EsiTest.php | 4 +- .../HttpKernel/Tests/HttpCache/SsiTest.php | 4 +- .../Data/Generator/LanguageDataGenerator.php | 22 +- .../Intl/Data/Util/LocaleScanner.php | 2 +- .../Tests/Data/Util/LocaleScannerTest.php | 6 +- .../Intl/Tests/Locale/LocaleTest.php | 8 +- .../Ldap/Adapter/ExtLdap/Connection.php | 4 +- .../Ldap/Adapter/ExtLdap/EntryManager.php | 2 +- .../Ldap/Adapter/ExtLdap/UpdateOperation.php | 8 +- .../Tests/Adapter/ExtLdap/LdapManagerTest.php | 44 +-- src/Symfony/Component/Lock/Lock.php | 14 +- src/Symfony/Component/Lock/Store/PdoStore.php | 12 +- .../Component/Lock/Store/RedisStore.php | 12 +- .../Component/Lock/Store/ZookeeperStore.php | 4 +- .../Tests/Store/BlockingStoreTestTrait.php | 8 +- .../Lock/Tests/Store/PdoDbalStoreTest.php | 4 +- .../Lock/Tests/Store/ZookeeperStoreTest.php | 2 +- .../Command/ConsumeMessagesCommand.php | 8 +- .../DataCollector/MessengerDataCollector.php | 22 +- .../DependencyInjection/MessengerPass.php | 34 +- src/Symfony/Component/Messenger/Envelope.php | 4 +- .../Messenger/Handler/HandlersLocator.php | 8 +- .../Middleware/LoggingMiddleware.php | 4 +- .../Command/ConsumeMessagesCommandTest.php | 4 +- .../DependencyInjection/MessengerPassTest.php | 178 ++++----- .../Messenger/Tests/EnvelopeTest.php | 2 +- .../Tests/Handler/HandlersLocatorTest.php | 10 +- .../Messenger/Tests/MessageBusTest.php | 14 +- .../Middleware/ActivationMiddlewareTest.php | 2 +- .../HandleMessageMiddlewareTest.php | 48 +-- .../Middleware/SendMessageMiddlewareTest.php | 24 +- .../Middleware/TraceableMiddlewareTest.php | 12 +- .../Middleware/ValidationMiddlewareTest.php | 2 +- .../Tests/Stamp/HandledStampTest.php | 22 +- .../Tests/Stamp/SerializerStampTest.php | 2 +- .../Tests/Stamp/ValidationStampTest.php | 8 +- .../Tests/TraceableMessageBusTest.php | 30 +- .../Transport/AmqpExt/AmqpSenderTest.php | 2 +- .../AmqpExt/AmqpTransportFactoryTest.php | 10 +- .../Transport/AmqpExt/AmqpTransportTest.php | 4 +- .../Transport/Sender/SendersLocatorTest.php | 18 +- .../Serialization/SerializerTest.php | 14 +- .../Messenger/TraceableMessageBus.php | 8 +- .../Transport/AmqpExt/AmqpReceiver.php | 4 +- .../Transport/Sender/SendersLocator.php | 6 +- .../Transport/Serialization/Serializer.php | 18 +- .../OptionsResolver/OptionsResolver.php | 66 ++-- .../Tests/OptionsResolverTest.php | 296 +++++++------- src/Symfony/Component/Process/Process.php | 2 +- .../Tests/KillableProcessWithOutput.php | 4 +- .../Tests/ProcessFailedExceptionTest.php | 6 +- .../Component/Process/Tests/ProcessTest.php | 198 +++++----- .../Extractor/ReflectionExtractor.php | 2 +- .../PropertyInfoCacheExtractor.php | 30 +- .../PropertyInfo/PropertyInfoExtractor.php | 30 +- ...ropertyInitializableExtractorInterface.php | 2 +- .../AbstractPropertyInfoExtractorTest.php | 16 +- .../PropertyInfoPassTest.php | 36 +- .../Tests/Extractor/PhpDocExtractorTest.php | 230 +++++------ .../Extractor/ReflectionExtractorTest.php | 16 +- .../Tests/Fixtures/DummyExtractor.php | 2 +- .../Tests/Fixtures/NullExtractor.php | 2 +- .../Matcher/Dumper/PhpMatcherDumper.php | 50 +-- .../Matcher/Dumper/PhpMatcherTrait.php | 22 +- .../Dumper/PhpGeneratorDumperTest.php | 62 +-- .../Tests/Loader/YamlFileLoaderTest.php | 2 +- .../TraceableAccessDecisionManager.php | 16 +- .../Authorization/Voter/ExpressionVoter.php | 4 +- .../Authorization/ExpressionLanguageTest.php | 74 ++-- .../TraceableAccessDecisionManagerTest.php | 234 +++++------ .../Voter/TraceableVoterTest.php | 6 +- .../Security/Core/User/LdapUserProvider.php | 2 +- .../Security/Http/Tests/FirewallTest.php | 12 +- ...istentTokenBasedRememberMeServicesTest.php | 44 +-- .../TokenBasedRememberMeServicesTest.php | 34 +- .../Serializer/Encoder/CsvEncoder.php | 40 +- .../Serializer/Encoder/JsonDecode.php | 12 +- .../Serializer/Encoder/JsonEncode.php | 8 +- .../Serializer/Encoder/JsonEncoder.php | 2 +- .../Serializer/Encoder/XmlEncoder.php | 40 +- .../Serializer/Mapping/AttributeMetadata.php | 4 +- .../AdvancedNameConverterInterface.php | 4 +- .../MetadataAwareNameConverter.php | 18 +- .../Normalizer/AbstractNormalizer.php | 12 +- .../Normalizer/AbstractObjectNormalizer.php | 34 +- .../ConstraintViolationListNormalizer.php | 18 +- .../Normalizer/DateIntervalNormalizer.php | 8 +- .../Normalizer/DateTimeNormalizer.php | 8 +- .../Normalizer/ObjectNormalizer.php | 2 +- .../Component/Serializer/Serializer.php | 42 +- .../Tests/Annotation/SerializedNameTest.php | 14 +- .../Tests/Encoder/CsvEncoderTest.php | 168 ++++---- .../Tests/Encoder/XmlEncoderTest.php | 272 ++++++------- .../MetadataAwareNameConverterTest.php | 20 +- .../Normalizer/AbstractNormalizerTest.php | 32 +- .../AbstractObjectNormalizerTest.php | 4 +- .../Normalizer/DateIntervalNormalizerTest.php | 4 +- .../Normalizer/DateTimeNormalizerTest.php | 6 +- .../Normalizer/GetSetMethodNormalizerTest.php | 186 ++++----- .../JsonSerializableNormalizerTest.php | 4 +- .../Tests/Normalizer/ObjectNormalizerTest.php | 372 +++++++++--------- .../Normalizer/PropertyNormalizerTest.php | 150 +++---- .../Serializer/Tests/SerializerTest.php | 8 +- .../Translation/Catalogue/MergeOperation.php | 14 +- .../Translation/Catalogue/TargetOperation.php | 14 +- .../Translation/Command/XliffLintCommand.php | 22 +- .../Translation/DataCollectorTranslator.php | 18 +- .../Translation/Dumper/FileDumper.php | 2 +- .../Translation/Formatter/IntlFormatter.php | 6 +- .../Formatter/IntlFormatterInterface.php | 2 +- .../Formatter/MessageFormatter.php | 10 +- .../Translation/IdentityTranslator.php | 4 +- .../Translation/Loader/XliffFileLoader.php | 16 +- .../Translation/LoggingTranslator.php | 12 +- .../Translation/MessageCatalogue.php | 22 +- .../Tests/Catalogue/MergeOperationTest.php | 12 +- .../Tests/Catalogue/TargetOperationTest.php | 12 +- .../Tests/Command/XliffLintCommandTest.php | 24 +- .../Tests/DataCollectorTranslatorTest.php | 54 +-- .../Tests/Dumper/FileDumperTest.php | 8 +- .../Tests/Formatter/IntlFormatterTest.php | 28 +- .../Tests/LoggingTranslatorTest.php | 8 +- .../Tests/MessageCatalogueTest.php | 78 ++-- .../Translation/Tests/TranslatorCacheTest.php | 60 +-- .../Translation/Tests/TranslatorTest.php | 264 ++++++------- .../Component/Translation/Translator.php | 24 +- .../Component/Translation/Util/XliffUtils.php | 8 +- .../Validator/Constraints/DivisibleBy.php | 4 +- .../AddValidatorInitializersPass.php | 8 +- .../Tests/Constraints/BicValidatorTest.php | 60 +-- .../Constraints/DivisibleByValidatorTest.php | 42 +- .../AddValidatorInitializersPassTest.php | 4 +- .../Validator/Util/LegacyTranslatorProxy.php | 6 +- .../Component/Validator/ValidatorBuilder.php | 12 +- .../Violation/ConstraintViolationBuilder.php | 2 +- .../Component/VarDumper/Caster/ClassStub.php | 2 +- .../Component/VarDumper/Caster/IntlCaster.php | 44 +-- .../VarDumper/Caster/MemcachedCaster.php | 10 +- .../VarDumper/Caster/RedisCaster.php | 42 +- .../VarDumper/Caster/ReflectionCaster.php | 2 +- .../VarDumper/Cloner/AbstractCloner.php | 222 +++++------ .../Component/VarDumper/Dumper/HtmlDumper.php | 26 +- .../VarDumper/Tests/Caster/StubCasterTest.php | 6 +- src/Symfony/Component/VarDumper/VarDumper.php | 2 +- .../Component/VarExporter/Instantiator.php | 12 +- .../VarExporter/Internal/Exporter.php | 36 +- .../VarExporter/Internal/Hydrator.php | 10 +- .../VarExporter/Internal/Registry.php | 22 +- .../VarExporter/Tests/InstantiatorTest.php | 26 +- .../VarExporter/Tests/VarExporterTest.php | 94 ++--- .../Component/VarExporter/VarExporter.php | 14 +- .../Workflow/Dumper/GraphvizDumper.php | 42 +- .../Component/Yaml/Command/LintCommand.php | 10 +- src/Symfony/Component/Yaml/Parser.php | 2 +- .../Yaml/Tests/Command/LintCommandTest.php | 2 +- src/Symfony/Contracts/Cache/CacheTrait.php | 2 +- .../Contracts/Service/ServiceLocatorTrait.php | 2 +- .../Service/ServiceSubscriberTrait.php | 4 +- .../Contracts/Tests/Cache/CacheTraitTest.php | 12 +- .../Tests/Service/ServiceLocatorTest.php | 20 +- .../Service/ServiceSubscriberTraitTest.php | 4 +- .../Tests/Translation/TranslatorTest.php | 190 ++++----- .../Translation/TranslatorInterface.php | 2 +- .../Contracts/Translation/TranslatorTrait.php | 6 +- 416 files changed, 6375 insertions(+), 6374 deletions(-) diff --git a/.php_cs.dist b/.php_cs.dist index 3d9248193b..fd6832920b 100644 --- a/.php_cs.dist +++ b/.php_cs.dist @@ -5,26 +5,26 @@ if (!file_exists(__DIR__.'/src')) { } return PhpCsFixer\Config::create() - ->setRules(array( + ->setRules([ '@Symfony' => true, '@Symfony:risky' => true, '@PHPUnit48Migration:risky' => true, 'php_unit_no_expectation_annotation' => false, // part of `PHPUnitXYMigration:risky` ruleset, to be enabled when PHPUnit 4.x support will be dropped, as we don't want to rewrite exceptions handling twice - 'array_syntax' => array('syntax' => 'short'), + 'array_syntax' => ['syntax' => 'short'], 'fopen_flags' => false, 'ordered_imports' => true, 'protected_to_private' => false, // Part of @Symfony:risky in PHP-CS-Fixer 2.13.0. To be removed from the config file once upgrading - 'native_function_invocation' => array('include' => array('@compiler_optimized'), 'scope' => 'namespaced'), + 'native_function_invocation' => ['include' => ['@compiler_optimized'], 'scope' => 'namespaced'], // Part of future @Symfony ruleset in PHP-CS-Fixer To be removed from the config file once upgrading - 'phpdoc_types_order' => array('null_adjustment' => 'always_last', 'sort_algorithm' => 'none'), - )) + 'phpdoc_types_order' => ['null_adjustment' => 'always_last', 'sort_algorithm' => 'none'], + ]) ->setRiskyAllowed(true) ->setFinder( PhpCsFixer\Finder::create() ->in(__DIR__.'/src') - ->append(array(__FILE__)) - ->exclude(array( + ->append([__FILE__]) + ->exclude([ 'Symfony/Bridge/ProxyManager/Tests/LazyProxy/PhpDumper/Fixtures', // directories containing files with content that is autogenerated by `var_export`, which breaks CS in output code 'Symfony/Component/DependencyInjection/Tests/Fixtures', @@ -40,7 +40,7 @@ return PhpCsFixer\Config::create() 'Symfony/Bundle/FrameworkBundle/Resources/views/Form', // explicit trigger_error tests 'Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/', - )) + ]) // Support for older PHPunit version ->notPath('Symfony/Bridge/PhpUnit/SymfonyTestsListener.php') // file content autogenerated by `var_export` diff --git a/src/Symfony/Bridge/Doctrine/DependencyInjection/CompilerPass/RegisterEventListenersAndSubscribersPass.php b/src/Symfony/Bridge/Doctrine/DependencyInjection/CompilerPass/RegisterEventListenersAndSubscribersPass.php index 46904ebbf4..deaa64e7c9 100644 --- a/src/Symfony/Bridge/Doctrine/DependencyInjection/CompilerPass/RegisterEventListenersAndSubscribersPass.php +++ b/src/Symfony/Bridge/Doctrine/DependencyInjection/CompilerPass/RegisterEventListenersAndSubscribersPass.php @@ -66,13 +66,13 @@ class RegisterEventListenersAndSubscribersPass implements CompilerPassInterface foreach ($taggedSubscribers as $taggedSubscriber) { list($id, $tag) = $taggedSubscriber; - $connections = isset($tag['connection']) ? array($tag['connection']) : array_keys($this->connections); + $connections = isset($tag['connection']) ? [$tag['connection']] : array_keys($this->connections); foreach ($connections as $con) { if (!isset($this->connections[$con])) { throw new RuntimeException(sprintf('The Doctrine connection "%s" referenced in service "%s" does not exist. Available connections names: %s', $con, $id, implode(', ', array_keys($this->connections)))); } - $this->getEventManagerDef($container, $con)->addMethodCall('addEventSubscriber', array(new Reference($id))); + $this->getEventManagerDef($container, $con)->addMethodCall('addEventSubscriber', [new Reference($id)]); } } } @@ -81,7 +81,7 @@ class RegisterEventListenersAndSubscribersPass implements CompilerPassInterface { $listenerTag = $this->tagPrefix.'.event_listener'; $taggedListeners = $this->findAndSortTags($listenerTag, $container); - $listenerRefs = array(); + $listenerRefs = []; foreach ($taggedListeners as $taggedListener) { list($id, $tag) = $taggedListener; @@ -89,7 +89,7 @@ class RegisterEventListenersAndSubscribersPass implements CompilerPassInterface throw new InvalidArgumentException(sprintf('Doctrine event listener "%s" must specify the "event" attribute.', $id)); } - $connections = isset($tag['connection']) ? array($tag['connection']) : array_keys($this->connections); + $connections = isset($tag['connection']) ? [$tag['connection']] : array_keys($this->connections); foreach ($connections as $con) { if (!isset($this->connections[$con])) { throw new RuntimeException(sprintf('The Doctrine connection "%s" referenced in service "%s" does not exist. Available connections names: %s', $con, $id, implode(', ', array_keys($this->connections)))); @@ -97,7 +97,7 @@ class RegisterEventListenersAndSubscribersPass implements CompilerPassInterface $listenerRefs[$con][$id] = new Reference($id); // we add one call per event per service so we have the correct order - $this->getEventManagerDef($container, $con)->addMethodCall('addEventListener', array(array($tag['event']), $id)); + $this->getEventManagerDef($container, $con)->addMethodCall('addEventListener', [[$tag['event']], $id]); } } @@ -135,12 +135,12 @@ class RegisterEventListenersAndSubscribersPass implements CompilerPassInterface */ private function findAndSortTags($tagName, ContainerBuilder $container) { - $sortedTags = array(); + $sortedTags = []; foreach ($container->findTaggedServiceIds($tagName, true) as $serviceId => $tags) { foreach ($tags as $attributes) { $priority = isset($attributes['priority']) ? $attributes['priority'] : 0; - $sortedTags[$priority][] = array($serviceId, $attributes); + $sortedTags[$priority][] = [$serviceId, $attributes]; } } diff --git a/src/Symfony/Bridge/Doctrine/Form/DoctrineOrmTypeGuesser.php b/src/Symfony/Bridge/Doctrine/Form/DoctrineOrmTypeGuesser.php index e85145d1ea..d9f7f391d2 100644 --- a/src/Symfony/Bridge/Doctrine/Form/DoctrineOrmTypeGuesser.php +++ b/src/Symfony/Bridge/Doctrine/Form/DoctrineOrmTypeGuesser.php @@ -26,7 +26,7 @@ class DoctrineOrmTypeGuesser implements FormTypeGuesserInterface { protected $registry; - private $cache = array(); + private $cache = []; public function __construct(ManagerRegistry $registry) { @@ -39,7 +39,7 @@ class DoctrineOrmTypeGuesser implements FormTypeGuesserInterface public function guessType($class, $property) { if (!$ret = $this->getMetadata($class)) { - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\TextType', array(), Guess::LOW_CONFIDENCE); + return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\TextType', [], Guess::LOW_CONFIDENCE); } list($metadata, $name) = $ret; @@ -48,45 +48,45 @@ class DoctrineOrmTypeGuesser implements FormTypeGuesserInterface $multiple = $metadata->isCollectionValuedAssociation($property); $mapping = $metadata->getAssociationMapping($property); - return new TypeGuess('Symfony\Bridge\Doctrine\Form\Type\EntityType', array('em' => $name, 'class' => $mapping['targetEntity'], 'multiple' => $multiple), Guess::HIGH_CONFIDENCE); + return new TypeGuess('Symfony\Bridge\Doctrine\Form\Type\EntityType', ['em' => $name, 'class' => $mapping['targetEntity'], 'multiple' => $multiple], Guess::HIGH_CONFIDENCE); } switch ($metadata->getTypeOfField($property)) { case Type::TARRAY: case Type::SIMPLE_ARRAY: - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\CollectionType', array(), Guess::MEDIUM_CONFIDENCE); + return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\CollectionType', [], Guess::MEDIUM_CONFIDENCE); case Type::BOOLEAN: - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\CheckboxType', array(), Guess::HIGH_CONFIDENCE); + return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\CheckboxType', [], Guess::HIGH_CONFIDENCE); case Type::DATETIME: case Type::DATETIMETZ: case 'vardatetime': - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\DateTimeType', array(), Guess::HIGH_CONFIDENCE); + return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\DateTimeType', [], Guess::HIGH_CONFIDENCE); case 'datetime_immutable': case 'datetimetz_immutable': - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\DateTimeType', array('input' => 'datetime_immutable'), Guess::HIGH_CONFIDENCE); + return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\DateTimeType', ['input' => 'datetime_immutable'], Guess::HIGH_CONFIDENCE); case 'dateinterval': - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\DateIntervalType', array(), Guess::HIGH_CONFIDENCE); + return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\DateIntervalType', [], Guess::HIGH_CONFIDENCE); case Type::DATE: - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\DateType', array(), Guess::HIGH_CONFIDENCE); + return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\DateType', [], Guess::HIGH_CONFIDENCE); case 'date_immutable': - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\DateType', array('input' => 'datetime_immutable'), Guess::HIGH_CONFIDENCE); + return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\DateType', ['input' => 'datetime_immutable'], Guess::HIGH_CONFIDENCE); case Type::TIME: - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\TimeType', array(), Guess::HIGH_CONFIDENCE); + return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\TimeType', [], Guess::HIGH_CONFIDENCE); case 'time_immutable': - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\TimeType', array('input' => 'datetime_immutable'), Guess::HIGH_CONFIDENCE); + return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\TimeType', ['input' => 'datetime_immutable'], Guess::HIGH_CONFIDENCE); case Type::DECIMAL: case Type::FLOAT: - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\NumberType', array(), Guess::MEDIUM_CONFIDENCE); + return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\NumberType', [], Guess::MEDIUM_CONFIDENCE); case Type::INTEGER: case Type::BIGINT: case Type::SMALLINT: - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\IntegerType', array(), Guess::MEDIUM_CONFIDENCE); + return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\IntegerType', [], Guess::MEDIUM_CONFIDENCE); case Type::STRING: - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\TextType', array(), Guess::MEDIUM_CONFIDENCE); + return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\TextType', [], Guess::MEDIUM_CONFIDENCE); case Type::TEXT: - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\TextareaType', array(), Guess::MEDIUM_CONFIDENCE); + return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\TextareaType', [], Guess::MEDIUM_CONFIDENCE); default: - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\TextType', array(), Guess::LOW_CONFIDENCE); + return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\TextType', [], Guess::LOW_CONFIDENCE); } } @@ -141,7 +141,7 @@ class DoctrineOrmTypeGuesser implements FormTypeGuesserInterface return new ValueGuess($mapping['length'], Guess::HIGH_CONFIDENCE); } - if (\in_array($ret[0]->getTypeOfField($property), array(Type::DECIMAL, Type::FLOAT))) { + if (\in_array($ret[0]->getTypeOfField($property), [Type::DECIMAL, Type::FLOAT])) { return new ValueGuess(null, Guess::MEDIUM_CONFIDENCE); } } @@ -154,7 +154,7 @@ class DoctrineOrmTypeGuesser implements FormTypeGuesserInterface { $ret = $this->getMetadata($class); if ($ret && isset($ret[0]->fieldMappings[$property]) && !$ret[0]->hasAssociation($property)) { - if (\in_array($ret[0]->getTypeOfField($property), array(Type::DECIMAL, Type::FLOAT))) { + if (\in_array($ret[0]->getTypeOfField($property), [Type::DECIMAL, Type::FLOAT])) { return new ValueGuess(null, Guess::MEDIUM_CONFIDENCE); } } @@ -172,7 +172,7 @@ class DoctrineOrmTypeGuesser implements FormTypeGuesserInterface $this->cache[$class] = null; foreach ($this->registry->getManagers() as $name => $em) { try { - return $this->cache[$class] = array($em->getClassMetadata($class), $name); + return $this->cache[$class] = [$em->getClassMetadata($class), $name]; } catch (MappingException $e) { // not an entity or mapped super class } catch (LegacyMappingException $e) { diff --git a/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/CompilerPass/RegisterEventListenersAndSubscribersPassTest.php b/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/CompilerPass/RegisterEventListenersAndSubscribersPassTest.php index dfdfecc094..ca75437b76 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/CompilerPass/RegisterEventListenersAndSubscribersPassTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/CompilerPass/RegisterEventListenersAndSubscribersPassTest.php @@ -46,7 +46,7 @@ class RegisterEventListenersAndSubscribersPassTest extends TestCase $abstractDefinition = new Definition('stdClass'); $abstractDefinition->setAbstract(true); - $abstractDefinition->addTag('doctrine.event_listener', array('event' => 'test')); + $abstractDefinition->addTag('doctrine.event_listener', ['event' => 'test']); $container->setDefinition('a', $abstractDefinition); @@ -60,30 +60,30 @@ class RegisterEventListenersAndSubscribersPassTest extends TestCase $container ->register('a', 'stdClass') ->setPublic(false) - ->addTag('doctrine.event_listener', array( + ->addTag('doctrine.event_listener', [ 'event' => 'bar', - )) - ->addTag('doctrine.event_listener', array( + ]) + ->addTag('doctrine.event_listener', [ 'event' => 'foo', 'priority' => -5, - )) - ->addTag('doctrine.event_listener', array( + ]) + ->addTag('doctrine.event_listener', [ 'event' => 'foo_bar', 'priority' => 3, - )) + ]) ; $container ->register('b', 'stdClass') - ->addTag('doctrine.event_listener', array( + ->addTag('doctrine.event_listener', [ 'event' => 'foo', - )) + ]) ; $container ->register('c', 'stdClass') - ->addTag('doctrine.event_listener', array( + ->addTag('doctrine.event_listener', [ 'event' => 'foo_bar', 'priority' => 4, - )) + ]) ; $this->process($container); @@ -91,24 +91,24 @@ class RegisterEventListenersAndSubscribersPassTest extends TestCase $methodCalls = $eventManagerDef->getMethodCalls(); $this->assertEquals( - array( - array('addEventListener', array(array('foo_bar'), 'c')), - array('addEventListener', array(array('foo_bar'), 'a')), - array('addEventListener', array(array('bar'), 'a')), - array('addEventListener', array(array('foo'), 'b')), - array('addEventListener', array(array('foo'), 'a')), - ), + [ + ['addEventListener', [['foo_bar'], 'c']], + ['addEventListener', [['foo_bar'], 'a']], + ['addEventListener', [['bar'], 'a']], + ['addEventListener', [['foo'], 'b']], + ['addEventListener', [['foo'], 'a']], + ], $methodCalls ); $serviceLocatorDef = $container->getDefinition((string) $eventManagerDef->getArgument(0)); $this->assertSame(ServiceLocator::class, $serviceLocatorDef->getClass()); $this->assertEquals( - array( + [ 'c' => new ServiceClosureArgument(new Reference('c')), 'a' => new ServiceClosureArgument(new Reference('a')), 'b' => new ServiceClosureArgument(new Reference('b')), - ), + ], $serviceLocatorDef->getArgument(0) ); } @@ -119,25 +119,25 @@ class RegisterEventListenersAndSubscribersPassTest extends TestCase $container ->register('a', 'stdClass') - ->addTag('doctrine.event_listener', array( + ->addTag('doctrine.event_listener', [ 'event' => 'onFlush', - )) + ]) ; $container ->register('b', 'stdClass') - ->addTag('doctrine.event_listener', array( + ->addTag('doctrine.event_listener', [ 'event' => 'onFlush', 'connection' => 'default', - )) + ]) ; $container ->register('c', 'stdClass') - ->addTag('doctrine.event_listener', array( + ->addTag('doctrine.event_listener', [ 'event' => 'onFlush', 'connection' => 'second', - )) + ]) ; $this->process($container); @@ -146,40 +146,40 @@ class RegisterEventListenersAndSubscribersPassTest extends TestCase // first connection $this->assertEquals( - array( - array('addEventListener', array(array('onFlush'), 'a')), - array('addEventListener', array(array('onFlush'), 'b')), - ), + [ + ['addEventListener', [['onFlush'], 'a']], + ['addEventListener', [['onFlush'], 'b']], + ], $eventManagerDef->getMethodCalls() ); $serviceLocatorDef = $container->getDefinition((string) $eventManagerDef->getArgument(0)); $this->assertSame(ServiceLocator::class, $serviceLocatorDef->getClass()); $this->assertEquals( - array( + [ 'a' => new ServiceClosureArgument(new Reference('a')), 'b' => new ServiceClosureArgument(new Reference('b')), - ), + ], $serviceLocatorDef->getArgument(0) ); // second connection $secondEventManagerDef = $container->getDefinition('doctrine.dbal.second_connection.event_manager'); $this->assertEquals( - array( - array('addEventListener', array(array('onFlush'), 'a')), - array('addEventListener', array(array('onFlush'), 'c')), - ), + [ + ['addEventListener', [['onFlush'], 'a']], + ['addEventListener', [['onFlush'], 'c']], + ], $secondEventManagerDef->getMethodCalls() ); $serviceLocatorDef = $container->getDefinition((string) $secondEventManagerDef->getArgument(0)); $this->assertSame(ServiceLocator::class, $serviceLocatorDef->getClass()); $this->assertEquals( - array( + [ 'a' => new ServiceClosureArgument(new Reference('a')), 'c' => new ServiceClosureArgument(new Reference('c')), - ), + ], $serviceLocatorDef->getArgument(0) ); } @@ -190,42 +190,42 @@ class RegisterEventListenersAndSubscribersPassTest extends TestCase $container ->register('a', 'stdClass') - ->addTag('doctrine.event_subscriber', array( + ->addTag('doctrine.event_subscriber', [ 'event' => 'onFlush', - )) + ]) ; $container ->register('b', 'stdClass') - ->addTag('doctrine.event_subscriber', array( + ->addTag('doctrine.event_subscriber', [ 'event' => 'onFlush', 'connection' => 'default', - )) + ]) ; $container ->register('c', 'stdClass') - ->addTag('doctrine.event_subscriber', array( + ->addTag('doctrine.event_subscriber', [ 'event' => 'onFlush', 'connection' => 'second', - )) + ]) ; $this->process($container); $this->assertEquals( - array( - array('addEventSubscriber', array(new Reference('a'))), - array('addEventSubscriber', array(new Reference('b'))), - ), + [ + ['addEventSubscriber', [new Reference('a')]], + ['addEventSubscriber', [new Reference('b')]], + ], $container->getDefinition('doctrine.dbal.default_connection.event_manager')->getMethodCalls() ); $this->assertEquals( - array( - array('addEventSubscriber', array(new Reference('a'))), - array('addEventSubscriber', array(new Reference('c'))), - ), + [ + ['addEventSubscriber', [new Reference('a')]], + ['addEventSubscriber', [new Reference('c')]], + ], $container->getDefinition('doctrine.dbal.second_connection.event_manager')->getMethodCalls() ); } @@ -240,39 +240,39 @@ class RegisterEventListenersAndSubscribersPassTest extends TestCase ; $container ->register('b', 'stdClass') - ->addTag('doctrine.event_subscriber', array( + ->addTag('doctrine.event_subscriber', [ 'priority' => 5, - )) + ]) ; $container ->register('c', 'stdClass') - ->addTag('doctrine.event_subscriber', array( + ->addTag('doctrine.event_subscriber', [ 'priority' => 10, - )) + ]) ; $container ->register('d', 'stdClass') - ->addTag('doctrine.event_subscriber', array( + ->addTag('doctrine.event_subscriber', [ 'priority' => 10, - )) + ]) ; $container ->register('e', 'stdClass') - ->addTag('doctrine.event_subscriber', array( + ->addTag('doctrine.event_subscriber', [ 'priority' => 10, - )) + ]) ; $this->process($container); $this->assertEquals( - array( - array('addEventSubscriber', array(new Reference('c'))), - array('addEventSubscriber', array(new Reference('d'))), - array('addEventSubscriber', array(new Reference('e'))), - array('addEventSubscriber', array(new Reference('b'))), - array('addEventSubscriber', array(new Reference('a'))), - ), + [ + ['addEventSubscriber', [new Reference('c')]], + ['addEventSubscriber', [new Reference('d')]], + ['addEventSubscriber', [new Reference('e')]], + ['addEventSubscriber', [new Reference('b')]], + ['addEventSubscriber', [new Reference('a')]], + ], $container->getDefinition('doctrine.dbal.default_connection.event_manager')->getMethodCalls() ); } @@ -283,9 +283,9 @@ class RegisterEventListenersAndSubscribersPassTest extends TestCase $this->process($container); - $this->assertEquals(array(), $container->getDefinition('doctrine.dbal.default_connection.event_manager')->getMethodCalls()); + $this->assertEquals([], $container->getDefinition('doctrine.dbal.default_connection.event_manager')->getMethodCalls()); - $this->assertEquals(array(), $container->getDefinition('doctrine.dbal.second_connection.event_manager')->getMethodCalls()); + $this->assertEquals([], $container->getDefinition('doctrine.dbal.second_connection.event_manager')->getMethodCalls()); } private function process(ContainerBuilder $container) @@ -298,7 +298,7 @@ class RegisterEventListenersAndSubscribersPassTest extends TestCase { $container = new ContainerBuilder(); - $connections = array('default' => 'doctrine.dbal.default_connection'); + $connections = ['default' => 'doctrine.dbal.default_connection']; $container->register('doctrine.dbal.default_connection.event_manager', 'stdClass') ->addArgument(new Reference('service_container')); diff --git a/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/DoctrineExtensionTest.php b/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/DoctrineExtensionTest.php index cc99e4f5f6..638e47ef3d 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/DoctrineExtensionTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/DoctrineExtensionTest.php @@ -32,13 +32,13 @@ class DoctrineExtensionTest extends TestCase $this->extension = $this ->getMockBuilder('Symfony\Bridge\Doctrine\DependencyInjection\AbstractDoctrineExtension') - ->setMethods(array( + ->setMethods([ 'getMappingResourceConfigDirectory', 'getObjectManagerElementName', 'getMappingObjectDefaultName', 'getMappingResourceExtension', 'load', - )) + ]) ->getMock() ; @@ -54,19 +54,19 @@ class DoctrineExtensionTest extends TestCase */ public function testFixManagersAutoMappingsWithTwoAutomappings() { - $emConfigs = array( - 'em1' => array( + $emConfigs = [ + 'em1' => [ 'auto_mapping' => true, - ), - 'em2' => array( + ], + 'em2' => [ 'auto_mapping' => true, - ), - ); + ], + ]; - $bundles = array( + $bundles = [ 'FirstBundle' => 'My\FirstBundle', 'SecondBundle' => 'My\SecondBundle', - ); + ]; $reflection = new \ReflectionClass(\get_class($this->extension)); $method = $reflection->getMethod('fixManagersAutoMappings'); @@ -77,69 +77,69 @@ class DoctrineExtensionTest extends TestCase public function getAutomappingData() { - return array( - array( - array( // no auto mapping on em1 + return [ + [ + [ // no auto mapping on em1 'auto_mapping' => false, - ), - array( // no auto mapping on em2 + ], + [ // no auto mapping on em2 'auto_mapping' => false, - ), - array(), - array(), - ), - array( - array( // no auto mapping on em1 + ], + [], + [], + ], + [ + [ // no auto mapping on em1 'auto_mapping' => false, - ), - array( // auto mapping enabled on em2 + ], + [ // auto mapping enabled on em2 'auto_mapping' => true, - ), - array(), - array( - 'mappings' => array( - 'FirstBundle' => array( + ], + [], + [ + 'mappings' => [ + 'FirstBundle' => [ 'mapping' => true, 'is_bundle' => true, - ), - 'SecondBundle' => array( + ], + 'SecondBundle' => [ 'mapping' => true, 'is_bundle' => true, - ), - ), - ), - ), - array( - array( // no auto mapping on em1, but it defines SecondBundle as own + ], + ], + ], + ], + [ + [ // no auto mapping on em1, but it defines SecondBundle as own 'auto_mapping' => false, - 'mappings' => array( - 'SecondBundle' => array( + 'mappings' => [ + 'SecondBundle' => [ 'mapping' => true, 'is_bundle' => true, - ), - ), - ), - array( // auto mapping enabled on em2 + ], + ], + ], + [ // auto mapping enabled on em2 'auto_mapping' => true, - ), - array( - 'mappings' => array( - 'SecondBundle' => array( + ], + [ + 'mappings' => [ + 'SecondBundle' => [ 'mapping' => true, 'is_bundle' => true, - ), - ), - ), - array( - 'mappings' => array( - 'FirstBundle' => array( + ], + ], + ], + [ + 'mappings' => [ + 'FirstBundle' => [ 'mapping' => true, 'is_bundle' => true, - ), - ), - ), - ), - ); + ], + ], + ], + ], + ]; } /** @@ -147,15 +147,15 @@ class DoctrineExtensionTest extends TestCase */ public function testFixManagersAutoMappings(array $originalEm1, array $originalEm2, array $expectedEm1, array $expectedEm2) { - $emConfigs = array( + $emConfigs = [ 'em1' => $originalEm1, 'em2' => $originalEm2, - ); + ]; - $bundles = array( + $bundles = [ 'FirstBundle' => 'My\FirstBundle', 'SecondBundle' => 'My\SecondBundle', - ); + ]; $reflection = new \ReflectionClass(\get_class($this->extension)); $method = $reflection->getMethod('fixManagersAutoMappings'); @@ -163,39 +163,39 @@ class DoctrineExtensionTest extends TestCase $newEmConfigs = $method->invoke($this->extension, $emConfigs, $bundles); - $this->assertEquals($newEmConfigs['em1'], array_merge(array( + $this->assertEquals($newEmConfigs['em1'], array_merge([ 'auto_mapping' => false, - ), $expectedEm1)); - $this->assertEquals($newEmConfigs['em2'], array_merge(array( + ], $expectedEm1)); + $this->assertEquals($newEmConfigs['em2'], array_merge([ 'auto_mapping' => false, - ), $expectedEm2)); + ], $expectedEm2)); } public function providerBasicDrivers() { - return array( - array('doctrine.orm.cache.apc.class', array('type' => 'apc')), - array('doctrine.orm.cache.apcu.class', array('type' => 'apcu')), - array('doctrine.orm.cache.array.class', array('type' => 'array')), - array('doctrine.orm.cache.xcache.class', array('type' => 'xcache')), - array('doctrine.orm.cache.wincache.class', array('type' => 'wincache')), - array('doctrine.orm.cache.zenddata.class', array('type' => 'zenddata')), - array('doctrine.orm.cache.redis.class', array('type' => 'redis'), array('setRedis')), - array('doctrine.orm.cache.memcached.class', array('type' => 'memcached'), array('setMemcached')), - ); + return [ + ['doctrine.orm.cache.apc.class', ['type' => 'apc']], + ['doctrine.orm.cache.apcu.class', ['type' => 'apcu']], + ['doctrine.orm.cache.array.class', ['type' => 'array']], + ['doctrine.orm.cache.xcache.class', ['type' => 'xcache']], + ['doctrine.orm.cache.wincache.class', ['type' => 'wincache']], + ['doctrine.orm.cache.zenddata.class', ['type' => 'zenddata']], + ['doctrine.orm.cache.redis.class', ['type' => 'redis'], ['setRedis']], + ['doctrine.orm.cache.memcached.class', ['type' => 'memcached'], ['setMemcached']], + ]; } /** * @dataProvider providerBasicDrivers */ - public function testLoadBasicCacheDriver(string $class, array $config, array $expectedCalls = array()) + public function testLoadBasicCacheDriver(string $class, array $config, array $expectedCalls = []) { $container = $this->createContainer(); $cacheName = 'metadata_cache'; - $objectManager = array( + $objectManager = [ 'name' => 'default', 'metadata_cache_driver' => $config, - ); + ]; $this->invokeLoadCacheDriver($objectManager, $container, $cacheName); @@ -219,13 +219,13 @@ class DoctrineExtensionTest extends TestCase $cacheName = 'metadata_cache'; $container = $this->createContainer(); $definition = new Definition('%doctrine.orm.cache.apc.class%'); - $objectManager = array( + $objectManager = [ 'name' => 'default', - 'metadata_cache_driver' => array( + 'metadata_cache_driver' => [ 'type' => 'service', 'id' => 'service_driver', - ), - ); + ], + ]; $container->setDefinition('service_driver', $definition); @@ -242,12 +242,12 @@ class DoctrineExtensionTest extends TestCase { $cacheName = 'metadata_cache'; $container = $this->createContainer(); - $objectManager = array( + $objectManager = [ 'name' => 'default', - 'metadata_cache_driver' => array( + 'metadata_cache_driver' => [ 'type' => 'unrecognized_type', - ), - ); + ], + ]; $this->invokeLoadCacheDriver($objectManager, $container, $cacheName); } @@ -258,19 +258,19 @@ class DoctrineExtensionTest extends TestCase $method->setAccessible(true); - $method->invokeArgs($this->extension, array($objectManager, $container, $cacheName)); + $method->invokeArgs($this->extension, [$objectManager, $container, $cacheName]); } /** * @return \Symfony\Component\DependencyInjection\ContainerBuilder */ - protected function createContainer(array $data = array()) + protected function createContainer(array $data = []) { - return new ContainerBuilder(new ParameterBag(array_merge(array( - 'kernel.bundles' => array('FrameworkBundle' => 'Symfony\\Bundle\\FrameworkBundle\\FrameworkBundle'), + return new ContainerBuilder(new ParameterBag(array_merge([ + 'kernel.bundles' => ['FrameworkBundle' => 'Symfony\\Bundle\\FrameworkBundle\\FrameworkBundle'], 'kernel.cache_dir' => __DIR__, 'kernel.container_class' => 'kernel', 'kernel.project_dir' => __DIR__, - ), $data))); + ], $data))); } } diff --git a/src/Symfony/Bridge/Doctrine/Tests/PropertyInfo/DoctrineExtractorTest.php b/src/Symfony/Bridge/Doctrine/Tests/PropertyInfo/DoctrineExtractorTest.php index 498c5ecbc9..ace1d447c2 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/PropertyInfo/DoctrineExtractorTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/PropertyInfo/DoctrineExtractorTest.php @@ -25,8 +25,8 @@ class DoctrineExtractorTest extends TestCase { private function createExtractor(bool $legacy = false) { - $config = Setup::createAnnotationMetadataConfiguration(array(__DIR__.\DIRECTORY_SEPARATOR.'Fixtures'), true); - $entityManager = EntityManager::create(array('driver' => 'pdo_sqlite'), $config); + $config = Setup::createAnnotationMetadataConfiguration([__DIR__.\DIRECTORY_SEPARATOR.'Fixtures'], true); + $entityManager = EntityManager::create(['driver' => 'pdo_sqlite'], $config); if (!DBALType::hasType('foo')) { DBALType::addType('foo', 'Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineFooType'); @@ -49,7 +49,7 @@ class DoctrineExtractorTest extends TestCase private function doTestGetProperties(bool $legacy) { $this->assertEquals( - array( + [ 'id', 'guid', 'time', @@ -67,7 +67,7 @@ class DoctrineExtractorTest extends TestCase 'bar', 'indexedBar', 'indexedFoo', - ), + ], $this->createExtractor($legacy)->getProperties('Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineDummy') ); } @@ -89,10 +89,10 @@ class DoctrineExtractorTest extends TestCase } $this->assertEquals( - array( + [ 'id', 'embedded', - ), + ], $this->createExtractor($legacy)->getProperties('Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineWithEmbedded') ); } @@ -115,7 +115,7 @@ class DoctrineExtractorTest extends TestCase private function doTestExtract(bool $legacy, $property, array $type = null) { - $this->assertEquals($type, $this->createExtractor($legacy)->getTypes('Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineDummy', $property, array())); + $this->assertEquals($type, $this->createExtractor($legacy)->getTypes('Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineDummy', $property, [])); } public function testExtractWithEmbedded() @@ -134,16 +134,16 @@ class DoctrineExtractorTest extends TestCase $this->markTestSkipped('@Embedded is not available in Doctrine ORM lower than 2.5.'); } - $expectedTypes = array(new Type( + $expectedTypes = [new Type( Type::BUILTIN_TYPE_OBJECT, false, 'Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineEmbeddable' - )); + )]; $actualTypes = $this->createExtractor($legacy)->getTypes( 'Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineWithEmbedded', 'embedded', - array() + [] ); $this->assertEquals($expectedTypes, $actualTypes); @@ -151,47 +151,47 @@ class DoctrineExtractorTest extends TestCase public function typesProvider() { - return array( - array('id', array(new Type(Type::BUILTIN_TYPE_INT))), - array('guid', array(new Type(Type::BUILTIN_TYPE_STRING))), - array('bigint', array(new Type(Type::BUILTIN_TYPE_STRING))), - array('time', array(new Type(Type::BUILTIN_TYPE_OBJECT, false, 'DateTime'))), - array('timeImmutable', array(new Type(Type::BUILTIN_TYPE_OBJECT, false, 'DateTimeImmutable'))), - array('dateInterval', array(new Type(Type::BUILTIN_TYPE_OBJECT, false, 'DateInterval'))), - array('float', array(new Type(Type::BUILTIN_TYPE_FLOAT))), - array('decimal', array(new Type(Type::BUILTIN_TYPE_STRING))), - array('bool', array(new Type(Type::BUILTIN_TYPE_BOOL))), - array('binary', array(new Type(Type::BUILTIN_TYPE_RESOURCE))), - array('json', array(new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true))), - array('foo', array(new Type(Type::BUILTIN_TYPE_OBJECT, true, 'Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineRelation'))), - array('bar', array(new Type( + return [ + ['id', [new Type(Type::BUILTIN_TYPE_INT)]], + ['guid', [new Type(Type::BUILTIN_TYPE_STRING)]], + ['bigint', [new Type(Type::BUILTIN_TYPE_STRING)]], + ['time', [new Type(Type::BUILTIN_TYPE_OBJECT, false, 'DateTime')]], + ['timeImmutable', [new Type(Type::BUILTIN_TYPE_OBJECT, false, 'DateTimeImmutable')]], + ['dateInterval', [new Type(Type::BUILTIN_TYPE_OBJECT, false, 'DateInterval')]], + ['float', [new Type(Type::BUILTIN_TYPE_FLOAT)]], + ['decimal', [new Type(Type::BUILTIN_TYPE_STRING)]], + ['bool', [new Type(Type::BUILTIN_TYPE_BOOL)]], + ['binary', [new Type(Type::BUILTIN_TYPE_RESOURCE)]], + ['json', [new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true)]], + ['foo', [new Type(Type::BUILTIN_TYPE_OBJECT, true, 'Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineRelation')]], + ['bar', [new Type( Type::BUILTIN_TYPE_OBJECT, false, 'Doctrine\Common\Collections\Collection', true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_OBJECT, false, 'Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineRelation') - ))), - array('indexedBar', array(new Type( + )]], + ['indexedBar', [new Type( Type::BUILTIN_TYPE_OBJECT, false, 'Doctrine\Common\Collections\Collection', true, new Type(Type::BUILTIN_TYPE_STRING), new Type(Type::BUILTIN_TYPE_OBJECT, false, 'Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineRelation') - ))), - array('indexedFoo', array(new Type( + )]], + ['indexedFoo', [new Type( Type::BUILTIN_TYPE_OBJECT, false, 'Doctrine\Common\Collections\Collection', true, new Type(Type::BUILTIN_TYPE_STRING), new Type(Type::BUILTIN_TYPE_OBJECT, false, 'Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineRelation') - ))), - array('simpleArray', array(new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_STRING)))), - array('customFoo', null), - array('notMapped', null), - ); + )]], + ['simpleArray', [new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_STRING))]], + ['customFoo', null], + ['notMapped', null], + ]; } public function testGetPropertiesCatchException() diff --git a/src/Symfony/Bridge/Monolog/Logger.php b/src/Symfony/Bridge/Monolog/Logger.php index 1d896f4ac4..de021426e0 100644 --- a/src/Symfony/Bridge/Monolog/Logger.php +++ b/src/Symfony/Bridge/Monolog/Logger.php @@ -36,7 +36,7 @@ class Logger extends BaseLogger implements DebugLoggerInterface, ResetInterface return $logger->getLogs(...\func_get_args()); } - return array(); + return []; } /** diff --git a/src/Symfony/Bridge/Monolog/Tests/LoggerTest.php b/src/Symfony/Bridge/Monolog/Tests/LoggerTest.php index 6ffade8073..2ee7bc7d93 100644 --- a/src/Symfony/Bridge/Monolog/Tests/LoggerTest.php +++ b/src/Symfony/Bridge/Monolog/Tests/LoggerTest.php @@ -22,16 +22,16 @@ class LoggerTest extends TestCase public function testGetLogsWithoutDebugProcessor() { $handler = new TestHandler(); - $logger = new Logger(__METHOD__, array($handler)); + $logger = new Logger(__METHOD__, [$handler]); $logger->error('error message'); - $this->assertSame(array(), $logger->getLogs()); + $this->assertSame([], $logger->getLogs()); } public function testCountErrorsWithoutDebugProcessor() { $handler = new TestHandler(); - $logger = new Logger(__METHOD__, array($handler)); + $logger = new Logger(__METHOD__, [$handler]); $logger->error('error message'); $this->assertSame(0, $logger->countErrors()); @@ -41,7 +41,7 @@ class LoggerTest extends TestCase { $handler = new TestHandler(); $processor = new DebugProcessor(); - $logger = new Logger(__METHOD__, array($handler), array($processor)); + $logger = new Logger(__METHOD__, [$handler], [$processor]); $logger->error('error message'); $this->assertCount(1, $logger->getLogs()); @@ -51,7 +51,7 @@ class LoggerTest extends TestCase { $handler = new TestHandler(); $processor = new DebugProcessor(); - $logger = new Logger(__METHOD__, array($handler), array($processor)); + $logger = new Logger(__METHOD__, [$handler], [$processor]); $logger->debug('test message'); $logger->info('test message'); @@ -69,7 +69,7 @@ class LoggerTest extends TestCase public function testGetLogsWithDebugProcessor2() { $handler = new TestHandler(); - $logger = new Logger('test', array($handler)); + $logger = new Logger('test', [$handler]); $logger->pushProcessor(new DebugProcessor()); $logger->info('test'); @@ -88,7 +88,7 @@ class LoggerTest extends TestCase $processor->expects($this->once())->method('countErrors')->with($request); $handler = new TestHandler(); - $logger = new Logger('test', array($handler)); + $logger = new Logger('test', [$handler]); $logger->pushProcessor($processor); $logger->getLogs($request); @@ -98,7 +98,7 @@ class LoggerTest extends TestCase public function testClear() { $handler = new TestHandler(); - $logger = new Logger('test', array($handler)); + $logger = new Logger('test', [$handler]); $logger->pushProcessor(new DebugProcessor()); $logger->info('test'); diff --git a/src/Symfony/Bridge/ProxyManager/Tests/LazyProxy/PhpDumper/ProxyDumperTest.php b/src/Symfony/Bridge/ProxyManager/Tests/LazyProxy/PhpDumper/ProxyDumperTest.php index b1dc1cf66a..a72891aa5d 100644 --- a/src/Symfony/Bridge/ProxyManager/Tests/LazyProxy/PhpDumper/ProxyDumperTest.php +++ b/src/Symfony/Bridge/ProxyManager/Tests/LazyProxy/PhpDumper/ProxyDumperTest.php @@ -94,18 +94,18 @@ class ProxyDumperTest extends TestCase public function getPrivatePublicDefinitions() { - return array( - array( + return [ + [ (new Definition(__CLASS__)) ->setPublic(false), 'privates', - ), - array( + ], + [ (new Definition(__CLASS__)) ->setPublic(true), 'services', - ), - ); + ], + ]; } /** @@ -125,8 +125,8 @@ class ProxyDumperTest extends TestCase $definition = new Definition($class); $definition->setLazy(true); - $definition->addTag('proxy', array('interface' => DummyInterface::class)); - $definition->addTag('proxy', array('interface' => SunnyInterface::class)); + $definition->addTag('proxy', ['interface' => DummyInterface::class]); + $definition->addTag('proxy', ['interface' => SunnyInterface::class]); $implem = "dumper->getProxyCode($definition); $factory = $this->dumper->getProxyFactoryCode($definition, 'foo', '$this->getFooService(false)'); @@ -179,12 +179,12 @@ EOPHP; */ public function getProxyCandidates() { - $definitions = array( - array(new Definition(__CLASS__), true), - array(new Definition('stdClass'), true), - array(new Definition(uniqid('foo', true)), false), - array(new Definition(), false), - ); + $definitions = [ + [new Definition(__CLASS__), true], + [new Definition('stdClass'), true], + [new Definition(uniqid('foo', true)), false], + [new Definition(), false], + ]; array_map( function ($definition) { diff --git a/src/Symfony/Bridge/Twig/Command/DebugCommand.php b/src/Symfony/Bridge/Twig/Command/DebugCommand.php index e9d9eda30e..5ff57e1cf4 100644 --- a/src/Symfony/Bridge/Twig/Command/DebugCommand.php +++ b/src/Symfony/Bridge/Twig/Command/DebugCommand.php @@ -37,7 +37,7 @@ class DebugCommand extends Command private $twigDefaultPath; private $rootDir; - public function __construct(Environment $twig, string $projectDir = null, array $bundlesMetadata = array(), string $twigDefaultPath = null, string $rootDir = null) + public function __construct(Environment $twig, string $projectDir = null, array $bundlesMetadata = [], string $twigDefaultPath = null, string $rootDir = null) { parent::__construct(); @@ -51,11 +51,11 @@ class DebugCommand extends Command protected function configure() { $this - ->setDefinition(array( + ->setDefinition([ new InputArgument('name', InputArgument::OPTIONAL, 'The template name'), new InputOption('filter', null, InputOption::VALUE_REQUIRED, 'Show details for all entries matching this filter'), new InputOption('format', null, InputOption::VALUE_REQUIRED, 'The output format (text or json)', 'text'), - )) + ]) ->setDescription('Shows a list of twig functions, filters, globals and tests') ->setHelp(<<<'EOF' The %command.name% command outputs a list of twig functions, @@ -115,11 +115,11 @@ EOF $io->listing($files); } } else { - $alternatives = array(); + $alternatives = []; if ($paths) { - $shortnames = array(); - $dirs = array(); + $shortnames = []; + $dirs = []; foreach (current($paths) as $path) { $dirs[] = $this->isAbsolutePath($path) ? $path : $this->projectDir.'/'.$path; } @@ -141,9 +141,9 @@ EOF $io->section('Configured Paths'); if ($paths) { - $io->table(array('Namespace', 'Paths'), $this->buildTableRows($paths)); + $io->table(['Namespace', 'Paths'], $this->buildTableRows($paths)); } else { - $alternatives = array(); + $alternatives = []; $namespace = $this->parseTemplateName($name)[0]; if (FilesystemLoader::MAIN_NAMESPACE === $namespace) { @@ -159,7 +159,7 @@ EOF $this->error($io, $message, $alternatives); if (!$alternatives && $paths = $this->getLoaderPaths()) { - $io->table(array('Namespace', 'Paths'), $this->buildTableRows($paths)); + $io->table(['Namespace', 'Paths'], $this->buildTableRows($paths)); } } } @@ -184,9 +184,9 @@ EOF private function displayGeneralText(SymfonyStyle $io, string $filter = null) { - $types = array('functions', 'filters', 'tests', 'globals'); + $types = ['functions', 'filters', 'tests', 'globals']; foreach ($types as $index => $type) { - $items = array(); + $items = []; foreach ($this->twig->{'get'.ucfirst($type)}() as $name => $entity) { if (!$filter || false !== strpos($name, $filter)) { $items[$name] = $name.$this->getPrettyMetadata($type, $entity); @@ -205,7 +205,7 @@ EOF if (!$filter && $paths = $this->getLoaderPaths()) { $io->section('Loader Paths'); - $io->table(array('Namespace', 'Paths'), $this->buildTableRows($paths)); + $io->table(['Namespace', 'Paths'], $this->buildTableRows($paths)); } if ($wrongBundles = $this->findWrongBundleOverrides()) { @@ -217,8 +217,8 @@ EOF private function displayGeneralJson(SymfonyStyle $io, $filter) { - $types = array('functions', 'filters', 'tests', 'globals'); - $data = array(); + $types = ['functions', 'filters', 'tests', 'globals']; + $data = []; foreach ($types as $type) { foreach ($this->twig->{'get'.ucfirst($type)}() as $name => $entity) { if (!$filter || false !== strpos($name, $filter)) { @@ -245,15 +245,15 @@ EOF { /** @var FilesystemLoader $loader */ $loader = $this->twig->getLoader(); - $loaderPaths = array(); + $loaderPaths = []; $namespaces = $loader->getNamespaces(); if (null !== $name) { $namespace = $this->parseTemplateName($name)[0]; - $namespaces = array_intersect(array($namespace), $namespaces); + $namespaces = array_intersect([$namespace], $namespaces); } foreach ($namespaces as $namespace) { - $paths = array_map(array($this, 'getRelativePath'), $loader->getPaths($namespace)); + $paths = array_map([$this, 'getRelativePath'], $loader->getPaths($namespace)); if (FilesystemLoader::MAIN_NAMESPACE === $namespace) { $namespace = '(None)'; @@ -357,8 +357,8 @@ EOF private function findWrongBundleOverrides(): array { - $alternatives = array(); - $bundleNames = array(); + $alternatives = []; + $bundleNames = []; if ($this->rootDir && $this->projectDir) { $folders = glob($this->rootDir.'/Resources/*/views', GLOB_ONLYDIR); @@ -391,7 +391,7 @@ EOF } if ($notFoundBundles = array_diff_key($bundleNames, $this->bundlesMetadata)) { - $alternatives = array(); + $alternatives = []; foreach ($notFoundBundles as $notFoundBundle => $path) { $alternatives[$path] = $this->findAlternatives($notFoundBundle, array_keys($this->bundlesMetadata)); } @@ -402,7 +402,7 @@ EOF private function buildWarningMessages(array $wrongBundles): array { - $messages = array(); + $messages = []; foreach ($wrongBundles as $path => $alternatives) { $message = sprintf('Path "%s" not matching any bundle found', $path); if ($alternatives) { @@ -421,7 +421,7 @@ EOF return $messages; } - private function error(SymfonyStyle $io, string $message, array $alternatives = array()): void + private function error(SymfonyStyle $io, string $message, array $alternatives = []): void { if ($alternatives) { if (1 === \count($alternatives)) { @@ -439,7 +439,7 @@ EOF { /** @var FilesystemLoader $loader */ $loader = $this->twig->getLoader(); - $files = array(); + $files = []; list($namespace, $shortname) = $this->parseTemplateName($name); foreach ($loader->getPaths($namespace) as $path) { @@ -470,29 +470,29 @@ EOF $namespace = substr($name, 1, $pos - 1); $shortname = substr($name, $pos + 1); - return array($namespace, $shortname); + return [$namespace, $shortname]; } - return array($default, $name); + return [$default, $name]; } private function buildTableRows(array $loaderPaths): array { - $rows = array(); + $rows = []; $firstNamespace = true; $prevHasSeparator = false; foreach ($loaderPaths as $namespace => $paths) { if (!$firstNamespace && !$prevHasSeparator && \count($paths) > 1) { - $rows[] = array('', ''); + $rows[] = ['', '']; } $firstNamespace = false; foreach ($paths as $path) { - $rows[] = array($namespace, $path.\DIRECTORY_SEPARATOR); + $rows[] = [$namespace, $path.\DIRECTORY_SEPARATOR]; $namespace = ''; } if (\count($paths) > 1) { - $rows[] = array('', ''); + $rows[] = ['', '']; $prevHasSeparator = true; } else { $prevHasSeparator = false; @@ -507,7 +507,7 @@ EOF private function findAlternatives(string $name, array $collection): array { - $alternatives = array(); + $alternatives = []; foreach ($collection as $item) { $lev = levenshtein($name, $item); if ($lev <= \strlen($name) / 3 || false !== strpos($item, $name)) { diff --git a/src/Symfony/Bridge/Twig/Extension/CodeExtension.php b/src/Symfony/Bridge/Twig/Extension/CodeExtension.php index 73d9031b90..56211fe6ec 100644 --- a/src/Symfony/Bridge/Twig/Extension/CodeExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/CodeExtension.php @@ -43,18 +43,18 @@ class CodeExtension extends AbstractExtension */ public function getFilters() { - return array( - new TwigFilter('abbr_class', array($this, 'abbrClass'), array('is_safe' => array('html'))), - new TwigFilter('abbr_method', array($this, 'abbrMethod'), array('is_safe' => array('html'))), - new TwigFilter('format_args', array($this, 'formatArgs'), array('is_safe' => array('html'))), - new TwigFilter('format_args_as_text', array($this, 'formatArgsAsText')), - new TwigFilter('file_excerpt', array($this, 'fileExcerpt'), array('is_safe' => array('html'))), - new TwigFilter('format_file', array($this, 'formatFile'), array('is_safe' => array('html'))), - new TwigFilter('format_file_from_text', array($this, 'formatFileFromText'), array('is_safe' => array('html'))), - new TwigFilter('format_log_message', array($this, 'formatLogMessage'), array('is_safe' => array('html'))), - new TwigFilter('file_link', array($this, 'getFileLink')), - new TwigFilter('file_relative', array($this, 'getFileRelative')), - ); + return [ + new TwigFilter('abbr_class', [$this, 'abbrClass'], ['is_safe' => ['html']]), + new TwigFilter('abbr_method', [$this, 'abbrMethod'], ['is_safe' => ['html']]), + new TwigFilter('format_args', [$this, 'formatArgs'], ['is_safe' => ['html']]), + new TwigFilter('format_args_as_text', [$this, 'formatArgsAsText']), + new TwigFilter('file_excerpt', [$this, 'fileExcerpt'], ['is_safe' => ['html']]), + new TwigFilter('format_file', [$this, 'formatFile'], ['is_safe' => ['html']]), + new TwigFilter('format_file_from_text', [$this, 'formatFileFromText'], ['is_safe' => ['html']]), + new TwigFilter('format_log_message', [$this, 'formatLogMessage'], ['is_safe' => ['html']]), + new TwigFilter('file_link', [$this, 'getFileLink']), + new TwigFilter('file_relative', [$this, 'getFileRelative']), + ]; } public function abbrClass($class) @@ -88,7 +88,7 @@ class CodeExtension extends AbstractExtension */ public function formatArgs($args) { - $result = array(); + $result = []; foreach ($args as $key => $item) { if ('object' === $item[0]) { $parts = explode('\\', $item[1]); @@ -147,7 +147,7 @@ class CodeExtension extends AbstractExtension }, $code); $content = explode('
', $code); - $lines = array(); + $lines = []; if (0 > $srcContext) { $srcContext = \count($content); } @@ -205,7 +205,7 @@ class CodeExtension extends AbstractExtension public function getFileLink($file, $line) { if ($fmt = $this->fileLinkFormat) { - return \is_string($fmt) ? strtr($fmt, array('%f' => $file, '%l' => $line)) : $fmt->format($file, $line); + return \is_string($fmt) ? strtr($fmt, ['%f' => $file, '%l' => $line]) : $fmt->format($file, $line); } return false; @@ -235,7 +235,7 @@ class CodeExtension extends AbstractExtension public function formatLogMessage($message, array $context) { if ($context && false !== strpos($message, '{')) { - $replacements = array(); + $replacements = []; foreach ($context as $key => $val) { if (is_scalar($val)) { $replacements['{'.$key.'}'] = $val; diff --git a/src/Symfony/Bridge/Twig/Extension/TranslationExtension.php b/src/Symfony/Bridge/Twig/Extension/TranslationExtension.php index ec5d452cef..b8a0eb6154 100644 --- a/src/Symfony/Bridge/Twig/Extension/TranslationExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/TranslationExtension.php @@ -69,10 +69,10 @@ class TranslationExtension extends AbstractExtension */ public function getFilters() { - return array( - new TwigFilter('trans', array($this, 'trans')), - new TwigFilter('transchoice', array($this, 'transchoice'), array('deprecated' => '4.2', 'alternative' => 'trans" with parameter "%count%')), - ); + return [ + new TwigFilter('trans', [$this, 'trans']), + new TwigFilter('transchoice', [$this, 'transchoice'], ['deprecated' => '4.2', 'alternative' => 'trans" with parameter "%count%']), + ]; } /** @@ -82,7 +82,7 @@ class TranslationExtension extends AbstractExtension */ public function getTokenParsers() { - return array( + return [ // {% trans %}Symfony is great!{% endtrans %} new TransTokenParser(), @@ -93,7 +93,7 @@ class TranslationExtension extends AbstractExtension // {% trans_default_domain "foobar" %} new TransDefaultDomainTokenParser(), - ); + ]; } /** @@ -101,7 +101,7 @@ class TranslationExtension extends AbstractExtension */ public function getNodeVisitors() { - return array($this->getTranslationNodeVisitor(), new TranslationDefaultDomainNodeVisitor()); + return [$this->getTranslationNodeVisitor(), new TranslationDefaultDomainNodeVisitor()]; } public function getTranslationNodeVisitor() @@ -109,7 +109,7 @@ class TranslationExtension extends AbstractExtension return $this->translationNodeVisitor ?: $this->translationNodeVisitor = new TranslationNodeVisitor(); } - public function trans($message, array $arguments = array(), $domain = null, $locale = null, $count = null) + public function trans($message, array $arguments = [], $domain = null, $locale = null, $count = null) { if (null !== $count) { $arguments['%count%'] = $count; @@ -124,16 +124,16 @@ class TranslationExtension extends AbstractExtension /** * @deprecated since Symfony 4.2, use the trans() method instead with a %count% parameter */ - public function transchoice($message, $count, array $arguments = array(), $domain = null, $locale = null) + public function transchoice($message, $count, array $arguments = [], $domain = null, $locale = null) { if (null === $this->translator) { - return $this->doTrans($message, array_merge(array('%count%' => $count), $arguments), $domain, $locale); + return $this->doTrans($message, array_merge(['%count%' => $count], $arguments), $domain, $locale); } if ($this->translator instanceof TranslatorInterface) { - return $this->translator->trans($message, array_merge(array('%count%' => $count), $arguments), $domain, $locale); + return $this->translator->trans($message, array_merge(['%count%' => $count], $arguments), $domain, $locale); } - return $this->translator->transChoice($message, $count, array_merge(array('%count%' => $count), $arguments), $domain, $locale); + return $this->translator->transChoice($message, $count, array_merge(['%count%' => $count], $arguments), $domain, $locale); } /** diff --git a/src/Symfony/Bridge/Twig/Tests/Command/DebugCommandTest.php b/src/Symfony/Bridge/Twig/Tests/Command/DebugCommandTest.php index e648a52d84..59c8ed045c 100644 --- a/src/Symfony/Bridge/Twig/Tests/Command/DebugCommandTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Command/DebugCommandTest.php @@ -23,7 +23,7 @@ class DebugCommandTest extends TestCase public function testDebugCommand() { $tester = $this->createCommandTester(); - $ret = $tester->execute(array(), array('decorated' => false)); + $ret = $tester->execute([], ['decorated' => false]); $this->assertEquals(0, $ret, 'Returns 0 in case of success'); $this->assertContains('Functions', trim($tester->getDisplay())); @@ -32,11 +32,11 @@ class DebugCommandTest extends TestCase public function testFilterAndJsonFormatOptions() { $tester = $this->createCommandTester(); - $ret = $tester->execute(array('--filter' => 'abs', '--format' => 'json'), array('decorated' => false)); + $ret = $tester->execute(['--filter' => 'abs', '--format' => 'json'], ['decorated' => false]); - $expected = array( - 'filters' => array('abs' => array()), - ); + $expected = [ + 'filters' => ['abs' => []], + ]; $this->assertEquals(0, $ret, 'Returns 0 in case of success'); $this->assertEquals($expected, json_decode($tester->getDisplay(true), true)); @@ -44,19 +44,19 @@ class DebugCommandTest extends TestCase public function testWarningsWrongBundleOverriding() { - $bundleMetadata = array( + $bundleMetadata = [ 'TwigBundle' => 'vendor/twig-bundle/', 'WebProfilerBundle' => 'vendor/web-profiler-bundle/', - ); + ]; $defaultPath = \dirname(__DIR__).\DIRECTORY_SEPARATOR.'Fixtures'.\DIRECTORY_SEPARATOR.'templates'; - $tester = $this->createCommandTester(array(), $bundleMetadata, $defaultPath); - $ret = $tester->execute(array('--filter' => 'unknown', '--format' => 'json'), array('decorated' => false)); + $tester = $this->createCommandTester([], $bundleMetadata, $defaultPath); + $ret = $tester->execute(['--filter' => 'unknown', '--format' => 'json'], ['decorated' => false]); - $expected = array('warnings' => array( + $expected = ['warnings' => [ 'Path "templates/bundles/UnknownBundle" not matching any bundle found', 'Path "templates/bundles/WebProfileBundle" not matching any bundle found, did you mean "WebProfilerBundle"?', - )); + ]]; $this->assertEquals(0, $ret, 'Returns 0 in case of success'); $this->assertEquals($expected, json_decode($tester->getDisplay(true), true)); @@ -68,21 +68,21 @@ class DebugCommandTest extends TestCase */ public function testDeprecationForWrongBundleOverridingInLegacyPath() { - $bundleMetadata = array( + $bundleMetadata = [ 'TwigBundle' => 'vendor/twig-bundle/', 'WebProfilerBundle' => 'vendor/web-profiler-bundle/', - ); + ]; $defaultPath = \dirname(__DIR__).\DIRECTORY_SEPARATOR.'Fixtures'.\DIRECTORY_SEPARATOR.'templates'; $rootDir = \dirname(__DIR__).\DIRECTORY_SEPARATOR.'Fixtures'; - $tester = $this->createCommandTester(array(), $bundleMetadata, $defaultPath, $rootDir); - $ret = $tester->execute(array('--filter' => 'unknown', '--format' => 'json'), array('decorated' => false)); + $tester = $this->createCommandTester([], $bundleMetadata, $defaultPath, $rootDir); + $ret = $tester->execute(['--filter' => 'unknown', '--format' => 'json'], ['decorated' => false]); - $expected = array('warnings' => array( + $expected = ['warnings' => [ 'Path "Resources/BarBundle" not matching any bundle found', 'Path "templates/bundles/UnknownBundle" not matching any bundle found', 'Path "templates/bundles/WebProfileBundle" not matching any bundle found, did you mean "WebProfilerBundle"?', - )); + ]]; $this->assertEquals(0, $ret, 'Returns 0 in case of success'); $this->assertEquals($expected, json_decode($tester->getDisplay(true), true)); @@ -94,7 +94,7 @@ class DebugCommandTest extends TestCase */ public function testMalformedTemplateName() { - $this->createCommandTester()->execute(array('name' => '@foo')); + $this->createCommandTester()->execute(['name' => '@foo']); } /** @@ -103,7 +103,7 @@ class DebugCommandTest extends TestCase public function testDebugTemplateName(array $input, string $output, array $paths) { $tester = $this->createCommandTester($paths); - $ret = $tester->execute($input, array('decorated' => false)); + $ret = $tester->execute($input, ['decorated' => false]); $this->assertEquals(0, $ret, 'Returns 0 in case of success'); $this->assertStringMatchesFormat($output, $tester->getDisplay(true)); @@ -111,14 +111,14 @@ class DebugCommandTest extends TestCase public function getDebugTemplateNameTestData() { - $defaultPaths = array( + $defaultPaths = [ 'templates/' => null, 'templates/bundles/TwigBundle/' => 'Twig', 'vendors/twig-bundle/Resources/views/' => 'Twig', - ); + ]; - yield 'no template paths configured for your application' => array( - 'input' => array('name' => 'base.html.twig'), + yield 'no template paths configured for your application' => [ + 'input' => ['name' => 'base.html.twig'], 'output' => << array('vendors/twig-bundle/Resources/views/' => 'Twig'), - ); + 'paths' => ['vendors/twig-bundle/Resources/views/' => 'Twig'], + ]; - yield 'no matched template' => array( - 'input' => array('name' => '@App/foo.html.twig'), + yield 'no matched template' => [ + 'input' => ['name' => '@App/foo.html.twig'], 'output' => << $defaultPaths, - ); + ]; - yield 'matched file' => array( - 'input' => array('name' => 'base.html.twig'), + yield 'matched file' => [ + 'input' => ['name' => 'base.html.twig'], 'output' => << $defaultPaths, - ); + ]; - yield 'overridden files' => array( - 'input' => array('name' => '@Twig/error.html.twig'), + yield 'overridden files' => [ + 'input' => ['name' => '@Twig/error.html.twig'], 'output' => << $defaultPaths, - ); + ]; - yield 'template namespace alternative' => array( - 'input' => array('name' => '@Twg/error.html.twig'), + yield 'template namespace alternative' => [ + 'input' => ['name' => '@Twg/error.html.twig'], 'output' => << $defaultPaths, - ); + ]; - yield 'template name alternative' => array( - 'input' => array('name' => '@Twig/eror.html.twig'), + yield 'template name alternative' => [ + 'input' => ['name' => '@Twig/eror.html.twig'], 'output' => << $defaultPaths, - ); + ]; } - private function createCommandTester(array $paths = array(), array $bundleMetadata = array(), string $defaultPath = null, string $rootDir = null): CommandTester + private function createCommandTester(array $paths = [], array $bundleMetadata = [], string $defaultPath = null, string $rootDir = null): CommandTester { $projectDir = \dirname(__DIR__).\DIRECTORY_SEPARATOR.'Fixtures'; - $loader = new FilesystemLoader(array(), $projectDir); + $loader = new FilesystemLoader([], $projectDir); foreach ($paths as $path => $namespace) { if (null === $namespace) { $loader->addPath($path); diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/AbstractBootstrap3LayoutTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/AbstractBootstrap3LayoutTest.php index 0c6e4e6244..fd1c319a63 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/AbstractBootstrap3LayoutTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/AbstractBootstrap3LayoutTest.php @@ -122,12 +122,12 @@ abstract class AbstractBootstrap3LayoutTest extends AbstractLayoutTest public function testHelpAttr() { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, array( + $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, [ 'help' => 'Help text test!', - 'help_attr' => array( + 'help_attr' => [ 'class' => 'class-test', - ), - )); + ], + ]); $view = $form->createView(); $html = $this->renderHelp($view); diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/AbstractBootstrap4LayoutTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/AbstractBootstrap4LayoutTest.php index 6e1ee0c49c..bec4159705 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/AbstractBootstrap4LayoutTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/AbstractBootstrap4LayoutTest.php @@ -179,12 +179,12 @@ abstract class AbstractBootstrap4LayoutTest extends AbstractBootstrap3LayoutTest public function testHelpAttr() { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, array( + $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, [ 'help' => 'Help text test!', - 'help_attr' => array( + 'help_attr' => [ 'class' => 'class-test', - ), - )); + ], + ]); $view = $form->createView(); $html = $this->renderHelp($view); diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/DumpExtensionTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/DumpExtensionTest.php index 9d8420e64d..167bcfeed3 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/DumpExtensionTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/DumpExtensionTest.php @@ -27,11 +27,11 @@ class DumpExtensionTest extends TestCase public function testDumpTag($template, $debug, $expectedOutput, $expectedDumped) { $extension = new DumpExtension(new VarCloner()); - $twig = new Environment(new ArrayLoader(array('template' => $template)), array( + $twig = new Environment(new ArrayLoader(['template' => $template]), [ 'debug' => $debug, 'cache' => false, 'optimizations' => 0, - )); + ]); $twig->addExtension($extension); $dumped = null; @@ -54,11 +54,11 @@ class DumpExtensionTest extends TestCase public function getDumpTags() { - return array( - array('A{% dump %}B', true, 'AB', array()), - array('A{% set foo="bar"%}B{% dump %}C', true, 'ABC', array('foo' => 'bar')), - array('A{% dump %}B', false, 'AB', null), - ); + return [ + ['A{% dump %}B', true, 'AB', []], + ['A{% set foo="bar"%}B{% dump %}C', true, 'ABC', ['foo' => 'bar']], + ['A{% dump %}B', false, 'AB', null], + ]; } /** @@ -67,11 +67,11 @@ class DumpExtensionTest extends TestCase public function testDump($context, $args, $expectedOutput, $debug = true) { $extension = new DumpExtension(new VarCloner()); - $twig = new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock(), array( + $twig = new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock(), [ 'debug' => $debug, 'cache' => false, 'optimizations' => 0, - )); + ]); array_unshift($args, $context); array_unshift($args, $twig); @@ -88,24 +88,24 @@ class DumpExtensionTest extends TestCase public function getDumpArgs() { - return array( - array(array(), array(), '', false), - array(array(), array(), "
[]\n
\n"), - array( - array(), - array(123, 456), + return [ + [[], [], '', false], + [[], [], "
[]\n
\n"], + [ + [], + [123, 456], "
123\n
\n" ."
456\n
\n", - ), - array( - array('foo' => 'bar'), - array(), + ], + [ + ['foo' => 'bar'], + [], "
array:1 [\n"
                 ."  \"foo\" => \"bar\"\n"
                 ."]\n"
                 ."
\n", - ), - ); + ], + ]; } public function testCustomDumper() @@ -123,13 +123,13 @@ class DumpExtensionTest extends TestCase '' ); $extension = new DumpExtension(new VarCloner(), $dumper); - $twig = new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock(), array( + $twig = new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock(), [ 'debug' => true, 'cache' => false, 'optimizations' => 0, - )); + ]); - $dump = $extension->dump($twig, array(), 'foo'); + $dump = $extension->dump($twig, [], 'foo'); $dump = preg_replace('/sf-dump-\d+/', 'sf-dump', $dump); $this->assertEquals( diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/Fixtures/StubTranslator.php b/src/Symfony/Bridge/Twig/Tests/Extension/Fixtures/StubTranslator.php index bd9191161a..55c0dfa18a 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/Fixtures/StubTranslator.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/Fixtures/StubTranslator.php @@ -15,7 +15,7 @@ use Symfony\Contracts\Translation\TranslatorInterface; class StubTranslator implements TranslatorInterface { - public function trans($id, array $parameters = array(), $domain = null, $locale = null) + public function trans($id, array $parameters = [], $domain = null, $locale = null) { return '[trans]'.$id.'[/trans]'; } diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionDivLayoutTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionDivLayoutTest.php index 4a2df0289f..330b8e70fa 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionDivLayoutTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionDivLayoutTest.php @@ -35,22 +35,22 @@ class FormExtensionDivLayoutTest extends AbstractDivLayoutTest { parent::setUp(); - $loader = new StubFilesystemLoader(array( + $loader = new StubFilesystemLoader([ __DIR__.'/../../Resources/views/Form', __DIR__.'/Fixtures/templates/form', - )); + ]); - $environment = new Environment($loader, array('strict_variables' => true)); + $environment = new Environment($loader, ['strict_variables' => true]); $environment->addExtension(new TranslationExtension(new StubTranslator())); $environment->addGlobal('global', ''); // the value can be any template that exists $environment->addGlobal('dynamic_template_name', 'child_label'); $environment->addExtension(new FormExtension()); - $rendererEngine = new TwigRendererEngine(array( + $rendererEngine = new TwigRendererEngine([ 'form_div_layout.html.twig', 'custom_widgets.html.twig', - ), $environment); + ], $environment); $this->renderer = new FormRenderer($rendererEngine, $this->getMockBuilder('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface')->getMock()); $this->registerTwigRuntimeLoader($environment, $this->renderer); } @@ -62,7 +62,7 @@ class FormExtensionDivLayoutTest extends AbstractDivLayoutTest ->createView() ; - $this->setTheme($view, array('theme_use.html.twig')); + $this->setTheme($view, ['theme_use.html.twig']); $this->assertMatchesXpath( $this->renderWidget($view), @@ -77,7 +77,7 @@ class FormExtensionDivLayoutTest extends AbstractDivLayoutTest ->createView() ; - $this->setTheme($view, array('theme_extends.html.twig')); + $this->setTheme($view, ['theme_extends.html.twig']); $this->assertMatchesXpath( $this->renderWidget($view), @@ -92,7 +92,7 @@ class FormExtensionDivLayoutTest extends AbstractDivLayoutTest ->createView() ; - $this->renderer->setTheme($view, array('page_dynamic_extends.html.twig')); + $this->renderer->setTheme($view, ['page_dynamic_extends.html.twig']); $this->assertMatchesXpath( $this->renderer->searchAndRenderBlock($view, 'row'), '/div/label[text()="child"]' @@ -101,18 +101,18 @@ class FormExtensionDivLayoutTest extends AbstractDivLayoutTest public function isSelectedChoiceProvider() { - return array( - array(true, '0', '0'), - array(true, '1', '1'), - array(true, '', ''), - array(true, '1.23', '1.23'), - array(true, 'foo', 'foo'), - array(true, 'foo10', 'foo10'), - array(true, 'foo', array(1, 'foo', 'foo10')), + return [ + [true, '0', '0'], + [true, '1', '1'], + [true, '', ''], + [true, '1.23', '1.23'], + [true, 'foo', 'foo'], + [true, 'foo10', 'foo10'], + [true, 'foo', [1, 'foo', 'foo10']], - array(false, 10, array(1, 'foo', 'foo10')), - array(false, 0, array(1, 'foo', 'foo10')), - ); + [false, 10, [1, 'foo', 'foo10']], + [false, 0, [1, 'foo', 'foo10']], + ]; } /** @@ -127,10 +127,10 @@ class FormExtensionDivLayoutTest extends AbstractDivLayoutTest public function testStartTagHasNoActionAttributeWhenActionIsEmpty() { - $form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, array( + $form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, [ 'method' => 'get', 'action' => '', - )); + ]); $html = $this->renderStart($form->createView()); @@ -139,10 +139,10 @@ class FormExtensionDivLayoutTest extends AbstractDivLayoutTest public function testStartTagHasActionAttributeWhenActionIsZero() { - $form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, array( + $form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, [ 'method' => 'get', 'action' => '0', - )); + ]); $html = $this->renderStart($form->createView()); @@ -151,10 +151,10 @@ class FormExtensionDivLayoutTest extends AbstractDivLayoutTest public function isRootFormProvider() { - return array( - array(true, new FormView()), - array(false, new FormView(new FormView())), - ); + return [ + [true, new FormView()], + [false, new FormView(new FormView())], + ]; } /** @@ -167,18 +167,18 @@ class FormExtensionDivLayoutTest extends AbstractDivLayoutTest public function testMoneyWidgetInIso() { - $environment = new Environment(new StubFilesystemLoader(array( + $environment = new Environment(new StubFilesystemLoader([ __DIR__.'/../../Resources/views/Form', __DIR__.'/Fixtures/templates/form', - )), array('strict_variables' => true)); + ]), ['strict_variables' => true]); $environment->addExtension(new TranslationExtension(new StubTranslator())); $environment->addExtension(new FormExtension()); $environment->setCharset('ISO-8859-1'); - $rendererEngine = new TwigRendererEngine(array( + $rendererEngine = new TwigRendererEngine([ 'form_div_layout.html.twig', 'custom_widgets.html.twig', - ), $environment); + ], $environment); $this->renderer = new FormRenderer($rendererEngine, $this->getMockBuilder('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface')->getMock()); $this->registerTwigRuntimeLoader($environment, $this->renderer); @@ -192,12 +192,12 @@ class FormExtensionDivLayoutTest extends AbstractDivLayoutTest public function testHelpAttr() { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, array( + $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, [ 'help' => 'Help text test!', - 'help_attr' => array( + 'help_attr' => [ 'class' => 'class-test', - ), - )); + ], + ]); $view = $form->createView(); $html = $this->renderHelp($view); @@ -210,15 +210,15 @@ class FormExtensionDivLayoutTest extends AbstractDivLayoutTest ); } - protected function renderForm(FormView $view, array $vars = array()) + protected function renderForm(FormView $view, array $vars = []) { return (string) $this->renderer->renderBlock($view, 'form', $vars); } - protected function renderLabel(FormView $view, $label = null, array $vars = array()) + protected function renderLabel(FormView $view, $label = null, array $vars = []) { if (null !== $label) { - $vars += array('label' => $label); + $vars += ['label' => $label]; } return (string) $this->renderer->searchAndRenderBlock($view, 'label', $vars); @@ -234,27 +234,27 @@ class FormExtensionDivLayoutTest extends AbstractDivLayoutTest return (string) $this->renderer->searchAndRenderBlock($view, 'errors'); } - protected function renderWidget(FormView $view, array $vars = array()) + protected function renderWidget(FormView $view, array $vars = []) { return (string) $this->renderer->searchAndRenderBlock($view, 'widget', $vars); } - protected function renderRow(FormView $view, array $vars = array()) + protected function renderRow(FormView $view, array $vars = []) { return (string) $this->renderer->searchAndRenderBlock($view, 'row', $vars); } - protected function renderRest(FormView $view, array $vars = array()) + protected function renderRest(FormView $view, array $vars = []) { return (string) $this->renderer->searchAndRenderBlock($view, 'rest', $vars); } - protected function renderStart(FormView $view, array $vars = array()) + protected function renderStart(FormView $view, array $vars = []) { return (string) $this->renderer->renderBlock($view, 'form_start', $vars); } - protected function renderEnd(FormView $view, array $vars = array()) + protected function renderEnd(FormView $view, array $vars = []) { return (string) $this->renderer->renderBlock($view, 'form_end', $vars); } @@ -266,15 +266,15 @@ class FormExtensionDivLayoutTest extends AbstractDivLayoutTest public static function themeBlockInheritanceProvider() { - return array( - array(array('theme.html.twig')), - ); + return [ + [['theme.html.twig']], + ]; } public static function themeInheritanceProvider() { - return array( - array(array('parent_label.html.twig'), array('child_label.html.twig')), - ); + return [ + [['parent_label.html.twig'], ['child_label.html.twig']], + ]; } } diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionTableLayoutTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionTableLayoutTest.php index ec00764a76..0b712562a9 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionTableLayoutTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionTableLayoutTest.php @@ -34,30 +34,30 @@ class FormExtensionTableLayoutTest extends AbstractTableLayoutTest { parent::setUp(); - $loader = new StubFilesystemLoader(array( + $loader = new StubFilesystemLoader([ __DIR__.'/../../Resources/views/Form', __DIR__.'/Fixtures/templates/form', - )); + ]); - $environment = new Environment($loader, array('strict_variables' => true)); + $environment = new Environment($loader, ['strict_variables' => true]); $environment->addExtension(new TranslationExtension(new StubTranslator())); $environment->addGlobal('global', ''); $environment->addExtension(new FormExtension()); - $rendererEngine = new TwigRendererEngine(array( + $rendererEngine = new TwigRendererEngine([ 'form_table_layout.html.twig', 'custom_widgets.html.twig', - ), $environment); + ], $environment); $this->renderer = new FormRenderer($rendererEngine, $this->getMockBuilder('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface')->getMock()); $this->registerTwigRuntimeLoader($environment, $this->renderer); } public function testStartTagHasNoActionAttributeWhenActionIsEmpty() { - $form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, array( + $form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, [ 'method' => 'get', 'action' => '', - )); + ]); $html = $this->renderStart($form->createView()); @@ -66,10 +66,10 @@ class FormExtensionTableLayoutTest extends AbstractTableLayoutTest public function testStartTagHasActionAttributeWhenActionIsZero() { - $form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, array( + $form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, [ 'method' => 'get', 'action' => '0', - )); + ]); $html = $this->renderStart($form->createView()); @@ -78,12 +78,12 @@ class FormExtensionTableLayoutTest extends AbstractTableLayoutTest public function testHelpAttr() { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, array( + $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, [ 'help' => 'Help text test!', - 'help_attr' => array( + 'help_attr' => [ 'class' => 'class-test', - ), - )); + ], + ]); $view = $form->createView(); $html = $this->renderHelp($view); @@ -96,15 +96,15 @@ class FormExtensionTableLayoutTest extends AbstractTableLayoutTest ); } - protected function renderForm(FormView $view, array $vars = array()) + protected function renderForm(FormView $view, array $vars = []) { return (string) $this->renderer->renderBlock($view, 'form', $vars); } - protected function renderLabel(FormView $view, $label = null, array $vars = array()) + protected function renderLabel(FormView $view, $label = null, array $vars = []) { if (null !== $label) { - $vars += array('label' => $label); + $vars += ['label' => $label]; } return (string) $this->renderer->searchAndRenderBlock($view, 'label', $vars); @@ -120,27 +120,27 @@ class FormExtensionTableLayoutTest extends AbstractTableLayoutTest return (string) $this->renderer->searchAndRenderBlock($view, 'errors'); } - protected function renderWidget(FormView $view, array $vars = array()) + protected function renderWidget(FormView $view, array $vars = []) { return (string) $this->renderer->searchAndRenderBlock($view, 'widget', $vars); } - protected function renderRow(FormView $view, array $vars = array()) + protected function renderRow(FormView $view, array $vars = []) { return (string) $this->renderer->searchAndRenderBlock($view, 'row', $vars); } - protected function renderRest(FormView $view, array $vars = array()) + protected function renderRest(FormView $view, array $vars = []) { return (string) $this->renderer->searchAndRenderBlock($view, 'rest', $vars); } - protected function renderStart(FormView $view, array $vars = array()) + protected function renderStart(FormView $view, array $vars = []) { return (string) $this->renderer->renderBlock($view, 'form_start', $vars); } - protected function renderEnd(FormView $view, array $vars = array()) + protected function renderEnd(FormView $view, array $vars = []) { return (string) $this->renderer->renderBlock($view, 'form_end', $vars); } diff --git a/src/Symfony/Bridge/Twig/Tests/Translation/TwigExtractorTest.php b/src/Symfony/Bridge/Twig/Tests/Translation/TwigExtractorTest.php index fca5f4d4a9..1f5c1955c7 100644 --- a/src/Symfony/Bridge/Twig/Tests/Translation/TwigExtractorTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Translation/TwigExtractorTest.php @@ -28,12 +28,12 @@ class TwigExtractorTest extends TestCase public function testExtract($template, $messages) { $loader = $this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock(); - $twig = new Environment($loader, array( + $twig = new Environment($loader, [ 'strict_variables' => true, 'debug' => true, 'cache' => false, 'autoescape' => false, - )); + ]); $twig->addExtension(new TranslationExtension($this->getMockBuilder(TranslatorInterface::class)->getMock())); $extractor = new TwigExtractor($twig); @@ -61,23 +61,23 @@ class TwigExtractorTest extends TestCase public function getExtractData() { - return array( - array('{{ "new key" | trans() }}', array('new key' => 'messages')), - array('{{ "new key" | trans() | upper }}', array('new key' => 'messages')), - array('{{ "new key" | trans({}, "domain") }}', array('new key' => 'domain')), - array('{% trans %}new key{% endtrans %}', array('new key' => 'messages')), - array('{% trans %} new key {% endtrans %}', array('new key' => 'messages')), - array('{% trans from "domain" %}new key{% endtrans %}', array('new key' => 'domain')), - array('{% set foo = "new key" | trans %}', array('new key' => 'messages')), - array('{{ 1 ? "new key" | trans : "another key" | trans }}', array('new key' => 'messages', 'another key' => 'messages')), + return [ + ['{{ "new key" | trans() }}', ['new key' => 'messages']], + ['{{ "new key" | trans() | upper }}', ['new key' => 'messages']], + ['{{ "new key" | trans({}, "domain") }}', ['new key' => 'domain']], + ['{% trans %}new key{% endtrans %}', ['new key' => 'messages']], + ['{% trans %} new key {% endtrans %}', ['new key' => 'messages']], + ['{% trans from "domain" %}new key{% endtrans %}', ['new key' => 'domain']], + ['{% set foo = "new key" | trans %}', ['new key' => 'messages']], + ['{{ 1 ? "new key" | trans : "another key" | trans }}', ['new key' => 'messages', 'another key' => 'messages']], // make sure 'trans_default_domain' tag is supported - array('{% trans_default_domain "domain" %}{{ "new key"|trans }}', array('new key' => 'domain')), - array('{% trans_default_domain "domain" %}{% trans %}new key{% endtrans %}', array('new key' => 'domain')), + ['{% trans_default_domain "domain" %}{{ "new key"|trans }}', ['new key' => 'domain']], + ['{% trans_default_domain "domain" %}{% trans %}new key{% endtrans %}', ['new key' => 'domain']], // make sure this works with twig's named arguments - array('{{ "new key" | trans(domain="domain") }}', array('new key' => 'domain')), - ); + ['{{ "new key" | trans(domain="domain") }}', ['new key' => 'domain']], + ]; } /** @@ -85,17 +85,17 @@ class TwigExtractorTest extends TestCase */ public function getLegacyExtractData() { - return array( - array('{{ "new key" | transchoice(1) }}', array('new key' => 'messages')), - array('{{ "new key" | transchoice(1) | upper }}', array('new key' => 'messages')), - array('{{ "new key" | transchoice(1, {}, "domain") }}', array('new key' => 'domain')), + return [ + ['{{ "new key" | transchoice(1) }}', ['new key' => 'messages']], + ['{{ "new key" | transchoice(1) | upper }}', ['new key' => 'messages']], + ['{{ "new key" | transchoice(1, {}, "domain") }}', ['new key' => 'domain']], // make sure 'trans_default_domain' tag is supported - array('{% trans_default_domain "domain" %}{{ "new key"|transchoice }}', array('new key' => 'domain')), + ['{% trans_default_domain "domain" %}{{ "new key"|transchoice }}', ['new key' => 'domain']], // make sure this works with twig's named arguments - array('{{ "new key" | transchoice(domain="domain", count=1) }}', array('new key' => 'domain')), - ); + ['{{ "new key" | transchoice(domain="domain", count=1) }}', ['new key' => 'domain']], + ]; } /** @@ -128,11 +128,11 @@ class TwigExtractorTest extends TestCase */ public function resourcesWithSyntaxErrorsProvider() { - return array( - array(__DIR__.'/../Fixtures'), - array(__DIR__.'/../Fixtures/extractor/syntax_error.twig'), - array(new \SplFileInfo(__DIR__.'/../Fixtures/extractor/syntax_error.twig')), - ); + return [ + [__DIR__.'/../Fixtures'], + [__DIR__.'/../Fixtures/extractor/syntax_error.twig'], + [new \SplFileInfo(__DIR__.'/../Fixtures/extractor/syntax_error.twig')], + ]; } /** @@ -140,13 +140,13 @@ class TwigExtractorTest extends TestCase */ public function testExtractWithFiles($resource) { - $loader = new ArrayLoader(array()); - $twig = new Environment($loader, array( + $loader = new ArrayLoader([]); + $twig = new Environment($loader, [ 'strict_variables' => true, 'debug' => true, 'cache' => false, 'autoescape' => false, - )); + ]); $twig->addExtension(new TranslationExtension($this->getMockBuilder(TranslatorInterface::class)->getMock())); $extractor = new TwigExtractor($twig); @@ -164,12 +164,12 @@ class TwigExtractorTest extends TestCase { $directory = __DIR__.'/../Fixtures/extractor/'; - return array( - array($directory.'with_translations.html.twig'), - array(array($directory.'with_translations.html.twig')), - array(array(new \SplFileInfo($directory.'with_translations.html.twig'))), - array(new \ArrayObject(array($directory.'with_translations.html.twig'))), - array(new \ArrayObject(array(new \SplFileInfo($directory.'with_translations.html.twig')))), - ); + return [ + [$directory.'with_translations.html.twig'], + [[$directory.'with_translations.html.twig']], + [[new \SplFileInfo($directory.'with_translations.html.twig')]], + [new \ArrayObject([$directory.'with_translations.html.twig'])], + [new \ArrayObject([new \SplFileInfo($directory.'with_translations.html.twig')])], + ]; } } diff --git a/src/Symfony/Bridge/Twig/TokenParser/TransChoiceTokenParser.php b/src/Symfony/Bridge/Twig/TokenParser/TransChoiceTokenParser.php index 84e13f1efb..08b44b27b8 100644 --- a/src/Symfony/Bridge/Twig/TokenParser/TransChoiceTokenParser.php +++ b/src/Symfony/Bridge/Twig/TokenParser/TransChoiceTokenParser.php @@ -42,7 +42,7 @@ class TransChoiceTokenParser extends TransTokenParser @trigger_error(sprintf('The "transchoice" tag is deprecated since Symfony 4.2, use the "trans" one instead with a "%%count%%" parameter in %s line %d.', $stream->getSourceContext()->getName(), $lineno), E_USER_DEPRECATED); - $vars = new ArrayExpression(array(), $lineno); + $vars = new ArrayExpression([], $lineno); $count = $this->parser->getExpressionParser()->parseExpression(); @@ -69,7 +69,7 @@ class TransChoiceTokenParser extends TransTokenParser $stream->expect(Token::BLOCK_END_TYPE); - $body = $this->parser->subparse(array($this, 'decideTransChoiceFork'), true); + $body = $this->parser->subparse([$this, 'decideTransChoiceFork'], true); if (!$body instanceof TextNode && !$body instanceof AbstractExpression) { throw new SyntaxError('A message inside a transchoice tag must be a simple text.', $body->getTemplateLine(), $stream->getSourceContext()); @@ -82,7 +82,7 @@ class TransChoiceTokenParser extends TransTokenParser public function decideTransChoiceFork($token) { - return $token->test(array('endtranschoice')); + return $token->test(['endtranschoice']); } /** diff --git a/src/Symfony/Bridge/Twig/TokenParser/TransTokenParser.php b/src/Symfony/Bridge/Twig/TokenParser/TransTokenParser.php index 3a485383ec..023e3dbf43 100644 --- a/src/Symfony/Bridge/Twig/TokenParser/TransTokenParser.php +++ b/src/Symfony/Bridge/Twig/TokenParser/TransTokenParser.php @@ -40,7 +40,7 @@ class TransTokenParser extends AbstractTokenParser $stream = $this->parser->getStream(); $count = null; - $vars = new ArrayExpression(array(), $lineno); + $vars = new ArrayExpression([], $lineno); $domain = null; $locale = null; if (!$stream->test(Token::BLOCK_END_TYPE)) { @@ -73,7 +73,7 @@ class TransTokenParser extends AbstractTokenParser // {% trans %}message{% endtrans %} $stream->expect(Token::BLOCK_END_TYPE); - $body = $this->parser->subparse(array($this, 'decideTransFork'), true); + $body = $this->parser->subparse([$this, 'decideTransFork'], true); if (!$body instanceof TextNode && !$body instanceof AbstractExpression) { throw new SyntaxError('A message inside a trans tag must be a simple text.', $body->getTemplateLine(), $stream->getSourceContext()); @@ -86,7 +86,7 @@ class TransTokenParser extends AbstractTokenParser public function decideTransFork($token) { - return $token->test(array('endtrans')); + return $token->test(['endtrans']); } /** diff --git a/src/Symfony/Bundle/FrameworkBundle/Command/AboutCommand.php b/src/Symfony/Bundle/FrameworkBundle/Command/AboutCommand.php index d781f2a7e7..3c5b15fb7e 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Command/AboutCommand.php +++ b/src/Symfony/Bundle/FrameworkBundle/Command/AboutCommand.php @@ -61,44 +61,44 @@ EOT /** @var KernelInterface $kernel */ $kernel = $this->getApplication()->getKernel(); - $rows = array( - array('Symfony'), + $rows = [ + ['Symfony'], new TableSeparator(), - array('Version', Kernel::VERSION), - array('End of maintenance', Kernel::END_OF_MAINTENANCE.(self::isExpired(Kernel::END_OF_MAINTENANCE) ? ' Expired' : '')), - array('End of life', Kernel::END_OF_LIFE.(self::isExpired(Kernel::END_OF_LIFE) ? ' Expired' : '')), + ['Version', Kernel::VERSION], + ['End of maintenance', Kernel::END_OF_MAINTENANCE.(self::isExpired(Kernel::END_OF_MAINTENANCE) ? ' Expired' : '')], + ['End of life', Kernel::END_OF_LIFE.(self::isExpired(Kernel::END_OF_LIFE) ? ' Expired' : '')], new TableSeparator(), - array('Kernel'), + ['Kernel'], new TableSeparator(), - array('Type', \get_class($kernel)), - array('Environment', $kernel->getEnvironment()), - array('Debug', $kernel->isDebug() ? 'true' : 'false'), - array('Charset', $kernel->getCharset()), - array('Cache directory', self::formatPath($kernel->getCacheDir(), $kernel->getProjectDir()).' ('.self::formatFileSize($kernel->getCacheDir()).')'), - array('Log directory', self::formatPath($kernel->getLogDir(), $kernel->getProjectDir()).' ('.self::formatFileSize($kernel->getLogDir()).')'), + ['Type', \get_class($kernel)], + ['Environment', $kernel->getEnvironment()], + ['Debug', $kernel->isDebug() ? 'true' : 'false'], + ['Charset', $kernel->getCharset()], + ['Cache directory', self::formatPath($kernel->getCacheDir(), $kernel->getProjectDir()).' ('.self::formatFileSize($kernel->getCacheDir()).')'], + ['Log directory', self::formatPath($kernel->getLogDir(), $kernel->getProjectDir()).' ('.self::formatFileSize($kernel->getLogDir()).')'], new TableSeparator(), - array('PHP'), + ['PHP'], new TableSeparator(), - array('Version', PHP_VERSION), - array('Architecture', (PHP_INT_SIZE * 8).' bits'), - array('Intl locale', class_exists('Locale', false) && \Locale::getDefault() ? \Locale::getDefault() : 'n/a'), - array('Timezone', date_default_timezone_get().' ('.(new \DateTime())->format(\DateTime::W3C).')'), - array('OPcache', \extension_loaded('Zend OPcache') && filter_var(ini_get('opcache.enable'), FILTER_VALIDATE_BOOLEAN) ? 'true' : 'false'), - array('APCu', \extension_loaded('apcu') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? 'true' : 'false'), - array('Xdebug', \extension_loaded('xdebug') ? 'true' : 'false'), - ); + ['Version', PHP_VERSION], + ['Architecture', (PHP_INT_SIZE * 8).' bits'], + ['Intl locale', class_exists('Locale', false) && \Locale::getDefault() ? \Locale::getDefault() : 'n/a'], + ['Timezone', date_default_timezone_get().' ('.(new \DateTime())->format(\DateTime::W3C).')'], + ['OPcache', \extension_loaded('Zend OPcache') && filter_var(ini_get('opcache.enable'), FILTER_VALIDATE_BOOLEAN) ? 'true' : 'false'], + ['APCu', \extension_loaded('apcu') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? 'true' : 'false'], + ['Xdebug', \extension_loaded('xdebug') ? 'true' : 'false'], + ]; if ($dotenv = self::getDotenvVars()) { - $rows = array_merge($rows, array( + $rows = array_merge($rows, [ new TableSeparator(), - array('Environment (.env)'), + ['Environment (.env)'], new TableSeparator(), - ), array_map(function ($value, $name) { - return array($name, $value); + ], array_map(function ($value, $name) { + return [$name, $value]; }, $dotenv, array_keys($dotenv))); } - $io->table(array(), $rows); + $io->table([], $rows); } private static function formatPath(string $path, string $baseDir): string @@ -129,7 +129,7 @@ EOT private static function getDotenvVars(): array { - $vars = array(); + $vars = []; foreach (explode(',', getenv('SYMFONY_DOTENV_VARS')) as $name) { if ('' !== $name && false !== $value = getenv($name)) { $vars[$name] = $value; diff --git a/src/Symfony/Bundle/FrameworkBundle/Command/ContainerDebugCommand.php b/src/Symfony/Bundle/FrameworkBundle/Command/ContainerDebugCommand.php index 575d109dd6..9b5193d63b 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Command/ContainerDebugCommand.php +++ b/src/Symfony/Bundle/FrameworkBundle/Command/ContainerDebugCommand.php @@ -48,7 +48,7 @@ class ContainerDebugCommand extends Command protected function configure() { $this - ->setDefinition(array( + ->setDefinition([ new InputArgument('name', InputArgument::OPTIONAL, 'A service name (foo)'), new InputOption('show-private', null, InputOption::VALUE_NONE, 'Used to show public *and* private services (deprecated)'), new InputOption('show-arguments', null, InputOption::VALUE_NONE, 'Used to show arguments in services'), @@ -60,7 +60,7 @@ class ContainerDebugCommand extends Command new InputOption('types', null, InputOption::VALUE_NONE, 'Displays types (classes/interfaces) available in the container'), new InputOption('format', null, InputOption::VALUE_REQUIRED, 'The output format (txt, xml, json, or md)', 'txt'), new InputOption('raw', null, InputOption::VALUE_NONE, 'To output raw description'), - )) + ]) ->setDescription('Displays current services for an application') ->setHelp(<<<'EOF' The %command.name% command displays all configured public services: @@ -117,26 +117,26 @@ EOF $object = $this->getContainerBuilder(); if ($input->getOption('types')) { - $options = array(); - $options['filter'] = array($this, 'filterToServiceTypes'); + $options = []; + $options['filter'] = [$this, 'filterToServiceTypes']; } elseif ($input->getOption('parameters')) { - $parameters = array(); + $parameters = []; foreach ($object->getParameterBag()->all() as $k => $v) { $parameters[$k] = $object->resolveEnvPlaceholders($v); } $object = new ParameterBag($parameters); - $options = array(); + $options = []; } elseif ($parameter = $input->getOption('parameter')) { - $options = array('parameter' => $parameter); + $options = ['parameter' => $parameter]; } elseif ($input->getOption('tags')) { - $options = array('group_by' => 'tags'); + $options = ['group_by' => 'tags']; } elseif ($tag = $input->getOption('tag')) { - $options = array('tag' => $tag); + $options = ['tag' => $tag]; } elseif ($name = $input->getArgument('name')) { $name = $this->findProperServiceName($input, $errorIo, $object, $name, $input->getOption('show-hidden')); - $options = array('id' => $name); + $options = ['id' => $name]; } else { - $options = array(); + $options = []; } $helper = new DescriptorHelper(); @@ -150,7 +150,7 @@ EOF $helper->describe($io, $object, $options); } catch (ServiceNotFoundException $e) { if ('' !== $e->getId() && '@' === $e->getId()[0]) { - throw new ServiceNotFoundException($e->getId(), $e->getSourceId(), null, array(substr($e->getId(), 1))); + throw new ServiceNotFoundException($e->getId(), $e->getSourceId(), null, [substr($e->getId(), 1)]); } throw $e; @@ -174,7 +174,7 @@ EOF */ protected function validateInput(InputInterface $input) { - $options = array('tags', 'tag', 'parameters', 'parameter'); + $options = ['tags', 'tag', 'parameters', 'parameter']; $optionsCount = 0; foreach ($options as $option) { @@ -209,7 +209,7 @@ EOF if (!$kernel->isDebug() || !(new ConfigCache($kernel->getContainer()->getParameter('debug.container.dump'), true))->isFresh()) { $buildContainer = \Closure::bind(function () { return $this->buildContainer(); }, $kernel, \get_class($kernel)); $container = $buildContainer(); - $container->getCompilerPassConfig()->setRemovingPasses(array()); + $container->getCompilerPassConfig()->setRemovingPasses([]); $container->compile(); } else { (new XmlFileLoader($container = new ContainerBuilder(), new FileLocator()))->load($kernel->getContainer()->getParameter('debug.container.dump')); @@ -239,7 +239,7 @@ EOF private function findServiceIdsContaining(ContainerBuilder $builder, string $name, bool $showHidden) { $serviceIds = $builder->getServiceIds(); - $foundServiceIds = $foundServiceIdsIgnoringBackslashes = array(); + $foundServiceIds = $foundServiceIdsIgnoringBackslashes = []; foreach ($serviceIds as $serviceId) { if (!$showHidden && 0 === strpos($serviceId, '.')) { continue; diff --git a/src/Symfony/Bundle/FrameworkBundle/Command/DebugAutowiringCommand.php b/src/Symfony/Bundle/FrameworkBundle/Command/DebugAutowiringCommand.php index 1c832c04d3..a1097592ee 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Command/DebugAutowiringCommand.php +++ b/src/Symfony/Bundle/FrameworkBundle/Command/DebugAutowiringCommand.php @@ -35,10 +35,10 @@ class DebugAutowiringCommand extends ContainerDebugCommand protected function configure() { $this - ->setDefinition(array( + ->setDefinition([ new InputArgument('search', InputArgument::OPTIONAL, 'A search filter'), new InputOption('all', null, InputOption::VALUE_NONE, 'Show also services that are not aliased'), - )) + ]) ->setDescription('Lists classes/interfaces you can use for autowiring') ->setHelp(<<<'EOF' The %command.name% command displays the classes and interfaces that @@ -65,7 +65,7 @@ EOF $builder = $this->getContainerBuilder(); $serviceIds = $builder->getServiceIds(); - $serviceIds = array_filter($serviceIds, array($this, 'filterToServiceTypes')); + $serviceIds = array_filter($serviceIds, [$this, 'filterToServiceTypes']); if ($search = $input->getArgument('search')) { $serviceIds = array_filter($serviceIds, function ($serviceId) use ($search) { @@ -86,11 +86,11 @@ EOF if ($search) { $io->text(sprintf('(only showing classes/interfaces matching %s)', $search)); } - $hasAlias = array(); + $hasAlias = []; $all = $input->getOption('all'); $previousId = '-'; foreach ($serviceIds as $serviceId) { - $text = array(); + $text = []; if (0 !== strpos($serviceId, $previousId)) { $text[] = ''; if ('' !== $description = Descriptor::getClassDescription($serviceId, $serviceId)) { diff --git a/src/Symfony/Bundle/FrameworkBundle/Command/TranslationDebugCommand.php b/src/Symfony/Bundle/FrameworkBundle/Command/TranslationDebugCommand.php index 92c1c07628..0b284e61c0 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Command/TranslationDebugCommand.php +++ b/src/Symfony/Bundle/FrameworkBundle/Command/TranslationDebugCommand.php @@ -74,14 +74,14 @@ class TranslationDebugCommand extends Command protected function configure() { $this - ->setDefinition(array( + ->setDefinition([ new InputArgument('locale', InputArgument::REQUIRED, 'The locale'), new InputArgument('bundle', InputArgument::OPTIONAL, 'The bundle name or directory where to load the messages'), new InputOption('domain', null, InputOption::VALUE_OPTIONAL, 'The messages domain'), new InputOption('only-missing', null, InputOption::VALUE_NONE, 'Displays only missing messages'), new InputOption('only-unused', null, InputOption::VALUE_NONE, 'Displays only unused messages'), new InputOption('all', null, InputOption::VALUE_NONE, 'Load messages from all registered bundles'), - )) + ]) ->setDescription('Displays translation messages information') ->setHelp(<<<'EOF' The %command.name% command helps finding unused or missing translation @@ -131,7 +131,7 @@ EOF $rootDir = $kernel->getContainer()->getParameter('kernel.root_dir'); // Define Root Paths - $transPaths = array(); + $transPaths = []; if (is_dir($dir = $rootDir.'/Resources/translations')) { if ($dir !== $this->defaultTransPath) { $notice = sprintf('Storing translations in the "%s" directory is deprecated since Symfony 4.2, ', $dir); @@ -142,7 +142,7 @@ EOF if ($this->defaultTransPath) { $transPaths[] = $this->defaultTransPath; } - $viewsPaths = array(); + $viewsPaths = []; if (is_dir($dir = $rootDir.'/Resources/views')) { if ($dir !== $this->defaultViewsPath) { $notice = sprintf('Storing templates in the "%s" directory is deprecated since Symfony 4.2, ', $dir); @@ -158,7 +158,7 @@ EOF if (null !== $input->getArgument('bundle')) { try { $bundle = $kernel->getBundle($input->getArgument('bundle')); - $transPaths = array($bundle->getPath().'/Resources/translations'); + $transPaths = [$bundle->getPath().'/Resources/translations']; if ($this->defaultTransPath) { $transPaths[] = $this->defaultTransPath; } @@ -167,7 +167,7 @@ EOF $notice = sprintf('Storing translations files for "%s" in the "%s" directory is deprecated since Symfony 4.2, ', $dir, $bundle->getName()); @trigger_error($notice.($this->defaultTransPath ? sprintf('use the "%s" directory instead.', $this->defaultTransPath) : 'configure and use "framework.translator.default_path" instead.'), E_USER_DEPRECATED); } - $viewsPaths = array($bundle->getPath().'/Resources/views'); + $viewsPaths = [$bundle->getPath().'/Resources/views']; if ($this->defaultViewsPath) { $viewsPaths[] = $this->defaultViewsPath; } @@ -180,7 +180,7 @@ EOF // such a bundle does not exist, so treat the argument as path $path = $input->getArgument('bundle'); - $transPaths = array($path.'/translations'); + $transPaths = [$path.'/translations']; if (is_dir($dir = $path.'/Resources/translations')) { if ($dir !== $this->defaultTransPath) { @trigger_error(sprintf('Storing translations in the "%s" directory is deprecated since Symfony 4.2, use the "%s" directory instead.', $dir, $path.'/translations'), E_USER_DEPRECATED); @@ -188,7 +188,7 @@ EOF $transPaths[] = $dir; } - $viewsPaths = array($path.'/templates'); + $viewsPaths = [$path.'/templates']; if (is_dir($dir = $path.'/Resources/views')) { if ($dir !== $this->defaultViewsPath) { @trigger_error(sprintf('Storing templates in the "%s" directory is deprecated since Symfony 4.2, use the "%s" directory instead.', $dir, $path.'/templates'), E_USER_DEPRECATED); @@ -227,7 +227,7 @@ EOF $mergeOperation = new MergeOperation($extractedCatalogue, $currentCatalogue); $allMessages = $mergeOperation->getResult()->all($domain); if (null !== $domain) { - $allMessages = array($domain => $allMessages); + $allMessages = [$domain => $allMessages]; } // No defined or extracted messages @@ -247,16 +247,16 @@ EOF $fallbackCatalogues = $this->loadFallbackCatalogues($locale, $transPaths); // Display header line - $headers = array('State', 'Domain', 'Id', sprintf('Message Preview (%s)', $locale)); + $headers = ['State', 'Domain', 'Id', sprintf('Message Preview (%s)', $locale)]; foreach ($fallbackCatalogues as $fallbackCatalogue) { $headers[] = sprintf('Fallback Message Preview (%s)', $fallbackCatalogue->getLocale()); } - $rows = array(); + $rows = []; // Iterate all message ids and determine their state foreach ($allMessages as $domain => $messages) { foreach (array_keys($messages) as $messageId) { $value = $currentCatalogue->get($messageId, $domain); - $states = array(); + $states = []; if ($extractedCatalogue->defines($messageId, $domain)) { if (!$currentCatalogue->defines($messageId, $domain)) { @@ -279,7 +279,7 @@ EOF } } - $row = array($this->formatStates($states), $domain, $this->formatId($messageId), $this->sanitizeString($value)); + $row = [$this->formatStates($states), $domain, $this->formatId($messageId), $this->sanitizeString($value)]; foreach ($fallbackCatalogues as $fallbackCatalogue) { $row[] = $this->sanitizeString($fallbackCatalogue->get($messageId, $domain)); } @@ -310,7 +310,7 @@ EOF private function formatStates(array $states): string { - $result = array(); + $result = []; foreach ($states as $state) { $result[] = $this->formatState($state); } @@ -367,7 +367,7 @@ EOF */ private function loadFallbackCatalogues(string $locale, array $transPaths): array { - $fallbackCatalogues = array(); + $fallbackCatalogues = []; if ($this->translator instanceof Translator || $this->translator instanceof DataCollectorTranslator || $this->translator instanceof LoggingTranslator) { foreach ($this->translator->getFallbackLocales() as $fallbackLocale) { if ($fallbackLocale === $locale) { diff --git a/src/Symfony/Bundle/FrameworkBundle/Command/TranslationUpdateCommand.php b/src/Symfony/Bundle/FrameworkBundle/Command/TranslationUpdateCommand.php index 6e009173d7..43c71c9ec8 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Command/TranslationUpdateCommand.php +++ b/src/Symfony/Bundle/FrameworkBundle/Command/TranslationUpdateCommand.php @@ -63,7 +63,7 @@ class TranslationUpdateCommand extends Command protected function configure() { $this - ->setDefinition(array( + ->setDefinition([ new InputArgument('locale', InputArgument::REQUIRED, 'The locale'), new InputArgument('bundle', InputArgument::OPTIONAL, 'The bundle name or directory where to load the messages'), new InputOption('prefix', null, InputOption::VALUE_OPTIONAL, 'Override the default prefix', '__'), @@ -73,7 +73,7 @@ class TranslationUpdateCommand extends Command new InputOption('no-backup', null, InputOption::VALUE_NONE, 'Should backup be disabled'), new InputOption('clean', null, InputOption::VALUE_NONE, 'Should clean not found messages'), new InputOption('domain', null, InputOption::VALUE_OPTIONAL, 'Specify the domain to update'), - )) + ]) ->setDescription('Updates the translation file') ->setHelp(<<<'EOF' The %command.name% command extracts translation strings from templates @@ -112,7 +112,7 @@ EOF // check format $supportedFormats = $this->writer->getFormats(); if (!\in_array($input->getOption('output-format'), $supportedFormats, true)) { - $errorIo->error(array('Wrong output format', 'Supported formats are: '.implode(', ', $supportedFormats).'.')); + $errorIo->error(['Wrong output format', 'Supported formats are: '.implode(', ', $supportedFormats).'.']); return 1; } @@ -121,7 +121,7 @@ EOF $rootDir = $kernel->getContainer()->getParameter('kernel.root_dir'); // Define Root Paths - $transPaths = array(); + $transPaths = []; if (is_dir($dir = $rootDir.'/Resources/translations')) { if ($dir !== $this->defaultTransPath) { $notice = sprintf('Storing translations in the "%s" directory is deprecated since Symfony 4.2, ', $dir); @@ -132,7 +132,7 @@ EOF if ($this->defaultTransPath) { $transPaths[] = $this->defaultTransPath; } - $viewsPaths = array(); + $viewsPaths = []; if (is_dir($dir = $rootDir.'/Resources/views')) { if ($dir !== $this->defaultViewsPath) { $notice = sprintf('Storing templates in the "%s" directory is deprecated since Symfony 4.2, ', $dir); @@ -149,7 +149,7 @@ EOF if (null !== $input->getArgument('bundle')) { try { $foundBundle = $kernel->getBundle($input->getArgument('bundle')); - $transPaths = array($foundBundle->getPath().'/Resources/translations'); + $transPaths = [$foundBundle->getPath().'/Resources/translations']; if ($this->defaultTransPath) { $transPaths[] = $this->defaultTransPath; } @@ -158,7 +158,7 @@ EOF $notice = sprintf('Storing translations files for "%s" in the "%s" directory is deprecated since Symfony 4.2, ', $foundBundle->getName(), $dir); @trigger_error($notice.($this->defaultTransPath ? sprintf('use the "%s" directory instead.', $this->defaultTransPath) : 'configure and use "framework.translator.default_path" instead.'), E_USER_DEPRECATED); } - $viewsPaths = array($foundBundle->getPath().'/Resources/views'); + $viewsPaths = [$foundBundle->getPath().'/Resources/views']; if ($this->defaultViewsPath) { $viewsPaths[] = $this->defaultViewsPath; } @@ -172,7 +172,7 @@ EOF // such a bundle does not exist, so treat the argument as path $path = $input->getArgument('bundle'); - $transPaths = array($path.'/translations'); + $transPaths = [$path.'/translations']; if (is_dir($dir = $path.'/Resources/translations')) { if ($dir !== $this->defaultTransPath) { @trigger_error(sprintf('Storing translations in the "%s" directory is deprecated since Symfony 4.2, use the "%s" directory instead.', $dir, $path.'/translations'), E_USER_DEPRECATED); @@ -180,7 +180,7 @@ EOF $transPaths[] = $dir; } - $viewsPaths = array($path.'/templates'); + $viewsPaths = [$path.'/templates']; if (is_dir($dir = $path.'/Resources/views')) { if ($dir !== $this->defaultViewsPath) { @trigger_error(sprintf('Storing templates in the "%s" directory is deprecated since Symfony 4.2, use the "%s" directory instead.', $dir, $path.'/templates'), E_USER_DEPRECATED); @@ -287,7 +287,7 @@ EOF $bundleTransPath = end($transPaths); } - $this->writer->write($operation->getResult(), $input->getOption('output-format'), array('path' => $bundleTransPath, 'default_locale' => $this->defaultLocale)); + $this->writer->write($operation->getResult(), $input->getOption('output-format'), ['path' => $bundleTransPath, 'default_locale' => $this->defaultLocale]); if (true === $input->getOption('dump-messages')) { $resultMessage .= ' and translation files were updated'; diff --git a/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/TextDescriptor.php b/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/TextDescriptor.php index 3938a5dc11..79566a1ad9 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/TextDescriptor.php +++ b/src/Symfony/Bundle/FrameworkBundle/Console/Descriptor/TextDescriptor.php @@ -36,24 +36,24 @@ class TextDescriptor extends Descriptor /** * {@inheritdoc} */ - protected function describeRouteCollection(RouteCollection $routes, array $options = array()) + protected function describeRouteCollection(RouteCollection $routes, array $options = []) { $showControllers = isset($options['show_controllers']) && $options['show_controllers']; - $tableHeaders = array('Name', 'Method', 'Scheme', 'Host', 'Path'); + $tableHeaders = ['Name', 'Method', 'Scheme', 'Host', 'Path']; if ($showControllers) { $tableHeaders[] = 'Controller'; } - $tableRows = array(); + $tableRows = []; foreach ($routes->all() as $name => $route) { - $row = array( + $row = [ $name, $route->getMethods() ? implode('|', $route->getMethods()) : 'ANY', $route->getSchemes() ? implode('|', $route->getSchemes()) : 'ANY', '' !== $route->getHost() ? $route->getHost() : 'ANY', $route->getPath(), - ); + ]; if ($showControllers) { $controller = $route->getDefault('_controller'); @@ -75,22 +75,22 @@ class TextDescriptor extends Descriptor /** * {@inheritdoc} */ - protected function describeRoute(Route $route, array $options = array()) + protected function describeRoute(Route $route, array $options = []) { - $tableHeaders = array('Property', 'Value'); - $tableRows = array( - array('Route Name', isset($options['name']) ? $options['name'] : ''), - array('Path', $route->getPath()), - array('Path Regex', $route->compile()->getRegex()), - array('Host', ('' !== $route->getHost() ? $route->getHost() : 'ANY')), - array('Host Regex', ('' !== $route->getHost() ? $route->compile()->getHostRegex() : '')), - array('Scheme', ($route->getSchemes() ? implode('|', $route->getSchemes()) : 'ANY')), - array('Method', ($route->getMethods() ? implode('|', $route->getMethods()) : 'ANY')), - array('Requirements', ($route->getRequirements() ? $this->formatRouterConfig($route->getRequirements()) : 'NO CUSTOM')), - array('Class', \get_class($route)), - array('Defaults', $this->formatRouterConfig($route->getDefaults())), - array('Options', $this->formatRouterConfig($route->getOptions())), - ); + $tableHeaders = ['Property', 'Value']; + $tableRows = [ + ['Route Name', isset($options['name']) ? $options['name'] : ''], + ['Path', $route->getPath()], + ['Path Regex', $route->compile()->getRegex()], + ['Host', ('' !== $route->getHost() ? $route->getHost() : 'ANY')], + ['Host Regex', ('' !== $route->getHost() ? $route->compile()->getHostRegex() : '')], + ['Scheme', ($route->getSchemes() ? implode('|', $route->getSchemes()) : 'ANY')], + ['Method', ($route->getMethods() ? implode('|', $route->getMethods()) : 'ANY')], + ['Requirements', ($route->getRequirements() ? $this->formatRouterConfig($route->getRequirements()) : 'NO CUSTOM')], + ['Class', \get_class($route)], + ['Defaults', $this->formatRouterConfig($route->getDefaults())], + ['Options', $this->formatRouterConfig($route->getOptions())], + ]; $table = new Table($this->getOutput()); $table->setHeaders($tableHeaders)->setRows($tableRows); @@ -100,13 +100,13 @@ class TextDescriptor extends Descriptor /** * {@inheritdoc} */ - protected function describeContainerParameters(ParameterBag $parameters, array $options = array()) + protected function describeContainerParameters(ParameterBag $parameters, array $options = []) { - $tableHeaders = array('Parameter', 'Value'); + $tableHeaders = ['Parameter', 'Value']; - $tableRows = array(); + $tableRows = []; foreach ($this->sortParameters($parameters) as $parameter => $value) { - $tableRows[] = array($parameter, $this->formatParameter($value)); + $tableRows[] = [$parameter, $this->formatParameter($value)]; } $options['output']->title('Symfony Container Parameters'); @@ -116,7 +116,7 @@ class TextDescriptor extends Descriptor /** * {@inheritdoc} */ - protected function describeContainerTags(ContainerBuilder $builder, array $options = array()) + protected function describeContainerTags(ContainerBuilder $builder, array $options = []) { $showHidden = isset($options['show_hidden']) && $options['show_hidden']; @@ -135,7 +135,7 @@ class TextDescriptor extends Descriptor /** * {@inheritdoc} */ - protected function describeContainerService($service, array $options = array(), ContainerBuilder $builder = null) + protected function describeContainerService($service, array $options = [], ContainerBuilder $builder = null) { if (!isset($options['id'])) { throw new \InvalidArgumentException('An "id" option must be provided.'); @@ -148,10 +148,10 @@ class TextDescriptor extends Descriptor } else { $options['output']->title(sprintf('Information for Service "%s"', $options['id'])); $options['output']->table( - array('Service ID', 'Class'), - array( - array(isset($options['id']) ? $options['id'] : '-', \get_class($service)), - ) + ['Service ID', 'Class'], + [ + [isset($options['id']) ? $options['id'] : '-', \get_class($service)], + ] ); } } @@ -159,7 +159,7 @@ class TextDescriptor extends Descriptor /** * {@inheritdoc} */ - protected function describeContainerServices(ContainerBuilder $builder, array $options = array()) + protected function describeContainerServices(ContainerBuilder $builder, array $options = []) { $showHidden = isset($options['show_hidden']) && $options['show_hidden']; $showTag = isset($options['tag']) ? $options['tag'] : null; @@ -177,7 +177,7 @@ class TextDescriptor extends Descriptor $options['output']->title($title); $serviceIds = isset($options['tag']) && $options['tag'] ? array_keys($builder->findTaggedServiceIds($options['tag'])) : $builder->getServiceIds(); - $maxTags = array(); + $maxTags = []; if (isset($options['filter'])) { $serviceIds = array_filter($serviceIds, $options['filter']); @@ -212,8 +212,8 @@ class TextDescriptor extends Descriptor $tagsCount = \count($maxTags); $tagsNames = array_keys($maxTags); - $tableHeaders = array_merge(array('Service ID'), $tagsNames, array('Class name')); - $tableRows = array(); + $tableHeaders = array_merge(['Service ID'], $tagsNames, ['Class name']); + $tableRows = []; $rawOutput = isset($options['raw_text']) && $options['raw_text']; foreach ($this->sortServiceIds($serviceIds) as $serviceId) { $definition = $this->resolveServiceDefinition($builder, $serviceId); @@ -222,24 +222,24 @@ class TextDescriptor extends Descriptor if ($definition instanceof Definition) { if ($showTag) { foreach ($definition->getTag($showTag) as $key => $tag) { - $tagValues = array(); + $tagValues = []; foreach ($tagsNames as $tagName) { $tagValues[] = isset($tag[$tagName]) ? $tag[$tagName] : ''; } if (0 === $key) { - $tableRows[] = array_merge(array($serviceId), $tagValues, array($definition->getClass())); + $tableRows[] = array_merge([$serviceId], $tagValues, [$definition->getClass()]); } else { - $tableRows[] = array_merge(array(' "'), $tagValues, array('')); + $tableRows[] = array_merge([' "'], $tagValues, ['']); } } } else { - $tableRows[] = array($styledServiceId, $definition->getClass()); + $tableRows[] = [$styledServiceId, $definition->getClass()]; } } elseif ($definition instanceof Alias) { $alias = $definition; - $tableRows[] = array_merge(array($styledServiceId, sprintf('alias for "%s"', $alias)), $tagsCount ? array_fill(0, $tagsCount, '') : array()); + $tableRows[] = array_merge([$styledServiceId, sprintf('alias for "%s"', $alias)], $tagsCount ? array_fill(0, $tagsCount, '') : []); } else { - $tableRows[] = array_merge(array($styledServiceId, \get_class($definition)), $tagsCount ? array_fill(0, $tagsCount, '') : array()); + $tableRows[] = array_merge([$styledServiceId, \get_class($definition)], $tagsCount ? array_fill(0, $tagsCount, '') : []); } } @@ -249,7 +249,7 @@ class TextDescriptor extends Descriptor /** * {@inheritdoc} */ - protected function describeContainerDefinition(Definition $definition, array $options = array()) + protected function describeContainerDefinition(Definition $definition, array $options = []) { if (isset($options['id'])) { $options['output']->title(sprintf('Information for Service "%s"', $options['id'])); @@ -259,14 +259,14 @@ class TextDescriptor extends Descriptor $options['output']->text($classDescription."\n"); } - $tableHeaders = array('Option', 'Value'); + $tableHeaders = ['Option', 'Value']; - $tableRows[] = array('Service ID', isset($options['id']) ? $options['id'] : '-'); - $tableRows[] = array('Class', $definition->getClass() ?: '-'); + $tableRows[] = ['Service ID', isset($options['id']) ? $options['id'] : '-']; + $tableRows[] = ['Class', $definition->getClass() ?: '-']; $omitTags = isset($options['omit_tags']) && $options['omit_tags']; if (!$omitTags && ($tags = $definition->getTags())) { - $tagInformation = array(); + $tagInformation = []; foreach ($tags as $tagName => $tagData) { foreach ($tagData as $tagParameters) { $parameters = array_map(function ($key, $value) { @@ -285,46 +285,46 @@ class TextDescriptor extends Descriptor } else { $tagInformation = '-'; } - $tableRows[] = array('Tags', $tagInformation); + $tableRows[] = ['Tags', $tagInformation]; $calls = $definition->getMethodCalls(); if (\count($calls) > 0) { - $callInformation = array(); + $callInformation = []; foreach ($calls as $call) { $callInformation[] = $call[0]; } - $tableRows[] = array('Calls', implode(', ', $callInformation)); + $tableRows[] = ['Calls', implode(', ', $callInformation)]; } - $tableRows[] = array('Public', $definition->isPublic() && !$definition->isPrivate() ? 'yes' : 'no'); - $tableRows[] = array('Synthetic', $definition->isSynthetic() ? 'yes' : 'no'); - $tableRows[] = array('Lazy', $definition->isLazy() ? 'yes' : 'no'); - $tableRows[] = array('Shared', $definition->isShared() ? 'yes' : 'no'); - $tableRows[] = array('Abstract', $definition->isAbstract() ? 'yes' : 'no'); - $tableRows[] = array('Autowired', $definition->isAutowired() ? 'yes' : 'no'); - $tableRows[] = array('Autoconfigured', $definition->isAutoconfigured() ? 'yes' : 'no'); + $tableRows[] = ['Public', $definition->isPublic() && !$definition->isPrivate() ? 'yes' : 'no']; + $tableRows[] = ['Synthetic', $definition->isSynthetic() ? 'yes' : 'no']; + $tableRows[] = ['Lazy', $definition->isLazy() ? 'yes' : 'no']; + $tableRows[] = ['Shared', $definition->isShared() ? 'yes' : 'no']; + $tableRows[] = ['Abstract', $definition->isAbstract() ? 'yes' : 'no']; + $tableRows[] = ['Autowired', $definition->isAutowired() ? 'yes' : 'no']; + $tableRows[] = ['Autoconfigured', $definition->isAutoconfigured() ? 'yes' : 'no']; if ($definition->getFile()) { - $tableRows[] = array('Required File', $definition->getFile() ?: '-'); + $tableRows[] = ['Required File', $definition->getFile() ?: '-']; } if ($factory = $definition->getFactory()) { if (\is_array($factory)) { if ($factory[0] instanceof Reference) { - $tableRows[] = array('Factory Service', $factory[0]); + $tableRows[] = ['Factory Service', $factory[0]]; } elseif ($factory[0] instanceof Definition) { throw new \InvalidArgumentException('Factory is not describable.'); } else { - $tableRows[] = array('Factory Class', $factory[0]); + $tableRows[] = ['Factory Class', $factory[0]]; } - $tableRows[] = array('Factory Method', $factory[1]); + $tableRows[] = ['Factory Method', $factory[1]]; } else { - $tableRows[] = array('Factory Function', $factory); + $tableRows[] = ['Factory Function', $factory]; } } $showArguments = isset($options['show_arguments']) && $options['show_arguments']; - $argumentsInformation = array(); + $argumentsInformation = []; if ($showArguments && ($arguments = $definition->getArguments())) { foreach ($arguments as $argument) { if ($argument instanceof ServiceClosureArgument) { @@ -343,7 +343,7 @@ class TextDescriptor extends Descriptor } } - $tableRows[] = array('Arguments', implode("\n", $argumentsInformation)); + $tableRows[] = ['Arguments', implode("\n", $argumentsInformation)]; } $options['output']->table($tableHeaders, $tableRows); @@ -352,7 +352,7 @@ class TextDescriptor extends Descriptor /** * {@inheritdoc} */ - protected function describeContainerAlias(Alias $alias, array $options = array(), ContainerBuilder $builder = null) + protected function describeContainerAlias(Alias $alias, array $options = [], ContainerBuilder $builder = null) { if ($alias->isPublic()) { $options['output']->comment(sprintf('This service is a public alias for the service %s', (string) $alias)); @@ -364,26 +364,26 @@ class TextDescriptor extends Descriptor return; } - return $this->describeContainerDefinition($builder->getDefinition((string) $alias), array_merge($options, array('id' => (string) $alias))); + return $this->describeContainerDefinition($builder->getDefinition((string) $alias), array_merge($options, ['id' => (string) $alias])); } /** * {@inheritdoc} */ - protected function describeContainerParameter($parameter, array $options = array()) + protected function describeContainerParameter($parameter, array $options = []) { $options['output']->table( - array('Parameter', 'Value'), - array( - array($options['parameter'], $this->formatParameter($parameter), - ), - )); + ['Parameter', 'Value'], + [ + [$options['parameter'], $this->formatParameter($parameter), + ], + ]); } /** * {@inheritdoc} */ - protected function describeEventDispatcherListeners(EventDispatcherInterface $eventDispatcher, array $options = array()) + protected function describeEventDispatcherListeners(EventDispatcherInterface $eventDispatcher, array $options = []) { $event = array_key_exists('event', $options) ? $options['event'] : null; @@ -410,19 +410,19 @@ class TextDescriptor extends Descriptor /** * {@inheritdoc} */ - protected function describeCallable($callable, array $options = array()) + protected function describeCallable($callable, array $options = []) { $this->writeText($this->formatCallable($callable), $options); } private function renderEventListenerTable(EventDispatcherInterface $eventDispatcher, $event, array $eventListeners, SymfonyStyle $io) { - $tableHeaders = array('Order', 'Callable', 'Priority'); - $tableRows = array(); + $tableHeaders = ['Order', 'Callable', 'Priority']; + $tableRows = []; $order = 1; foreach ($eventListeners as $order => $listener) { - $tableRows[] = array(sprintf('#%d', $order + 1), $this->formatCallable($listener), $eventDispatcher->getListenerPriority($event, $listener)); + $tableRows[] = [sprintf('#%d', $order + 1), $this->formatCallable($listener), $eventDispatcher->getListenerPriority($event, $listener)]; } $io->table($tableHeaders, $tableRows); @@ -477,7 +477,7 @@ class TextDescriptor extends Descriptor throw new \InvalidArgumentException('Callable is not describable.'); } - private function writeText(string $content, array $options = array()) + private function writeText(string $content, array $options = []) { $this->write( isset($options['raw_text']) && $options['raw_text'] ? strip_tags($content) : $content, diff --git a/src/Symfony/Bundle/FrameworkBundle/Controller/ControllerTrait.php b/src/Symfony/Bundle/FrameworkBundle/Controller/ControllerTrait.php index cfd9c3c72e..0650fea5ca 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Controller/ControllerTrait.php +++ b/src/Symfony/Bundle/FrameworkBundle/Controller/ControllerTrait.php @@ -419,7 +419,7 @@ trait ControllerTrait } if (null === $linkProvider = $request->attributes->get('_links')) { - $request->attributes->set('_links', new GenericLinkProvider(array($link))); + $request->attributes->set('_links', new GenericLinkProvider([$link])); return; } diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php index 12f2092320..1a8d6fb461 100644 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php +++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php @@ -64,7 +64,7 @@ class Configuration implements ConfigurationInterface ->beforeNormalization() ->ifTrue(function ($v) { return !isset($v['assets']) && isset($v['templating']) && class_exists(Package::class); }) ->then(function ($v) { - $v['assets'] = array(); + $v['assets'] = []; return $v; }) @@ -79,7 +79,7 @@ class Configuration implements ConfigurationInterface ->booleanNode('test')->end() ->scalarNode('default_locale')->defaultValue('en')->end() ->arrayNode('trusted_hosts') - ->beforeNormalization()->ifString()->then(function ($v) { return array($v); })->end() + ->beforeNormalization()->ifString()->then(function ($v) { return [$v]; })->end() ->prototype('scalar')->end() ->end() ->end() @@ -117,9 +117,9 @@ class Configuration implements ConfigurationInterface $rootNode ->children() ->arrayNode('csrf_protection') - ->treatFalseLike(array('enabled' => false)) - ->treatTrueLike(array('enabled' => true)) - ->treatNullLike(array('enabled' => true)) + ->treatFalseLike(['enabled' => false]) + ->treatTrueLike(['enabled' => true]) + ->treatNullLike(['enabled' => true]) ->addDefaultsIfNotSet() ->children() // defaults to framework.session.enabled && !class_exists(FullStack::class) && interface_exists(CsrfTokenManagerInterface::class) @@ -139,9 +139,9 @@ class Configuration implements ConfigurationInterface ->{!class_exists(FullStack::class) && class_exists(Form::class) ? 'canBeDisabled' : 'canBeEnabled'}() ->children() ->arrayNode('csrf_protection') - ->treatFalseLike(array('enabled' => false)) - ->treatTrueLike(array('enabled' => true)) - ->treatNullLike(array('enabled' => true)) + ->treatFalseLike(['enabled' => false]) + ->treatTrueLike(['enabled' => true]) + ->treatNullLike(['enabled' => true]) ->addDefaultsIfNotSet() ->children() ->booleanNode('enabled')->defaultNull()->end() // defaults to framework.csrf_protection.enabled @@ -224,10 +224,10 @@ class Configuration implements ConfigurationInterface unset($workflows['enabled']); if (1 === \count($workflows) && isset($workflows[0]['enabled']) && 1 === \count($workflows[0])) { - $workflows = array(); + $workflows = []; } - if (1 === \count($workflows) && isset($workflows['workflows']) && array_keys($workflows['workflows']) !== range(0, \count($workflows) - 1) && !empty(array_diff(array_keys($workflows['workflows']), array('audit_trail', 'type', 'marking_store', 'supports', 'support_strategy', 'initial_place', 'places', 'transitions')))) { + if (1 === \count($workflows) && isset($workflows['workflows']) && array_keys($workflows['workflows']) !== range(0, \count($workflows) - 1) && !empty(array_diff(array_keys($workflows['workflows']), ['audit_trail', 'type', 'marking_store', 'supports', 'support_strategy', 'initial_place', 'places', 'transitions']))) { $workflows = $workflows['workflows']; } @@ -239,10 +239,10 @@ class Configuration implements ConfigurationInterface unset($workflows[$key]['enabled']); } - $v = array( + $v = [ 'enabled' => true, 'workflows' => $workflows, - ); + ]; } return $v; @@ -260,19 +260,19 @@ class Configuration implements ConfigurationInterface ->canBeEnabled() ->end() ->enumNode('type') - ->values(array('workflow', 'state_machine')) + ->values(['workflow', 'state_machine']) ->defaultValue('state_machine') ->end() ->arrayNode('marking_store') ->fixXmlConfig('argument') ->children() ->enumNode('type') - ->values(array('multiple_state', 'single_state')) + ->values(['multiple_state', 'single_state']) ->end() ->arrayNode('arguments') ->beforeNormalization() ->ifString() - ->then(function ($v) { return array($v); }) + ->then(function ($v) { return [$v]; }) ->end() ->requiresAtLeastOneElement() ->prototype('scalar') @@ -294,7 +294,7 @@ class Configuration implements ConfigurationInterface ->arrayNode('supports') ->beforeNormalization() ->ifString() - ->then(function ($v) { return array($v); }) + ->then(function ($v) { return [$v]; }) ->end() ->prototype('scalar') ->cannotBeEmpty() @@ -317,7 +317,7 @@ class Configuration implements ConfigurationInterface // It's an indexed array of shape ['place1', 'place2'] if (isset($places[0]) && \is_string($places[0])) { return array_map(function (string $place) { - return array('name' => $place); + return ['name' => $place]; }, $places); } @@ -347,8 +347,8 @@ class Configuration implements ConfigurationInterface ->end() ->arrayNode('metadata') ->normalizeKeys(false) - ->defaultValue(array()) - ->example(array('color' => 'blue', 'description' => 'Workflow to manage article.')) + ->defaultValue([]) + ->example(['color' => 'blue', 'description' => 'Workflow to manage article.']) ->prototype('variable') ->end() ->end() @@ -391,7 +391,7 @@ class Configuration implements ConfigurationInterface ->arrayNode('from') ->beforeNormalization() ->ifString() - ->then(function ($v) { return array($v); }) + ->then(function ($v) { return [$v]; }) ->end() ->requiresAtLeastOneElement() ->prototype('scalar') @@ -401,7 +401,7 @@ class Configuration implements ConfigurationInterface ->arrayNode('to') ->beforeNormalization() ->ifString() - ->then(function ($v) { return array($v); }) + ->then(function ($v) { return [$v]; }) ->end() ->requiresAtLeastOneElement() ->prototype('scalar') @@ -410,8 +410,8 @@ class Configuration implements ConfigurationInterface ->end() ->arrayNode('metadata') ->normalizeKeys(false) - ->defaultValue(array()) - ->example(array('color' => 'blue', 'description' => 'Workflow to manage article.')) + ->defaultValue([]) + ->example(['color' => 'blue', 'description' => 'Workflow to manage article.']) ->prototype('variable') ->end() ->end() @@ -420,8 +420,8 @@ class Configuration implements ConfigurationInterface ->end() ->arrayNode('metadata') ->normalizeKeys(false) - ->defaultValue(array()) - ->example(array('color' => 'blue', 'description' => 'Workflow to manage article.')) + ->defaultValue([]) + ->example(['color' => 'blue', 'description' => 'Workflow to manage article.']) ->prototype('variable') ->end() ->end() @@ -497,9 +497,9 @@ class Configuration implements ConfigurationInterface ->scalarNode('cookie_lifetime')->end() ->scalarNode('cookie_path')->end() ->scalarNode('cookie_domain')->end() - ->enumNode('cookie_secure')->values(array(true, false, 'auto'))->end() + ->enumNode('cookie_secure')->values([true, false, 'auto'])->end() ->booleanNode('cookie_httponly')->defaultTrue()->end() - ->enumNode('cookie_samesite')->values(array(null, Cookie::SAMESITE_LAX, Cookie::SAMESITE_STRICT))->defaultNull()->end() + ->enumNode('cookie_samesite')->values([null, Cookie::SAMESITE_LAX, Cookie::SAMESITE_STRICT])->defaultNull()->end() ->booleanNode('use_cookies')->end() ->scalarNode('gc_divisor')->end() ->scalarNode('gc_probability')->defaultValue(1)->end() @@ -533,7 +533,7 @@ class Configuration implements ConfigurationInterface ->end() ->beforeNormalization() ->ifTrue(function ($v) { return !\is_array($v); }) - ->then(function ($v) { return array($v); }) + ->then(function ($v) { return [$v]; }) ->end() ->prototype('scalar')->end() ->end() @@ -553,7 +553,7 @@ class Configuration implements ConfigurationInterface ->canBeEnabled() ->beforeNormalization() ->ifTrue(function ($v) { return false === $v || \is_array($v) && false === $v['enabled']; }) - ->then(function () { return array('enabled' => false, 'engines' => false); }) + ->then(function () { return ['enabled' => false, 'engines' => false]; }) ->end() ->children() ->scalarNode('hinclude_default_template')->defaultNull()->end() @@ -568,7 +568,7 @@ class Configuration implements ConfigurationInterface ->validate() ->ifTrue(function ($v) {return !\in_array('FrameworkBundle:Form', $v); }) ->then(function ($v) { - return array_merge(array('FrameworkBundle:Form'), $v); + return array_merge(['FrameworkBundle:Form'], $v); }) ->end() ->end() @@ -578,13 +578,13 @@ class Configuration implements ConfigurationInterface ->fixXmlConfig('engine') ->children() ->arrayNode('engines') - ->example(array('twig')) + ->example(['twig']) ->isRequired() ->requiresAtLeastOneElement() ->canBeUnset() ->beforeNormalization() ->ifTrue(function ($v) { return !\is_array($v) && false !== $v; }) - ->then(function ($v) { return array($v); }) + ->then(function ($v) { return [$v]; }) ->end() ->prototype('scalar')->end() ->end() @@ -594,7 +594,7 @@ class Configuration implements ConfigurationInterface ->arrayNode('loaders') ->beforeNormalization() ->ifTrue(function ($v) { return !\is_array($v); }) - ->then(function ($v) { return array($v); }) + ->then(function ($v) { return [$v]; }) ->end() ->prototype('scalar')->end() ->end() @@ -622,7 +622,7 @@ class Configuration implements ConfigurationInterface ->requiresAtLeastOneElement() ->beforeNormalization() ->ifTrue(function ($v) { return !\is_array($v); }) - ->then(function ($v) { return array($v); }) + ->then(function ($v) { return [$v]; }) ->end() ->prototype('scalar')->end() ->end() @@ -666,7 +666,7 @@ class Configuration implements ConfigurationInterface ->requiresAtLeastOneElement() ->beforeNormalization() ->ifTrue(function ($v) { return !\is_array($v); }) - ->then(function ($v) { return array($v); }) + ->then(function ($v) { return [$v]; }) ->end() ->prototype('scalar')->end() ->end() @@ -708,9 +708,9 @@ class Configuration implements ConfigurationInterface ->fixXmlConfig('path') ->children() ->arrayNode('fallbacks') - ->beforeNormalization()->ifString()->then(function ($v) { return array($v); })->end() + ->beforeNormalization()->ifString()->then(function ($v) { return [$v]; })->end() ->prototype('scalar')->end() - ->defaultValue(array('en')) + ->defaultValue(['en']) ->end() ->booleanNode('logging')->defaultValue(false)->end() ->scalarNode('formatter')->defaultValue('translator.formatter.default')->end() @@ -759,9 +759,9 @@ class Configuration implements ConfigurationInterface ->scalarNode('cache')->end() ->booleanNode('enable_annotations')->{!class_exists(FullStack::class) && class_exists(Annotation::class) ? 'defaultTrue' : 'defaultFalse'}()->end() ->arrayNode('static_method') - ->defaultValue(array('loadValidatorMetadata')) + ->defaultValue(['loadValidatorMetadata']) ->prototype('scalar')->end() - ->treatFalseLike(array()) + ->treatFalseLike([]) ->validate() ->ifTrue(function ($v) { return !\is_array($v); }) ->then(function ($v) { return (array) $v; }) @@ -769,7 +769,7 @@ class Configuration implements ConfigurationInterface ->end() ->scalarNode('translation_domain')->defaultValue('validators')->end() ->booleanNode('strict_email')->end() - ->enumNode('email_validation_mode')->values(array('html5', 'loose', 'strict'))->end() + ->enumNode('email_validation_mode')->values(['html5', 'loose', 'strict'])->end() ->arrayNode('mapping') ->addDefaultsIfNotSet() ->fixXmlConfig('path') @@ -946,7 +946,7 @@ class Configuration implements ConfigurationInterface ->info('Lock configuration') ->{!class_exists(FullStack::class) && class_exists(Lock::class) ? 'canBeDisabled' : 'canBeEnabled'}() ->beforeNormalization() - ->ifString()->then(function ($v) { return array('enabled' => true, 'resources' => $v); }) + ->ifString()->then(function ($v) { return ['enabled' => true, 'resources' => $v]; }) ->end() ->beforeNormalization() ->ifTrue(function ($v) { return \is_array($v) && !isset($v['resources']); }) @@ -954,7 +954,7 @@ class Configuration implements ConfigurationInterface $e = $v['enabled']; unset($v['enabled']); - return array('enabled' => $e, 'resources' => $v); + return ['enabled' => $e, 'resources' => $v]; }) ->end() ->addDefaultsIfNotSet() @@ -962,16 +962,16 @@ class Configuration implements ConfigurationInterface ->children() ->arrayNode('resources') ->requiresAtLeastOneElement() - ->defaultValue(array('default' => array(class_exists(SemaphoreStore::class) && SemaphoreStore::isSupported() ? 'semaphore' : 'flock'))) + ->defaultValue(['default' => [class_exists(SemaphoreStore::class) && SemaphoreStore::isSupported() ? 'semaphore' : 'flock']]) ->beforeNormalization() - ->ifString()->then(function ($v) { return array('default' => $v); }) + ->ifString()->then(function ($v) { return ['default' => $v]; }) ->end() ->beforeNormalization() ->ifTrue(function ($v) { return \is_array($v) && array_keys($v) === range(0, \count($v) - 1); }) - ->then(function ($v) { return array('default' => $v); }) + ->then(function ($v) { return ['default' => $v]; }) ->end() ->prototype('array') - ->beforeNormalization()->ifString()->then(function ($v) { return array($v); })->end() + ->beforeNormalization()->ifString()->then(function ($v) { return [$v]; })->end() ->prototype('scalar')->end() ->end() ->end() @@ -1009,16 +1009,16 @@ class Configuration implements ConfigurationInterface ->always() ->then(function ($config) { if (!\is_array($config)) { - return array(); + return []; } - $newConfig = array(); + $newConfig = []; foreach ($config as $k => $v) { if (!\is_int($k)) { - $newConfig[$k] = array( - 'senders' => $v['senders'] ?? (\is_array($v) ? array_values($v) : array($v)), + $newConfig[$k] = [ + 'senders' => $v['senders'] ?? (\is_array($v) ? array_values($v) : [$v]), 'send_and_handle' => $v['send_and_handle'] ?? false, - ); + ]; } else { $newConfig[$v['message-class']]['senders'] = array_map( function ($a) { @@ -1049,11 +1049,11 @@ class Configuration implements ConfigurationInterface ->always() ->then(function ($config) { if (false === $config) { - return array('id' => null); + return ['id' => null]; } if (\is_string($config)) { - return array('id' => $config); + return ['id' => $config]; } return $config; @@ -1065,7 +1065,7 @@ class Configuration implements ConfigurationInterface ->arrayNode('context') ->normalizeKeys(false) ->useAttributeAsKey('name') - ->defaultValue(array()) + ->defaultValue([]) ->prototype('variable')->end() ->end() ->end() @@ -1076,7 +1076,7 @@ class Configuration implements ConfigurationInterface ->beforeNormalization() ->ifString() ->then(function (string $dsn) { - return array('dsn' => $dsn); + return ['dsn' => $dsn]; }) ->end() ->fixXmlConfig('option') @@ -1084,7 +1084,7 @@ class Configuration implements ConfigurationInterface ->scalarNode('dsn')->end() ->arrayNode('options') ->normalizeKeys(false) - ->defaultValue(array()) + ->defaultValue([]) ->prototype('variable') ->end() ->end() @@ -1093,27 +1093,27 @@ class Configuration implements ConfigurationInterface ->end() ->scalarNode('default_bus')->defaultNull()->end() ->arrayNode('buses') - ->defaultValue(array('messenger.bus.default' => array('default_middleware' => true, 'middleware' => array()))) + ->defaultValue(['messenger.bus.default' => ['default_middleware' => true, 'middleware' => []]]) ->useAttributeAsKey('name') ->arrayPrototype() ->addDefaultsIfNotSet() ->children() ->enumNode('default_middleware') - ->values(array(true, false, 'allow_no_handlers')) + ->values([true, false, 'allow_no_handlers']) ->defaultTrue() ->end() ->arrayNode('middleware') ->beforeNormalization() ->ifTrue(function ($v) { return \is_string($v) || (\is_array($v) && !\is_int(key($v))); }) - ->then(function ($v) { return array($v); }) + ->then(function ($v) { return [$v]; }) ->end() - ->defaultValue(array()) + ->defaultValue([]) ->arrayPrototype() ->beforeNormalization() ->always() ->then(function ($middleware): array { if (!\is_array($middleware)) { - return array('id' => $middleware); + return ['id' => $middleware]; } if (isset($middleware['id'])) { return $middleware; @@ -1122,10 +1122,10 @@ class Configuration implements ConfigurationInterface throw new \InvalidArgumentException(sprintf('Invalid middleware at path "framework.messenger": a map with a single factory id as key and its arguments as value was expected, %s given.', json_encode($middleware))); } - return array( + return [ 'id' => key($middleware), 'arguments' => current($middleware), - ); + ]; }) ->end() ->fixXmlConfig('argument') @@ -1133,7 +1133,7 @@ class Configuration implements ConfigurationInterface ->scalarNode('id')->isRequired()->cannotBeEmpty()->end() ->arrayNode('arguments') ->normalizeKeys(false) - ->defaultValue(array()) + ->defaultValue([]) ->prototype('variable') ->end() ->end() diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php index 19ba861564..87ce95e44b 100644 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php +++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php @@ -180,7 +180,7 @@ class FrameworkExtension extends Extension if (!$container->hasParameter('debug.file_link_format')) { if (!$container->hasParameter('templating.helper.code.file_link_format')) { - $links = array( + $links = [ 'textmate' => 'txmt://open?url=file://%%f&line=%%l', 'macvim' => 'mvim://open?url=file://%%f&line=%%l', 'emacs' => 'emacs://open?url=file://%%f&line=%%l', @@ -188,7 +188,7 @@ class FrameworkExtension extends Extension 'phpstorm' => 'phpstorm://open?file=%%f&line=%%l', 'atom' => 'atom://core/open/file?filename=%%f&line=%%l', 'vscode' => 'vscode://file/%%f:%%l', - ); + ]; $ide = $config['ide']; $container->setParameter('templating.helper.code.file_link_format', str_replace('%', '%%', ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format')) ?: (isset($links[$ide]) ? $links[$ide] : $ide)); @@ -301,13 +301,13 @@ class FrameworkExtension extends Extension $loader->load('web_link.xml'); } - $this->addAnnotatedClassesToCompile(array( + $this->addAnnotatedClassesToCompile([ '**\\Controller\\', '**\\Entity\\', // Added explicitly so that we don't rely on the class map being dumped to make it work 'Symfony\\Bundle\\FrameworkBundle\\Controller\\AbstractController', - )); + ]); $container->registerForAutoconfiguration(Command::class) ->addTag('console.command'); @@ -340,11 +340,11 @@ class FrameworkExtension extends Extension $container->registerForAutoconfiguration(EventSubscriberInterface::class) ->addTag('kernel.event_subscriber'); $container->registerForAutoconfiguration(ResetInterface::class) - ->addTag('kernel.reset', array('method' => 'reset')); + ->addTag('kernel.reset', ['method' => 'reset']); if (!interface_exists(MarshallerInterface::class)) { $container->registerForAutoconfiguration(ResettableInterface::class) - ->addTag('kernel.reset', array('method' => 'reset')); + ->addTag('kernel.reset', ['method' => 'reset']); } $container->registerForAutoconfiguration(PropertyListExtractorInterface::class) @@ -374,11 +374,11 @@ class FrameworkExtension extends Extension $container->registerForAutoconfiguration(TransportFactoryInterface::class) ->addTag('messenger.transport_factory'); $container->registerForAutoconfiguration(LoggerAwareInterface::class) - ->addMethodCall('setLogger', array(new Reference('logger'))); + ->addMethodCall('setLogger', [new Reference('logger')]); if (!$container->getParameter('kernel.debug')) { // remove tagged iterator argument for resource checkers - $container->getDefinition('config_cache_factory')->setArguments(array()); + $container->getDefinition('config_cache_factory')->setArguments([]); } } @@ -450,7 +450,7 @@ class FrameworkExtension extends Extension { if (!$this->isConfigEnabled($container, $config)) { // this is needed for the WebProfiler to work even if the profiler is disabled - $container->setParameter('data_collector.templates', array()); + $container->setParameter('data_collector.templates', []); return; } @@ -490,7 +490,7 @@ class FrameworkExtension extends Extension $container->getDefinition('profiler') ->addArgument($config['collect']) - ->addTag('kernel.reset', array('method' => 'reset')); + ->addTag('kernel.reset', ['method' => 'reset']); } private function registerWorkflowConfiguration(array $config, ContainerBuilder $container, XmlFileLoader $loader) @@ -514,11 +514,11 @@ class FrameworkExtension extends Extension $workflowId = sprintf('%s.%s', $type, $name); // Process Metadata (workflow + places (transition is done in the "create transition" block)) - $metadataStoreDefinition = new Definition(Workflow\Metadata\InMemoryMetadataStore::class, array(array(), array(), null)); + $metadataStoreDefinition = new Definition(Workflow\Metadata\InMemoryMetadataStore::class, [[], [], null]); if ($workflow['metadata']) { $metadataStoreDefinition->replaceArgument(0, $workflow['metadata']); } - $placesMetadata = array(); + $placesMetadata = []; foreach ($workflow['places'] as $place) { if ($place['metadata']) { $placesMetadata[$place['name']] = $place['metadata']; @@ -529,14 +529,14 @@ class FrameworkExtension extends Extension } // Create transitions - $transitions = array(); - $guardsConfiguration = array(); + $transitions = []; + $guardsConfiguration = []; $transitionsMetadataDefinition = new Definition(\SplObjectStorage::class); // Global transition counter per workflow $transitionCounter = 0; foreach ($workflow['transitions'] as $transition) { if ('workflow' === $type) { - $transitionDefinition = new Definition(Workflow\Transition::class, array($transition['name'], $transition['from'], $transition['to'])); + $transitionDefinition = new Definition(Workflow\Transition::class, [$transition['name'], $transition['from'], $transition['to']]); $transitionDefinition->setPublic(false); $transitionId = sprintf('%s.transition.%s', $workflowId, $transitionCounter++); $container->setDefinition($transitionId, $transitionDefinition); @@ -550,15 +550,15 @@ class FrameworkExtension extends Extension $guardsConfiguration[$eventName][] = $configuration; } if ($transition['metadata']) { - $transitionsMetadataDefinition->addMethodCall('attach', array( + $transitionsMetadataDefinition->addMethodCall('attach', [ new Reference($transitionId), $transition['metadata'], - )); + ]); } } elseif ('state_machine' === $type) { foreach ($transition['from'] as $from) { foreach ($transition['to'] as $to) { - $transitionDefinition = new Definition(Workflow\Transition::class, array($transition['name'], $from, $to)); + $transitionDefinition = new Definition(Workflow\Transition::class, [$transition['name'], $from, $to]); $transitionDefinition->setPublic(false); $transitionId = sprintf('%s.transition.%s', $workflowId, $transitionCounter++); $container->setDefinition($transitionId, $transitionDefinition); @@ -572,10 +572,10 @@ class FrameworkExtension extends Extension $guardsConfiguration[$eventName][] = $configuration; } if ($transition['metadata']) { - $transitionsMetadataDefinition->addMethodCall('attach', array( + $transitionsMetadataDefinition->addMethodCall('attach', [ new Reference($transitionId), $transition['metadata'], - )); + ]); } } } @@ -593,11 +593,11 @@ class FrameworkExtension extends Extension $definitionDefinition->addArgument($transitions); $definitionDefinition->addArgument($workflow['initial_place'] ?? null); $definitionDefinition->addArgument($metadataStoreDefinition); - $definitionDefinition->addTag('workflow.definition', array( + $definitionDefinition->addTag('workflow.definition', [ 'name' => $name, 'type' => $type, 'marking_store' => isset($workflow['marking_store']['type']) ? $workflow['marking_store']['type'] : null, - )); + ]); // Create MarkingStore if (isset($workflow['marking_store']['type'])) { @@ -625,22 +625,22 @@ class FrameworkExtension extends Extension // Add workflow to Registry if ($workflow['supports']) { foreach ($workflow['supports'] as $supportedClassName) { - $strategyDefinition = new Definition(Workflow\SupportStrategy\InstanceOfSupportStrategy::class, array($supportedClassName)); + $strategyDefinition = new Definition(Workflow\SupportStrategy\InstanceOfSupportStrategy::class, [$supportedClassName]); $strategyDefinition->setPublic(false); - $registryDefinition->addMethodCall('addWorkflow', array(new Reference($workflowId), $strategyDefinition)); + $registryDefinition->addMethodCall('addWorkflow', [new Reference($workflowId), $strategyDefinition]); } } elseif (isset($workflow['support_strategy'])) { - $registryDefinition->addMethodCall('addWorkflow', array(new Reference($workflowId), new Reference($workflow['support_strategy']))); + $registryDefinition->addMethodCall('addWorkflow', [new Reference($workflowId), new Reference($workflow['support_strategy'])]); } // Enable the AuditTrail if ($workflow['audit_trail']['enabled']) { $listener = new Definition(Workflow\EventListener\AuditTrailListener::class); $listener->setPrivate(true); - $listener->addTag('monolog.logger', array('channel' => 'workflow')); - $listener->addTag('kernel.event_listener', array('event' => sprintf('workflow.%s.leave', $name), 'method' => 'onLeave')); - $listener->addTag('kernel.event_listener', array('event' => sprintf('workflow.%s.transition', $name), 'method' => 'onTransition')); - $listener->addTag('kernel.event_listener', array('event' => sprintf('workflow.%s.enter', $name), 'method' => 'onEnter')); + $listener->addTag('monolog.logger', ['channel' => 'workflow']); + $listener->addTag('kernel.event_listener', ['event' => sprintf('workflow.%s.leave', $name), 'method' => 'onLeave']); + $listener->addTag('kernel.event_listener', ['event' => sprintf('workflow.%s.transition', $name), 'method' => 'onTransition']); + $listener->addTag('kernel.event_listener', ['event' => sprintf('workflow.%s.enter', $name), 'method' => 'onEnter']); $listener->addArgument(new Reference('logger')); $container->setDefinition(sprintf('%s.listener.audit_trail', $workflowId), $listener); } @@ -658,7 +658,7 @@ class FrameworkExtension extends Extension $guard = new Definition(Workflow\EventListener\GuardListener::class); $guard->setPrivate(true); - $guard->setArguments(array( + $guard->setArguments([ $guardsConfiguration, new Reference('workflow.security.expression_language'), new Reference('security.token_storage'), @@ -666,9 +666,9 @@ class FrameworkExtension extends Extension new Reference('security.authentication.trust_resolver'), new Reference('security.role_hierarchy'), new Reference('validator', ContainerInterface::NULL_ON_INVALID_REFERENCE), - )); + ]); foreach ($guardsConfiguration as $eventName => $config) { - $guard->addTag('kernel.event_listener', array('event' => $eventName, 'method' => 'onTransition')); + $guard->addTag('kernel.event_listener', ['event' => $eventName, 'method' => 'onTransition']); } $container->setDefinition(sprintf('%s.listener.guard', $workflowId), $guard); @@ -685,7 +685,7 @@ class FrameworkExtension extends Extension $container->register('debug.stopwatch', Stopwatch::class) ->addArgument(true) ->setPrivate(true) - ->addTag('kernel.reset', array('method' => 'reset')); + ->addTag('kernel.reset', ['method' => 'reset']); $container->setAlias(Stopwatch::class, new Alias('debug.stopwatch', false)); } @@ -734,7 +734,7 @@ class FrameworkExtension extends Extension $loader->load('routing.xml'); if ($config['utf8']) { - $container->getDefinition('routing.loader')->replaceArgument(2, array('utf8' => true)); + $container->getDefinition('routing.loader')->replaceArgument(2, ['utf8' => true]); } $container->setParameter('router.resource', $config['resource']); @@ -753,24 +753,24 @@ class FrameworkExtension extends Extension if ($this->annotationsConfigEnabled) { $container->register('routing.loader.annotation', AnnotatedRouteControllerLoader::class) ->setPublic(false) - ->addTag('routing.loader', array('priority' => -10)) + ->addTag('routing.loader', ['priority' => -10]) ->addArgument(new Reference('annotation_reader')); $container->register('routing.loader.annotation.directory', AnnotationDirectoryLoader::class) ->setPublic(false) - ->addTag('routing.loader', array('priority' => -10)) - ->setArguments(array( + ->addTag('routing.loader', ['priority' => -10]) + ->setArguments([ new Reference('file_locator'), new Reference('routing.loader.annotation'), - )); + ]); $container->register('routing.loader.annotation.file', AnnotationFileLoader::class) ->setPublic(false) - ->addTag('routing.loader', array('priority' => -10)) - ->setArguments(array( + ->addTag('routing.loader', ['priority' => -10]) + ->setArguments([ new Reference('file_locator'), new Reference('routing.loader.annotation'), - )); + ]); } } @@ -780,8 +780,8 @@ class FrameworkExtension extends Extension // session storage $container->setAlias('session.storage', $config['storage_id'])->setPrivate(true); - $options = array('cache_limiter' => '0'); - foreach (array('name', 'cookie_lifetime', 'cookie_path', 'cookie_domain', 'cookie_secure', 'cookie_httponly', 'cookie_samesite', 'use_cookies', 'gc_maxlifetime', 'gc_probability', 'gc_divisor') as $key) { + $options = ['cache_limiter' => '0']; + foreach (['name', 'cookie_lifetime', 'cookie_path', 'cookie_domain', 'cookie_secure', 'cookie_httponly', 'cookie_samesite', 'use_cookies', 'gc_maxlifetime', 'gc_probability', 'gc_divisor'] as $key) { if (isset($config[$key])) { $options[$key] = $config[$key]; } @@ -789,10 +789,10 @@ class FrameworkExtension extends Extension if ('auto' === ($options['cookie_secure'] ?? null)) { $locator = $container->getDefinition('session_listener')->getArgument(0); - $locator->setValues($locator->getValues() + array( + $locator->setValues($locator->getValues() + [ 'session_storage' => new Reference('session.storage', ContainerInterface::IGNORE_ON_INVALID_REFERENCE), 'request_stack' => new Reference('request_stack'), - )); + ]); } $container->setParameter('session.storage.options', $options); @@ -831,11 +831,11 @@ class FrameworkExtension extends Extension $logger = new Reference('logger', ContainerInterface::IGNORE_ON_INVALID_REFERENCE); $container->getDefinition('templating.loader.cache') - ->addTag('monolog.logger', array('channel' => 'templating')) - ->addMethodCall('setLogger', array($logger)); + ->addTag('monolog.logger', ['channel' => 'templating']) + ->addMethodCall('setLogger', [$logger]); $container->getDefinition('templating.loader.chain') - ->addTag('monolog.logger', array('channel' => 'templating')) - ->addMethodCall('setLogger', array($logger)); + ->addTag('monolog.logger', ['channel' => 'templating']) + ->addMethodCall('setLogger', [$logger]); } if (!empty($config['loaders'])) { @@ -869,13 +869,13 @@ class FrameworkExtension extends Extension } else { $templateEngineDefinition = $container->getDefinition('templating.engine.delegating'); foreach ($engines as $engine) { - $templateEngineDefinition->addMethodCall('addEngine', array($engine)); + $templateEngineDefinition->addMethodCall('addEngine', [$engine]); } $container->setAlias('templating', 'templating.engine.delegating')->setPublic(true); } $container->getDefinition('fragment.renderer.hinclude') - ->addTag('kernel.fragment_renderer', array('alias' => 'hinclude')) + ->addTag('kernel.fragment_renderer', ['alias' => 'hinclude']) ->replaceArgument(0, new Reference('templating')) ; @@ -915,7 +915,7 @@ class FrameworkExtension extends Extension $defaultPackage = $this->createPackageDefinition($config['base_path'], $config['base_urls'], $defaultVersion); $container->setDefinition('assets._default_package', $defaultPackage); - $namedPackages = array(); + $namedPackages = []; foreach ($config['packages'] as $name => $package) { if (null !== $package['version_strategy']) { $version = new Reference($package['version_strategy']); @@ -998,13 +998,13 @@ class FrameworkExtension extends Extension $container->setAlias('translator', 'translator.default')->setPublic(true); $container->setAlias('translator.formatter', new Alias($config['formatter'], false)); $translator = $container->findDefinition('translator.default'); - $translator->addMethodCall('setFallbackLocales', array($config['fallbacks'])); + $translator->addMethodCall('setFallbackLocales', [$config['fallbacks']]); $container->setParameter('translator.logging', $config['logging']); $container->setParameter('translator.default_path', $config['default_path']); // Discover translation directories - $dirs = array(); + $dirs = []; if (class_exists('Symfony\Component\Validator\Validation')) { $r = new \ReflectionClass('Symfony\Component\Validator\Validation'); @@ -1054,7 +1054,7 @@ class FrameworkExtension extends Extension // Register translation resources if ($dirs) { - $files = array(); + $files = []; $finder = Finder::create() ->followLinks() ->files() @@ -1068,7 +1068,7 @@ class FrameworkExtension extends Extension foreach ($finder as $file) { list(, $locale) = explode('.', $file->getBasename(), 3); if (!isset($files[$locale])) { - $files[$locale] = array(); + $files[$locale] = []; } $files[$locale][] = (string) $file; @@ -1076,7 +1076,7 @@ class FrameworkExtension extends Extension $options = array_merge( $translator->getArgument(4), - array('resource_files' => $files) + ['resource_files' => $files] ); $translator->replaceArgument(4, $options); @@ -1103,15 +1103,15 @@ class FrameworkExtension extends Extension $container->setParameter('validator.translation_domain', $config['translation_domain']); - $files = array('xml' => array(), 'yml' => array()); + $files = ['xml' => [], 'yml' => []]; $this->registerValidatorMapping($container, $config, $files); if (!empty($files['xml'])) { - $validatorBuilder->addMethodCall('addXmlMappings', array($files['xml'])); + $validatorBuilder->addMethodCall('addXmlMappings', [$files['xml']]); } if (!empty($files['yml'])) { - $validatorBuilder->addMethodCall('addYamlMappings', array($files['yml'])); + $validatorBuilder->addMethodCall('addYamlMappings', [$files['yml']]); } $definition = $container->findDefinition('validator.email'); @@ -1122,17 +1122,17 @@ class FrameworkExtension extends Extension throw new \LogicException('"enable_annotations" on the validator cannot be set as Annotations support is disabled.'); } - $validatorBuilder->addMethodCall('enableAnnotationMapping', array(new Reference('annotation_reader'))); + $validatorBuilder->addMethodCall('enableAnnotationMapping', [new Reference('annotation_reader')]); } if (array_key_exists('static_method', $config) && $config['static_method']) { foreach ($config['static_method'] as $methodName) { - $validatorBuilder->addMethodCall('addMethodMapping', array($methodName)); + $validatorBuilder->addMethodCall('addMethodMapping', [$methodName]); } } if (!$container->getParameter('kernel.debug')) { - $validatorBuilder->addMethodCall('setMetadataCache', array(new Reference('validator.mapping.cache.symfony'))); + $validatorBuilder->addMethodCall('setMetadataCache', [new Reference('validator.mapping.cache.symfony')]); } } @@ -1212,7 +1212,7 @@ class FrameworkExtension extends Extension if (!method_exists(AnnotationRegistry::class, 'registerUniqueLoader')) { $container->getDefinition('annotations.dummy_registry') - ->setMethodCalls(array(array('registerLoader', array('class_exists')))); + ->setMethodCalls([['registerLoader', ['class_exists']]]); } if ('none' !== $config['cache']) { @@ -1323,7 +1323,7 @@ class FrameworkExtension extends Extension $container->removeDefinition('serializer.encoder.yaml'); } - $serializerLoaders = array(); + $serializerLoaders = []; if (isset($config['enable_annotations']) && $config['enable_annotations']) { if (!$this->annotationsConfigEnabled) { throw new \LogicException('"enable_annotations" on the serializer cannot be set as Annotations support is disabled.'); @@ -1331,7 +1331,7 @@ class FrameworkExtension extends Extension $annotationLoader = new Definition( 'Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader', - array(new Reference('annotation_reader')) + [new Reference('annotation_reader')] ); $annotationLoader->setPublic(false); @@ -1339,7 +1339,7 @@ class FrameworkExtension extends Extension } $fileRecorder = function ($extension, $path) use (&$serializerLoaders) { - $definition = new Definition(\in_array($extension, array('yaml', 'yml')) ? 'Symfony\Component\Serializer\Mapping\Loader\YamlFileLoader' : 'Symfony\Component\Serializer\Mapping\Loader\XmlFileLoader', array($path)); + $definition = new Definition(\in_array($extension, ['yaml', 'yml']) ? 'Symfony\Component\Serializer\Mapping\Loader\YamlFileLoader' : 'Symfony\Component\Serializer\Mapping\Loader\XmlFileLoader', [$path]); $definition->setPublic(false); $serializerLoaders[] = $definition; }; @@ -1376,10 +1376,10 @@ class FrameworkExtension extends Extension if (!$container->getParameter('kernel.debug')) { $cacheMetadataFactory = new Definition( CacheClassMetadataFactory::class, - array( + [ new Reference('serializer.mapping.cache_class_metadata_factory.inner'), new Reference('serializer.mapping.cache.symfony'), - ) + ] ); $cacheMetadataFactory->setPublic(false); $cacheMetadataFactory->setDecoratedService('serializer.mapping.class_metadata_factory'); @@ -1392,11 +1392,11 @@ class FrameworkExtension extends Extension } if (isset($config['circular_reference_handler']) && $config['circular_reference_handler']) { - $container->getDefinition('serializer.normalizer.object')->addMethodCall('setCircularReferenceHandler', array(new Reference($config['circular_reference_handler']))); + $container->getDefinition('serializer.normalizer.object')->addMethodCall('setCircularReferenceHandler', [new Reference($config['circular_reference_handler'])]); } if ($config['max_depth_handler'] ?? false) { - $container->getDefinition('serializer.normalizer.object')->addMethodCall('setMaxDepthHandler', array(new Reference($config['max_depth_handler']))); + $container->getDefinition('serializer.normalizer.object')->addMethodCall('setMaxDepthHandler', [new Reference($config['max_depth_handler'])]); } } @@ -1411,8 +1411,8 @@ class FrameworkExtension extends Extension if (interface_exists('phpDocumentor\Reflection\DocBlockFactoryInterface')) { $definition = $container->register('property_info.php_doc_extractor', 'Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor'); $definition->setPrivate(true); - $definition->addTag('property_info.description_extractor', array('priority' => -1000)); - $definition->addTag('property_info.type_extractor', array('priority' => -1001)); + $definition->addTag('property_info.description_extractor', ['priority' => -1000]); + $definition->addTag('property_info.type_extractor', ['priority' => -1001]); } } @@ -1426,7 +1426,7 @@ class FrameworkExtension extends Extension } // Generate stores - $storeDefinitions = array(); + $storeDefinitions = []; foreach ($resourceStores as $storeDsn) { $storeDsn = $container->resolveEnvPlaceholders($storeDsn, null, $usedEnvs); switch (true) { @@ -1448,15 +1448,15 @@ class FrameworkExtension extends Extension if (!$container->hasDefinition($connectionDefinitionId = '.lock_connection.'.$container->hash($storeDsn))) { $connectionDefinition = new Definition(\stdClass::class); $connectionDefinition->setPublic(false); - $connectionDefinition->setFactory(array(AbstractAdapter::class, 'createConnection')); - $connectionDefinition->setArguments(array($storeDsn, array('lazy' => true))); + $connectionDefinition->setFactory([AbstractAdapter::class, 'createConnection']); + $connectionDefinition->setArguments([$storeDsn, ['lazy' => true]]); $container->setDefinition($connectionDefinitionId, $connectionDefinition); } $storeDefinition = new Definition(StoreInterface::class); $storeDefinition->setPublic(false); - $storeDefinition->setFactory(array(StoreFactory::class, 'createStore')); - $storeDefinition->setArguments(array(new Reference($connectionDefinitionId))); + $storeDefinition->setFactory([StoreFactory::class, 'createStore']); + $storeDefinition->setArguments([new Reference($connectionDefinitionId)]); $container->setDefinition($storeDefinitionId = '.lock.'.$resourceName.'.store.'.$container->hash($storeDsn), $storeDefinition); @@ -1486,8 +1486,8 @@ class FrameworkExtension extends Extension // Generate services for lock instances $lockDefinition = new Definition(Lock::class); $lockDefinition->setPublic(false); - $lockDefinition->setFactory(array(new Reference('lock.'.$resourceName.'.factory'), 'createLock')); - $lockDefinition->setArguments(array($resourceName)); + $lockDefinition->setFactory([new Reference('lock.'.$resourceName.'.factory'), 'createLock']); + $lockDefinition->setArguments([$resourceName]); $container->setDefinition('lock.'.$resourceName, $lockDefinition); // provide alias for default resource @@ -1539,16 +1539,16 @@ class FrameworkExtension extends Extension $config['default_bus'] = key($config['buses']); } - $defaultMiddleware = array( - 'before' => array(array('id' => 'logging')), - 'after' => array(array('id' => 'send_message'), array('id' => 'handle_message')), - ); + $defaultMiddleware = [ + 'before' => [['id' => 'logging']], + 'after' => [['id' => 'send_message'], ['id' => 'handle_message']], + ]; foreach ($config['buses'] as $busId => $bus) { $middleware = $bus['middleware']; if ($bus['default_middleware']) { if ('allow_no_handlers' === $bus['default_middleware']) { - $defaultMiddleware['after'][1]['arguments'] = array(true); + $defaultMiddleware['after'][1]['arguments'] = [true]; } else { unset($defaultMiddleware['after'][1]['arguments']); } @@ -1556,17 +1556,17 @@ class FrameworkExtension extends Extension } foreach ($middleware as $middlewareItem) { - if (!$validationConfig['enabled'] && \in_array($middlewareItem['id'], array('validation', 'messenger.middleware.validation'), true)) { + if (!$validationConfig['enabled'] && \in_array($middlewareItem['id'], ['validation', 'messenger.middleware.validation'], true)) { throw new LogicException('The Validation middleware is only available when the Validator component is installed and enabled. Try running "composer require symfony/validator".'); } } if ($container->getParameter('kernel.debug') && class_exists(Stopwatch::class)) { - array_unshift($middleware, array('id' => 'traceable', 'arguments' => array($busId))); + array_unshift($middleware, ['id' => 'traceable', 'arguments' => [$busId]]); } $container->setParameter($busId.'.middleware', $middleware); - $container->register($busId, MessageBus::class)->addArgument(array())->addTag('messenger.bus'); + $container->register($busId, MessageBus::class)->addArgument([])->addTag('messenger.bus'); if ($busId === $config['default_bus']) { $container->setAlias('message_bus', $busId)->setPublic(true); @@ -1576,28 +1576,28 @@ class FrameworkExtension extends Extension } } - $senderAliases = array(); + $senderAliases = []; foreach ($config['transports'] as $name => $transport) { if (0 === strpos($transport['dsn'], 'amqp://') && !$container->hasDefinition('messenger.transport.amqp.factory')) { throw new LogicException('The default AMQP transport is not available. Make sure you have installed and enabled the Serializer component. Try enabling it or running "composer require symfony/serializer-pack".'); } $transportDefinition = (new Definition(TransportInterface::class)) - ->setFactory(array(new Reference('messenger.transport_factory'), 'createTransport')) - ->setArguments(array($transport['dsn'], $transport['options'])) - ->addTag('messenger.receiver', array('alias' => $name)) + ->setFactory([new Reference('messenger.transport_factory'), 'createTransport']) + ->setArguments([$transport['dsn'], $transport['options']]) + ->addTag('messenger.receiver', ['alias' => $name]) ; $container->setDefinition($transportId = 'messenger.transport.'.$name, $transportDefinition); $senderAliases[$name] = $transportId; } - $messageToSendersMapping = array(); - $messagesToSendAndHandle = array(); + $messageToSendersMapping = []; + $messagesToSendAndHandle = []; foreach ($config['routing'] as $message => $messageConfiguration) { if ('*' !== $message && !class_exists($message) && !interface_exists($message, false)) { throw new LogicException(sprintf('Invalid Messenger routing configuration: class or interface "%s" not found.', $message)); } - $senders = array(); + $senders = []; foreach ($messageConfiguration['senders'] as $sender) { $senders[$sender] = new Reference($senderAliases[$sender] ?? $sender); } @@ -1630,24 +1630,24 @@ class FrameworkExtension extends Extension // Inline any env vars referenced in the parameter $container->setParameter('cache.prefix.seed', $container->resolveEnvPlaceholders($container->getParameter('cache.prefix.seed'), true)); } - foreach (array('doctrine', 'psr6', 'redis', 'memcached', 'pdo') as $name) { + foreach (['doctrine', 'psr6', 'redis', 'memcached', 'pdo'] as $name) { if (isset($config[$name = 'default_'.$name.'_provider'])) { $container->setAlias('cache.'.$name, new Alias(CachePoolPass::getServiceProvider($container, $config[$name]), false)); } } - foreach (array('app', 'system') as $name) { - $config['pools']['cache.'.$name] = array( + foreach (['app', 'system'] as $name) { + $config['pools']['cache.'.$name] = [ 'adapter' => $config[$name], 'public' => true, 'tags' => false, - ); + ]; } foreach ($config['pools'] as $name => $pool) { if ($config['pools'][$pool['adapter']]['tags'] ?? false) { $pool['adapter'] = '.'.$pool['adapter'].'.inner'; } $definition = new ChildDefinition($pool['adapter']); - if (!\in_array($name, array('cache.app', 'cache.system'), true)) { + if (!\in_array($name, ['cache.app', 'cache.system'], true)) { $container->registerAliasForArgument($name, CacheInterface::class); $container->registerAliasForArgument($name, CacheItemPoolInterface::class); } @@ -1678,13 +1678,13 @@ class FrameworkExtension extends Extension $propertyAccessDefinition->setPublic(false); if (!$container->getParameter('kernel.debug')) { - $propertyAccessDefinition->setFactory(array(PropertyAccessor::class, 'createCache')); - $propertyAccessDefinition->setArguments(array(null, null, $version, new Reference('logger', ContainerInterface::IGNORE_ON_INVALID_REFERENCE))); - $propertyAccessDefinition->addTag('cache.pool', array('clearer' => 'cache.system_clearer')); - $propertyAccessDefinition->addTag('monolog.logger', array('channel' => 'cache')); + $propertyAccessDefinition->setFactory([PropertyAccessor::class, 'createCache']); + $propertyAccessDefinition->setArguments([null, null, $version, new Reference('logger', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)]); + $propertyAccessDefinition->addTag('cache.pool', ['clearer' => 'cache.system_clearer']); + $propertyAccessDefinition->addTag('monolog.logger', ['channel' => 'cache']); } else { $propertyAccessDefinition->setClass(ArrayAdapter::class); - $propertyAccessDefinition->setArguments(array(0, false)); + $propertyAccessDefinition->setArguments([0, false]); } } } diff --git a/src/Symfony/Bundle/FrameworkBundle/Routing/DelegatingLoader.php b/src/Symfony/Bundle/FrameworkBundle/Routing/DelegatingLoader.php index 84e237626c..1e6b90a9bf 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Routing/DelegatingLoader.php +++ b/src/Symfony/Bundle/FrameworkBundle/Routing/DelegatingLoader.php @@ -34,7 +34,7 @@ class DelegatingLoader extends BaseDelegatingLoader * @param ControllerNameParser $parser A ControllerNameParser instance * @param LoaderResolverInterface $resolver A LoaderResolverInterface instance */ - public function __construct(ControllerNameParser $parser, LoaderResolverInterface $resolver, array $defaultOptions = array()) + public function __construct(ControllerNameParser $parser, LoaderResolverInterface $resolver, array $defaultOptions = []) { $this->parser = $parser; $this->defaultOptions = $defaultOptions; diff --git a/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/StopwatchHelper.php b/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/StopwatchHelper.php index e15273c385..1b16d47dbb 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/StopwatchHelper.php +++ b/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/StopwatchHelper.php @@ -33,7 +33,7 @@ class StopwatchHelper extends Helper return 'stopwatch'; } - public function __call($method, $arguments = array()) + public function __call($method, $arguments = []) { if (null !== $this->stopwatch) { if (method_exists($this->stopwatch, $method)) { diff --git a/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/TranslatorHelper.php b/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/TranslatorHelper.php index 19829a26e8..22fed9921b 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/TranslatorHelper.php +++ b/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/TranslatorHelper.php @@ -61,10 +61,10 @@ class TranslatorHelper extends Helper @trigger_error(sprintf('The "%s()" method is deprecated since Symfony 4.2, use the trans() one instead with a "%count%" parameter.', __METHOD__), E_USER_DEPRECATED); if (null === $this->translator) { - return $this->doTrans($id, array('%count%' => $number) + $parameters, $domain, $locale); + return $this->doTrans($id, ['%count%' => $number] + $parameters, $domain, $locale); } if ($this->translator instanceof TranslatorInterface) { - return $this->translator->trans($id, array('%count%' => $number) + $parameters, $domain, $locale); + return $this->translator->trans($id, ['%count%' => $number] + $parameters, $domain, $locale); } return $this->translator->transChoice($id, $number, $parameters, $domain, $locale); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/CacheWarmer/SerializerCacheWarmerTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/CacheWarmer/SerializerCacheWarmerTest.php index 4c7c1c929a..ccaa64931b 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/CacheWarmer/SerializerCacheWarmerTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/CacheWarmer/SerializerCacheWarmerTest.php @@ -27,10 +27,10 @@ class SerializerCacheWarmerTest extends TestCase $this->markTestSkipped('The Serializer default cache warmer has been introduced in the Serializer Component version 3.2.'); } - $loaders = array( + $loaders = [ new XmlFileLoader(__DIR__.'/../Fixtures/Serialization/Resources/person.xml'), new YamlFileLoader(__DIR__.'/../Fixtures/Serialization/Resources/author.yml'), - ); + ]; $file = sys_get_temp_dir().'/cache-serializer.php'; @unlink($file); @@ -55,7 +55,7 @@ class SerializerCacheWarmerTest extends TestCase $file = sys_get_temp_dir().'/cache-serializer-without-loader.php'; @unlink($file); - $warmer = new SerializerCacheWarmer(array(), $file); + $warmer = new SerializerCacheWarmer([], $file); $warmer->warmUp(\dirname($file)); $this->assertFileExists($file); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/TranslationDebugCommandTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/TranslationDebugCommandTest.php index a082e01401..400f994d2f 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/TranslationDebugCommandTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/TranslationDebugCommandTest.php @@ -26,24 +26,24 @@ class TranslationDebugCommandTest extends TestCase public function testDebugMissingMessages() { - $tester = $this->createCommandTester(array('foo' => 'foo')); - $tester->execute(array('locale' => 'en', 'bundle' => 'foo')); + $tester = $this->createCommandTester(['foo' => 'foo']); + $tester->execute(['locale' => 'en', 'bundle' => 'foo']); $this->assertRegExp('/missing/', $tester->getDisplay()); } public function testDebugUnusedMessages() { - $tester = $this->createCommandTester(array(), array('foo' => 'foo')); - $tester->execute(array('locale' => 'en', 'bundle' => 'foo')); + $tester = $this->createCommandTester([], ['foo' => 'foo']); + $tester->execute(['locale' => 'en', 'bundle' => 'foo']); $this->assertRegExp('/unused/', $tester->getDisplay()); } public function testDebugFallbackMessages() { - $tester = $this->createCommandTester(array(), array('foo' => 'foo')); - $tester->execute(array('locale' => 'fr', 'bundle' => 'foo')); + $tester = $this->createCommandTester([], ['foo' => 'foo']); + $tester->execute(['locale' => 'fr', 'bundle' => 'foo']); $this->assertRegExp('/fallback/', $tester->getDisplay()); } @@ -51,15 +51,15 @@ class TranslationDebugCommandTest extends TestCase public function testNoDefinedMessages() { $tester = $this->createCommandTester(); - $tester->execute(array('locale' => 'fr', 'bundle' => 'test')); + $tester->execute(['locale' => 'fr', 'bundle' => 'test']); $this->assertRegExp('/No defined or extracted messages for locale "fr"/', $tester->getDisplay()); } public function testDebugDefaultDirectory() { - $tester = $this->createCommandTester(array('foo' => 'foo'), array('bar' => 'bar')); - $tester->execute(array('locale' => 'en')); + $tester = $this->createCommandTester(['foo' => 'foo'], ['bar' => 'bar']); + $tester->execute(['locale' => 'en']); $this->assertRegExp('/missing/', $tester->getDisplay()); $this->assertRegExp('/unused/', $tester->getDisplay()); @@ -75,8 +75,8 @@ class TranslationDebugCommandTest extends TestCase $this->fs->mkdir($this->translationDir.'/Resources/translations'); $this->fs->mkdir($this->translationDir.'/Resources/views'); - $tester = $this->createCommandTester(array('foo' => 'foo'), array('bar' => 'bar')); - $tester->execute(array('locale' => 'en')); + $tester = $this->createCommandTester(['foo' => 'foo'], ['bar' => 'bar']); + $tester->execute(['locale' => 'en']); $this->assertRegExp('/missing/', $tester->getDisplay()); $this->assertRegExp('/unused/', $tester->getDisplay()); @@ -90,8 +90,8 @@ class TranslationDebugCommandTest extends TestCase $this->fs->mkdir($this->translationDir.'/translations'); $this->fs->mkdir($this->translationDir.'/templates'); - $tester = $this->createCommandTester(array('foo' => 'foo'), array('bar' => 'bar')); - $tester->execute(array('locale' => 'en')); + $tester = $this->createCommandTester(['foo' => 'foo'], ['bar' => 'bar']); + $tester->execute(['locale' => 'en']); $this->assertRegExp('/missing/', $tester->getDisplay()); $this->assertRegExp('/unused/', $tester->getDisplay()); @@ -107,8 +107,8 @@ class TranslationDebugCommandTest extends TestCase ->with($this->equalTo($this->translationDir.'/customDir')) ->willThrowException(new \InvalidArgumentException()); - $tester = $this->createCommandTester(array('foo' => 'foo'), array('bar' => 'bar'), $kernel); - $tester->execute(array('locale' => 'en', 'bundle' => $this->translationDir.'/customDir')); + $tester = $this->createCommandTester(['foo' => 'foo'], ['bar' => 'bar'], $kernel); + $tester->execute(['locale' => 'en', 'bundle' => $this->translationDir.'/customDir']); $this->assertRegExp('/missing/', $tester->getDisplay()); $this->assertRegExp('/unused/', $tester->getDisplay()); @@ -125,8 +125,8 @@ class TranslationDebugCommandTest extends TestCase ->with($this->equalTo('dir')) ->willThrowException(new \InvalidArgumentException()); - $tester = $this->createCommandTester(array(), array(), $kernel); - $tester->execute(array('locale' => 'en', 'bundle' => 'dir')); + $tester = $this->createCommandTester([], [], $kernel); + $tester->execute(['locale' => 'en', 'bundle' => 'dir']); } protected function setUp() @@ -145,7 +145,7 @@ class TranslationDebugCommandTest extends TestCase /** * @return CommandTester */ - private function createCommandTester($extractedMessages = array(), $loadedMessages = array(), $kernel = null) + private function createCommandTester($extractedMessages = [], $loadedMessages = [], $kernel = null) { $translator = $this->getMockBuilder('Symfony\Component\Translation\Translator') ->disableOriginalConstructor() @@ -154,7 +154,7 @@ class TranslationDebugCommandTest extends TestCase $translator ->expects($this->any()) ->method('getFallbackLocales') - ->will($this->returnValue(array('en'))); + ->will($this->returnValue(['en'])); $extractor = $this->getMockBuilder('Symfony\Component\Translation\Extractor\ExtractorInterface')->getMock(); $extractor @@ -177,15 +177,15 @@ class TranslationDebugCommandTest extends TestCase ); if (null === $kernel) { - $returnValues = array( - array('foo', $this->getBundle($this->translationDir)), - array('test', $this->getBundle('test')), - ); + $returnValues = [ + ['foo', $this->getBundle($this->translationDir)], + ['test', $this->getBundle('test')], + ]; if (HttpKernel\Kernel::VERSION_ID < 40000) { - $returnValues = array( - array('foo', true, $this->getBundle($this->translationDir)), - array('test', true, $this->getBundle('test')), - ); + $returnValues = [ + ['foo', true, $this->getBundle($this->translationDir)], + ['test', true, $this->getBundle('test')], + ]; } $kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock(); $kernel @@ -197,7 +197,7 @@ class TranslationDebugCommandTest extends TestCase $kernel ->expects($this->any()) ->method('getBundles') - ->will($this->returnValue(array())); + ->will($this->returnValue([])); $container = new Container(); $container->setParameter('kernel.root_dir', $this->translationDir); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/TranslationUpdateCommandTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/TranslationUpdateCommandTest.php index 40ade53e27..b1a957201f 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/TranslationUpdateCommandTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/TranslationUpdateCommandTest.php @@ -93,8 +93,8 @@ class TranslationUpdateCommandTest extends TestCase $this->fs->mkdir($this->translationDir.'/Resources/translations'); $this->fs->mkdir($this->translationDir.'/Resources/views'); - $tester = $this->createCommandTester(array('messages' => array('foo' => 'foo'))); - $tester->execute(array('command' => 'translation:update', 'locale' => 'en', '--force' => true)); + $tester = $this->createCommandTester(['messages' => ['foo' => 'foo']]); + $tester->execute(['command' => 'translation:update', 'locale' => 'en', '--force' => true]); $this->assertRegExp('/Translation files were successfully updated./', $tester->getDisplay()); } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Console/Descriptor/AbstractDescriptorTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Console/Descriptor/AbstractDescriptorTest.php index 0a1368a4d1..33b0cb6375 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Console/Descriptor/AbstractDescriptorTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Console/Descriptor/AbstractDescriptorTest.php @@ -203,12 +203,12 @@ abstract class AbstractDescriptorTest extends TestCase public function getClassDescriptionTestData() { - return array( - array(ClassWithDocCommentOnMultipleLines::class, 'This is the first line of the description. This is the second line.'), - array(ClassWithDocCommentWithoutInitialSpace::class, 'Foo.'), - array(ClassWithoutDocComment::class, ''), - array(ClassWithDocComment::class, 'This is a class with a doc comment.'), - ); + return [ + [ClassWithDocCommentOnMultipleLines::class, 'This is the first line of the description. This is the second line.'], + [ClassWithDocCommentWithoutInitialSpace::class, 'Foo.'], + [ClassWithoutDocComment::class, ''], + [ClassWithDocComment::class, 'This is a class with a doc comment.'], + ]; } abstract protected function getDescriptor(); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Console/Descriptor/ObjectsProvider.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Console/Descriptor/ObjectsProvider.php index 58b1d29227..caafff6842 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Console/Descriptor/ObjectsProvider.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Console/Descriptor/ObjectsProvider.php @@ -98,10 +98,10 @@ class ObjectsProvider public static function getContainerDefinitionsWithExistingClasses() { - return array( + return [ 'existing_class_def_1' => new Definition(ClassWithDocComment::class), 'existing_class_def_2' => new Definition(ClassWithoutDocComment::class), - ); + ]; } public static function getContainerDefinitions() diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/CachePoolClearerPassTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/CachePoolClearerPassTest.php index 67aa34cf5b..494cf6f094 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/CachePoolClearerPassTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/CachePoolClearerPassTest.php @@ -37,18 +37,18 @@ class CachePoolClearerPassTest extends TestCase $publicPool = new Definition(); $publicPool->addArgument('namespace'); - $publicPool->addTag('cache.pool', array('clearer' => 'clearer_alias')); + $publicPool->addTag('cache.pool', ['clearer' => 'clearer_alias']); $container->setDefinition('public.pool', $publicPool); $publicPool = new Definition(); $publicPool->addArgument('namespace'); - $publicPool->addTag('cache.pool', array('clearer' => 'clearer_alias', 'name' => 'pool2')); + $publicPool->addTag('cache.pool', ['clearer' => 'clearer_alias', 'name' => 'pool2']); $container->setDefinition('public.pool2', $publicPool); $privatePool = new Definition(); $privatePool->setPublic(false); $privatePool->addArgument('namespace'); - $privatePool->addTag('cache.pool', array('clearer' => 'clearer_alias')); + $privatePool->addTag('cache.pool', ['clearer' => 'clearer_alias']); $container->setDefinition('private.pool', $privatePool); $clearer = new Definition(); @@ -58,18 +58,18 @@ class CachePoolClearerPassTest extends TestCase $pass = new RemoveUnusedDefinitionsPass(); foreach ($container->getCompiler()->getPassConfig()->getRemovingPasses() as $removingPass) { if ($removingPass instanceof RepeatedPass) { - $pass->setRepeatedPass(new RepeatedPass(array($pass))); + $pass->setRepeatedPass(new RepeatedPass([$pass])); break; } } - foreach (array(new CachePoolPass(), $pass, new CachePoolClearerPass()) as $pass) { + foreach ([new CachePoolPass(), $pass, new CachePoolClearerPass()] as $pass) { $pass->process($container); } - $expected = array(array( + $expected = [[ 'public.pool' => new Reference('public.pool'), 'pool2' => new Reference('public.pool2'), - )); + ]]; $this->assertEquals($expected, $clearer->getArguments()); $this->assertEquals($expected, $globalClearer->getArguments()); } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/CachePoolPassTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/CachePoolPassTest.php index 087f07854e..747e29ffef 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/CachePoolPassTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/CachePoolPassTest.php @@ -97,10 +97,10 @@ class CachePoolPassTest extends TestCase $container->setParameter('kernel.container_class', 'app'); $container->setParameter('cache.prefix.seed', 'foo'); $cachePool = new Definition(); - $cachePool->addTag('cache.pool', array( + $cachePool->addTag('cache.pool', [ 'name' => 'foobar', 'provider' => 'foobar', - )); + ]); $cachePool->addArgument(null); $cachePool->addArgument(null); $cachePool->addArgument(null); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/DataCollectorTranslatorPassTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/DataCollectorTranslatorPassTest.php index 481500c2cb..4496c7927e 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/DataCollectorTranslatorPassTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/DataCollectorTranslatorPassTest.php @@ -33,11 +33,11 @@ class DataCollectorTranslatorPassTest extends TestCase $this->container->register('translator.data_collector', 'Symfony\Component\Translation\DataCollectorTranslator') ->setPublic(false) ->setDecoratedService('translator') - ->setArguments(array(new Reference('translator.data_collector.inner'))) + ->setArguments([new Reference('translator.data_collector.inner')]) ; $this->container->register('data_collector.translation', 'Symfony\Component\Translation\DataCollector\TranslationDataCollector') - ->setArguments(array(new Reference('translator.data_collector'))) + ->setArguments([new Reference('translator.data_collector')]) ; } @@ -67,10 +67,10 @@ class DataCollectorTranslatorPassTest extends TestCase public function getImplementingTranslatorBagInterfaceTranslatorClassNames() { - return array( - array('Symfony\Component\Translation\Translator'), - array('%translator_implementing_bag%'), - ); + return [ + ['Symfony\Component\Translation\Translator'], + ['%translator_implementing_bag%'], + ]; } /** @@ -99,16 +99,16 @@ class DataCollectorTranslatorPassTest extends TestCase public function getNotImplementingTranslatorBagInterfaceTranslatorClassNames() { - return array( - array('Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler\TranslatorWithTranslatorBag'), - array('%translator_not_implementing_bag%'), - ); + return [ + ['Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler\TranslatorWithTranslatorBag'], + ['%translator_not_implementing_bag%'], + ]; } } class TranslatorWithTranslatorBag implements TranslatorInterface { - public function trans($id, array $parameters = array(), $domain = null, $locale = null) + public function trans($id, array $parameters = [], $domain = null, $locale = null) { } } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/ConfigurationTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/ConfigurationTest.php index 9a3b2183e1..453ccf449d 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/ConfigurationTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/ConfigurationTest.php @@ -26,35 +26,35 @@ class ConfigurationTest extends TestCase public function testDefaultConfig() { $processor = new Processor(); - $config = $processor->processConfiguration(new Configuration(true), array(array('secret' => 's3cr3t'))); + $config = $processor->processConfiguration(new Configuration(true), [['secret' => 's3cr3t']]); $this->assertEquals( - array_merge(array('secret' => 's3cr3t', 'trusted_hosts' => array()), self::getBundleDefaultConfig()), + array_merge(['secret' => 's3cr3t', 'trusted_hosts' => []], self::getBundleDefaultConfig()), $config ); } public function testDoNoDuplicateDefaultFormResources() { - $input = array('templating' => array( - 'form' => array('resources' => array('FrameworkBundle:Form')), - 'engines' => array('php'), - )); + $input = ['templating' => [ + 'form' => ['resources' => ['FrameworkBundle:Form']], + 'engines' => ['php'], + ]]; $processor = new Processor(); - $config = $processor->processConfiguration(new Configuration(true), array($input)); + $config = $processor->processConfiguration(new Configuration(true), [$input]); - $this->assertEquals(array('FrameworkBundle:Form'), $config['templating']['form']['resources']); + $this->assertEquals(['FrameworkBundle:Form'], $config['templating']['form']['resources']); } public function getTestValidSessionName() { - return array( - array(null), - array('PHPSESSID'), - array('a&b'), - array(',_-!@#$%^*(){}:<>/?'), - ); + return [ + [null], + ['PHPSESSID'], + ['a&b'], + [',_-!@#$%^*(){}:<>/?'], + ]; } /** @@ -66,38 +66,38 @@ class ConfigurationTest extends TestCase $processor = new Processor(); $processor->processConfiguration( new Configuration(true), - array(array('session' => array('name' => $sessionName))) + [['session' => ['name' => $sessionName]]] ); } public function getTestInvalidSessionName() { - return array( - array('a.b'), - array('a['), - array('a[]'), - array('a[b]'), - array('a=b'), - array('a+b'), - ); + return [ + ['a.b'], + ['a['], + ['a[]'], + ['a[b]'], + ['a=b'], + ['a+b'], + ]; } public function testAssetsCanBeEnabled() { $processor = new Processor(); $configuration = new Configuration(true); - $config = $processor->processConfiguration($configuration, array(array('assets' => null))); + $config = $processor->processConfiguration($configuration, [['assets' => null]]); - $defaultConfig = array( + $defaultConfig = [ 'enabled' => true, 'version_strategy' => null, 'version' => null, 'version_format' => '%%s?%%s', 'base_path' => '', - 'base_urls' => array(), - 'packages' => array(), + 'base_urls' => [], + 'packages' => [], 'json_manifest_path' => null, - ); + ]; $this->assertEquals($defaultConfig, $config['assets']); } @@ -116,120 +116,120 @@ class ConfigurationTest extends TestCase $processor = new Processor(); $configuration = new Configuration(true); - $processor->processConfiguration($configuration, array( - array( + $processor->processConfiguration($configuration, [ + [ 'assets' => $assetConfig, - ), - )); + ], + ]); } public function provideInvalidAssetConfigurationTests() { // helper to turn config into embedded package config $createPackageConfig = function (array $packageConfig) { - return array( + return [ 'base_urls' => '//example.com', 'version' => 1, - 'packages' => array( + 'packages' => [ 'foo' => $packageConfig, - ), - ); + ], + ]; }; - $config = array( + $config = [ 'version' => 1, 'version_strategy' => 'foo', - ); - yield array($config, 'You cannot use both "version_strategy" and "version" at the same time under "assets".'); - yield array($createPackageConfig($config), 'You cannot use both "version_strategy" and "version" at the same time under "assets" packages.'); + ]; + yield [$config, 'You cannot use both "version_strategy" and "version" at the same time under "assets".']; + yield [$createPackageConfig($config), 'You cannot use both "version_strategy" and "version" at the same time under "assets" packages.']; - $config = array( + $config = [ 'json_manifest_path' => '/foo.json', 'version_strategy' => 'foo', - ); - yield array($config, 'You cannot use both "version_strategy" and "json_manifest_path" at the same time under "assets".'); - yield array($createPackageConfig($config), 'You cannot use both "version_strategy" and "json_manifest_path" at the same time under "assets" packages.'); + ]; + yield [$config, 'You cannot use both "version_strategy" and "json_manifest_path" at the same time under "assets".']; + yield [$createPackageConfig($config), 'You cannot use both "version_strategy" and "json_manifest_path" at the same time under "assets" packages.']; - $config = array( + $config = [ 'json_manifest_path' => '/foo.json', 'version' => '1', - ); - yield array($config, 'You cannot use both "version" and "json_manifest_path" at the same time under "assets".'); - yield array($createPackageConfig($config), 'You cannot use both "version" and "json_manifest_path" at the same time under "assets" packages.'); + ]; + yield [$config, 'You cannot use both "version" and "json_manifest_path" at the same time under "assets".']; + yield [$createPackageConfig($config), 'You cannot use both "version" and "json_manifest_path" at the same time under "assets" packages.']; } protected static function getBundleDefaultConfig() { - return array( + return [ 'http_method_override' => true, 'ide' => null, 'default_locale' => 'en', - 'csrf_protection' => array( + 'csrf_protection' => [ 'enabled' => false, - ), - 'form' => array( + ], + 'form' => [ 'enabled' => !class_exists(FullStack::class), - 'csrf_protection' => array( + 'csrf_protection' => [ 'enabled' => null, // defaults to csrf_protection.enabled 'field_name' => '_token', - ), - ), - 'esi' => array('enabled' => false), - 'ssi' => array('enabled' => false), - 'fragments' => array( + ], + ], + 'esi' => ['enabled' => false], + 'ssi' => ['enabled' => false], + 'fragments' => [ 'enabled' => false, 'path' => '/_fragment', - ), - 'profiler' => array( + ], + 'profiler' => [ 'enabled' => false, 'only_exceptions' => false, 'only_master_requests' => false, 'dsn' => 'file:%kernel.cache_dir%/profiler', 'collect' => true, - ), - 'translator' => array( + ], + 'translator' => [ 'enabled' => !class_exists(FullStack::class), - 'fallbacks' => array('en'), + 'fallbacks' => ['en'], 'logging' => false, 'formatter' => 'translator.formatter.default', - 'paths' => array(), + 'paths' => [], 'default_path' => '%kernel.project_dir%/translations', - ), - 'validation' => array( + ], + 'validation' => [ 'enabled' => !class_exists(FullStack::class), 'enable_annotations' => !class_exists(FullStack::class), - 'static_method' => array('loadValidatorMetadata'), + 'static_method' => ['loadValidatorMetadata'], 'translation_domain' => 'validators', - 'mapping' => array( - 'paths' => array(), - ), - ), - 'annotations' => array( + 'mapping' => [ + 'paths' => [], + ], + ], + 'annotations' => [ 'cache' => 'php_array', 'file_cache_dir' => '%kernel.cache_dir%/annotations', 'debug' => true, 'enabled' => true, - ), - 'serializer' => array( + ], + 'serializer' => [ 'enabled' => !class_exists(FullStack::class), 'enable_annotations' => !class_exists(FullStack::class), - 'mapping' => array('paths' => array()), - ), - 'property_access' => array( + 'mapping' => ['paths' => []], + ], + 'property_access' => [ 'magic_call' => false, 'throw_exception_on_invalid_index' => false, - ), - 'property_info' => array( + ], + 'property_info' => [ 'enabled' => !class_exists(FullStack::class), - ), - 'router' => array( + ], + 'router' => [ 'enabled' => false, 'http_port' => 80, 'https_port' => 443, 'strict_requirements' => true, 'utf8' => false, - ), - 'session' => array( + ], + 'session' => [ 'enabled' => false, 'storage_id' => 'session.storage.native', 'handler_id' => 'session.handler.native_file', @@ -238,70 +238,70 @@ class ConfigurationTest extends TestCase 'gc_probability' => 1, 'save_path' => '%kernel.cache_dir%/sessions', 'metadata_update_threshold' => 0, - ), - 'request' => array( + ], + 'request' => [ 'enabled' => false, - 'formats' => array(), - ), - 'templating' => array( + 'formats' => [], + ], + 'templating' => [ 'enabled' => false, 'hinclude_default_template' => null, - 'form' => array( - 'resources' => array('FrameworkBundle:Form'), - ), - 'engines' => array(), - 'loaders' => array(), - ), - 'assets' => array( + 'form' => [ + 'resources' => ['FrameworkBundle:Form'], + ], + 'engines' => [], + 'loaders' => [], + ], + 'assets' => [ 'enabled' => !class_exists(FullStack::class), 'version_strategy' => null, 'version' => null, 'version_format' => '%%s?%%s', 'base_path' => '', - 'base_urls' => array(), - 'packages' => array(), + 'base_urls' => [], + 'packages' => [], 'json_manifest_path' => null, - ), - 'cache' => array( - 'pools' => array(), + ], + 'cache' => [ + 'pools' => [], 'app' => 'cache.adapter.filesystem', 'system' => 'cache.adapter.system', 'directory' => '%kernel.cache_dir%/pools', 'default_redis_provider' => 'redis://localhost', 'default_memcached_provider' => 'memcached://localhost', 'default_pdo_provider' => class_exists(Connection::class) ? 'database_connection' : null, - ), - 'workflows' => array( + ], + 'workflows' => [ 'enabled' => false, - 'workflows' => array(), - ), - 'php_errors' => array( + 'workflows' => [], + ], + 'php_errors' => [ 'log' => true, 'throw' => true, - ), - 'web_link' => array( + ], + 'web_link' => [ 'enabled' => !class_exists(FullStack::class), - ), - 'lock' => array( + ], + 'lock' => [ 'enabled' => !class_exists(FullStack::class), - 'resources' => array( - 'default' => array( + 'resources' => [ + 'default' => [ class_exists(SemaphoreStore::class) && SemaphoreStore::isSupported() ? 'semaphore' : 'flock', - ), - ), - ), - 'messenger' => array( + ], + ], + ], + 'messenger' => [ 'enabled' => !class_exists(FullStack::class) && interface_exists(MessageBusInterface::class), - 'routing' => array(), - 'transports' => array(), - 'serializer' => array( + 'routing' => [], + 'transports' => [], + 'serializer' => [ 'id' => !class_exists(FullStack::class) && class_exists(Serializer::class) ? 'messenger.transport.symfony_serializer' : null, 'format' => 'json', - 'context' => array(), - ), + 'context' => [], + ], 'default_bus' => null, - 'buses' => array('messenger.bus.default' => array('default_middleware' => true, 'middleware' => array())), - ), - ); + 'buses' => ['messenger.bus.default' => ['default_middleware' => true, 'middleware' => []]], + ], + ]; } } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/messenger_amqp_transport_no_serializer.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/messenger_amqp_transport_no_serializer.php index 6c9ce5fc0a..10d31660f9 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/messenger_amqp_transport_no_serializer.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/messenger_amqp_transport_no_serializer.php @@ -1,10 +1,10 @@ loadFromExtension('framework', array( - 'messenger' => array( +$container->loadFromExtension('framework', [ + 'messenger' => [ 'serializer' => false, - 'transports' => array( + 'transports' => [ 'default' => 'amqp://localhost/%2f/messages', - ), - ), -)); + ], + ], +]); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/messenger_multiple_buses.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/messenger_multiple_buses.php index f500ff9573..627e21f308 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/messenger_multiple_buses.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/messenger_multiple_buses.php @@ -1,22 +1,22 @@ loadFromExtension('framework', array( - 'messenger' => array( +$container->loadFromExtension('framework', [ + 'messenger' => [ 'default_bus' => 'messenger.bus.commands', - 'buses' => array( + 'buses' => [ 'messenger.bus.commands' => null, - 'messenger.bus.events' => array( - 'middleware' => array( - array('with_factory' => array('foo', true, array('bar' => 'baz'))), - ), - ), - 'messenger.bus.queries' => array( + 'messenger.bus.events' => [ + 'middleware' => [ + ['with_factory' => ['foo', true, ['bar' => 'baz']]], + ], + ], + 'messenger.bus.queries' => [ 'default_middleware' => false, - 'middleware' => array( + 'middleware' => [ 'send_message', 'handle_message', - ), - ), - ), - ), -)); + ], + ], + ], + ], +]); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/messenger_routing.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/messenger_routing.php index 60b68f1fdb..08aae8f27d 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/messenger_routing.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/messenger_routing.php @@ -1,19 +1,19 @@ loadFromExtension('framework', array( +$container->loadFromExtension('framework', [ 'serializer' => true, - 'messenger' => array( + 'messenger' => [ 'serializer' => 'messenger.transport.symfony_serializer', - 'routing' => array( - 'Symfony\Component\Messenger\Tests\Fixtures\DummyMessage' => array('amqp', 'audit'), - 'Symfony\Component\Messenger\Tests\Fixtures\SecondMessage' => array( - 'senders' => array('amqp', 'audit'), + 'routing' => [ + 'Symfony\Component\Messenger\Tests\Fixtures\DummyMessage' => ['amqp', 'audit'], + 'Symfony\Component\Messenger\Tests\Fixtures\SecondMessage' => [ + 'senders' => ['amqp', 'audit'], 'send_and_handle' => true, - ), + ], '*' => 'amqp', - ), - 'transports' => array( + ], + 'transports' => [ 'amqp' => 'amqp://localhost/%2f/messages', - ), - ), -)); + ], + ], +]); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/messenger_transport.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/messenger_transport.php index 728a1a910c..cab5efe30a 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/messenger_transport.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/messenger_transport.php @@ -1,15 +1,15 @@ loadFromExtension('framework', array( +$container->loadFromExtension('framework', [ 'serializer' => true, - 'messenger' => array( - 'serializer' => array( + 'messenger' => [ + 'serializer' => [ 'id' => 'messenger.transport.symfony_serializer', 'format' => 'csv', - 'context' => array('enable_max_depth' => true), - ), - 'transports' => array( + 'context' => ['enable_max_depth' => true], + ], + 'transports' => [ 'default' => 'amqp://localhost/%2f/messages', - ), - ), -)); + ], + ], +]); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/messenger_transport_no_serializer.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/messenger_transport_no_serializer.php index f861e25690..7580c3c1e5 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/messenger_transport_no_serializer.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/messenger_transport_no_serializer.php @@ -1,13 +1,13 @@ loadFromExtension('framework', array( - 'serializer' => array( +$container->loadFromExtension('framework', [ + 'serializer' => [ 'enabled' => false, - ), - 'messenger' => array( + ], + 'messenger' => [ 'serializer' => 'messenger.transport.symfony_serializer', - 'transports' => array( + 'transports' => [ 'default' => 'amqp://localhost/%2f/messages', - ), - ), -)); + ], + ], +]); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/messenger_transports.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/messenger_transports.php index 4edc0d880a..fd4b6feee7 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/messenger_transports.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/messenger_transports.php @@ -1,15 +1,15 @@ loadFromExtension('framework', array( +$container->loadFromExtension('framework', [ 'serializer' => true, - 'messenger' => array( + 'messenger' => [ 'serializer' => 'messenger.transport.symfony_serializer', - 'transports' => array( + 'transports' => [ 'default' => 'amqp://localhost/%2f/messages', - 'customised' => array( + 'customised' => [ 'dsn' => 'amqp://localhost/%2f/messages?exchange_name=exchange_name', - 'options' => array('queue' => array('name' => 'Queue')), - ), - ), - ), -)); + 'options' => ['queue' => ['name' => 'Queue']], + ], + ], + ], +]); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/serializer_disabled.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/serializer_disabled.php index dedd090beb..937a07c225 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/serializer_disabled.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/serializer_disabled.php @@ -1,7 +1,7 @@ loadFromExtension('framework', array( - 'serializer' => array( +$container->loadFromExtension('framework', [ + 'serializer' => [ 'enabled' => false, - ), -)); + ], +]); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/session_cookie_secure_auto.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/session_cookie_secure_auto.php index b23f2a5cd3..7259b07f92 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/session_cookie_secure_auto.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/session_cookie_secure_auto.php @@ -1,8 +1,8 @@ loadFromExtension('framework', array( - 'session' => array( +$container->loadFromExtension('framework', [ + 'session' => [ 'handler_id' => null, 'cookie_secure' => 'auto', - ), -)); + ], +]); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php index 4a959568f4..862786c9b8 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php @@ -54,7 +54,7 @@ use Symfony\Component\Workflow; abstract class FrameworkExtensionTest extends TestCase { - private static $containerCache = array(); + private static $containerCache = []; abstract protected function loadFromFile(ContainerBuilder $container, $file); @@ -96,13 +96,13 @@ abstract class FrameworkExtensionTest extends TestCase } $cache = $container->getDefinition('cache.property_access'); - $this->assertSame(array(PropertyAccessor::class, 'createCache'), $cache->getFactory(), 'PropertyAccessor::createCache() should be used in non-debug mode'); + $this->assertSame([PropertyAccessor::class, 'createCache'], $cache->getFactory(), 'PropertyAccessor::createCache() should be used in non-debug mode'); $this->assertSame(AdapterInterface::class, $cache->getClass()); } public function testPropertyAccessCacheWithDebug() { - $container = $this->createContainerFromFile('property_accessor', array('kernel.debug' => true)); + $container = $this->createContainerFromFile('property_accessor', ['kernel.debug' => true]); if (!method_exists(PropertyAccessor::class, 'createCache')) { return $this->assertFalse($container->hasDefinition('cache.property_access')); @@ -204,18 +204,18 @@ abstract class FrameworkExtensionTest extends TestCase $workflowDefinition = $container->getDefinition('workflow.article.definition'); $this->assertSame( - array( + [ 'draft', 'wait_for_journalist', 'approved_by_journalist', 'wait_for_spellchecker', 'approved_by_spellchecker', 'published', - ), + ], $workflowDefinition->getArgument(0), 'Places are passed to the workflow definition' ); - $this->assertSame(array('workflow.definition' => array(array('name' => 'article', 'type' => 'workflow', 'marking_store' => 'multiple_state'))), $workflowDefinition->getTags()); + $this->assertSame(['workflow.definition' => [['name' => 'article', 'type' => 'workflow', 'marking_store' => 'multiple_state']]], $workflowDefinition->getTags()); $this->assertCount(4, $workflowDefinition->getArgument(1)); $this->assertSame('draft', $workflowDefinition->getArgument(2)); @@ -226,18 +226,18 @@ abstract class FrameworkExtensionTest extends TestCase $stateMachineDefinition = $container->getDefinition('state_machine.pull_request.definition'); $this->assertSame( - array( + [ 'start', 'coding', 'travis', 'review', 'merged', 'closed', - ), + ], $stateMachineDefinition->getArgument(0), 'Places are passed to the state machine definition' ); - $this->assertSame(array('workflow.definition' => array(array('name' => 'pull_request', 'type' => 'state_machine', 'marking_store' => 'single_state'))), $stateMachineDefinition->getTags()); + $this->assertSame(['workflow.definition' => [['name' => 'pull_request', 'type' => 'state_machine', 'marking_store' => 'single_state']]], $stateMachineDefinition->getTags()); $this->assertCount(9, $stateMachineDefinition->getArgument(1)); $this->assertSame('start', $stateMachineDefinition->getArgument(2)); @@ -246,11 +246,11 @@ abstract class FrameworkExtensionTest extends TestCase $this->assertSame(Workflow\Metadata\InMemoryMetadataStore::class, $metadataStoreDefinition->getClass()); $workflowMetadata = $metadataStoreDefinition->getArgument(0); - $this->assertSame(array('title' => 'workflow title'), $workflowMetadata); + $this->assertSame(['title' => 'workflow title'], $workflowMetadata); $placesMetadata = $metadataStoreDefinition->getArgument(1); $this->assertArrayHasKey('start', $placesMetadata); - $this->assertSame(array('title' => 'place start title'), $placesMetadata['start']); + $this->assertSame(['title' => 'place start title'], $placesMetadata['start']); $transitionsMetadata = $metadataStoreDefinition->getArgument(2); $this->assertSame(\SplObjectStorage::class, $transitionsMetadata->getClass()); @@ -322,60 +322,60 @@ abstract class FrameworkExtensionTest extends TestCase $this->assertCount(5, $transitions); $this->assertSame('workflow.article.transition.0', (string) $transitions[0]); - $this->assertSame(array( + $this->assertSame([ 'request_review', - array( + [ 'draft', - ), - array( + ], + [ 'wait_for_journalist', 'wait_for_spellchecker', - ), - ), $container->getDefinition($transitions[0])->getArguments()); + ], + ], $container->getDefinition($transitions[0])->getArguments()); $this->assertSame('workflow.article.transition.1', (string) $transitions[1]); - $this->assertSame(array( + $this->assertSame([ 'journalist_approval', - array( + [ 'wait_for_journalist', - ), - array( + ], + [ 'approved_by_journalist', - ), - ), $container->getDefinition($transitions[1])->getArguments()); + ], + ], $container->getDefinition($transitions[1])->getArguments()); $this->assertSame('workflow.article.transition.2', (string) $transitions[2]); - $this->assertSame(array( + $this->assertSame([ 'spellchecker_approval', - array( + [ 'wait_for_spellchecker', - ), - array( + ], + [ 'approved_by_spellchecker', - ), - ), $container->getDefinition($transitions[2])->getArguments()); + ], + ], $container->getDefinition($transitions[2])->getArguments()); $this->assertSame('workflow.article.transition.3', (string) $transitions[3]); - $this->assertSame(array( + $this->assertSame([ 'publish', - array( + [ 'approved_by_journalist', 'approved_by_spellchecker', - ), - array( + ], + [ 'published', - ), - ), $container->getDefinition($transitions[3])->getArguments()); + ], + ], $container->getDefinition($transitions[3])->getArguments()); $this->assertSame('workflow.article.transition.4', (string) $transitions[4]); - $this->assertSame(array( + $this->assertSame([ 'publish', - array( + [ 'draft', - ), - array( + ], + [ 'published', - ), - ), $container->getDefinition($transitions[4])->getArguments()); + ], + ], $container->getDefinition($transitions[4])->getArguments()); } public function testGuardExpressions() @@ -386,12 +386,12 @@ abstract class FrameworkExtensionTest extends TestCase $this->assertTrue($container->hasParameter('workflow.has_guard_listeners'), 'Workflow guard listeners parameter exists'); $this->assertTrue(true === $container->getParameter('workflow.has_guard_listeners'), 'Workflow guard listeners parameter is enabled'); $guardDefinition = $container->getDefinition('workflow.article.listener.guard'); - $this->assertSame(array( - array( + $this->assertSame([ + [ 'event' => 'workflow.article.guard.publish', 'method' => 'onTransition', - ), - ), $guardDefinition->getTag('kernel.event_listener')); + ], + ], $guardDefinition->getTag('kernel.event_listener')); $guardsConfiguration = $guardDefinition->getArgument(0); $this->assertTrue(1 === \count($guardsConfiguration), 'Workflow guard configuration contains one element per transition name'); $transitionGuardExpressions = $guardsConfiguration['workflow.article.guard.publish']; @@ -470,7 +470,7 @@ abstract class FrameworkExtensionTest extends TestCase { $container = $this->createContainer(); $loader = new FrameworkExtension(); - $loader->load(array(array('router' => true)), $container); + $loader->load([['router' => true]], $container); } public function testSession() @@ -505,7 +505,7 @@ abstract class FrameworkExtensionTest extends TestCase $this->assertNull($container->getDefinition('session.storage.native')->getArgument(1)); $this->assertNull($container->getDefinition('session.storage.php_bridge')->getArgument(0)); - $expected = array('session', 'initialized_session'); + $expected = ['session', 'initialized_session']; $this->assertEquals($expected, array_keys($container->getDefinition('session_listener')->getArgument(0)->getValues())); } @@ -515,7 +515,7 @@ abstract class FrameworkExtensionTest extends TestCase $this->assertTrue($container->hasDefinition('request.add_request_formats_listener'), '->registerRequestConfiguration() loads request.xml'); $listenerDef = $container->getDefinition('request.add_request_formats_listener'); - $this->assertEquals(array('csv' => array('text/csv', 'text/plain'), 'pdf' => array('application/pdf')), $listenerDef->getArgument(0)); + $this->assertEquals(['csv' => ['text/csv', 'text/plain'], 'pdf' => ['application/pdf']], $listenerDef->getArgument(0)); } public function testEmptyRequestFormats() @@ -540,9 +540,9 @@ abstract class FrameworkExtensionTest extends TestCase $this->assertEquals('%templating.loader.cache.path%', $container->getDefinition('templating.loader.cache')->getArgument(1)); $this->assertEquals('/path/to/cache', $container->getParameter('templating.loader.cache.path')); - $this->assertEquals(array('php', 'twig'), $container->getParameter('templating.engines'), '->registerTemplatingConfiguration() sets a templating.engines parameter'); + $this->assertEquals(['php', 'twig'], $container->getParameter('templating.engines'), '->registerTemplatingConfiguration() sets a templating.engines parameter'); - $this->assertEquals(array('FrameworkBundle:Form', 'theme1', 'theme2'), $container->getParameter('templating.helper.form.resources'), '->registerTemplatingConfiguration() registers the theme and adds the base theme'); + $this->assertEquals(['FrameworkBundle:Form', 'theme1', 'theme2'], $container->getParameter('templating.helper.form.resources'), '->registerTemplatingConfiguration() registers the theme and adds the base theme'); $this->assertEquals('global_hinclude_template', $container->getParameter('fragment.renderer.hinclude.global_template'), '->registerTemplatingConfiguration() registers the global hinclude.js template'); } @@ -560,7 +560,7 @@ abstract class FrameworkExtensionTest extends TestCase // default package $defaultPackage = $container->getDefinition((string) $packages->getArgument(0)); - $this->assertUrlPackage($container, $defaultPackage, array('http://cdn.example.com'), 'SomeVersionScheme', '%%s?version=%%s'); + $this->assertUrlPackage($container, $defaultPackage, ['http://cdn.example.com'], 'SomeVersionScheme', '%%s?version=%%s'); // packages $packages = $packages->getArgument(1); @@ -570,13 +570,13 @@ abstract class FrameworkExtensionTest extends TestCase $this->assertPathPackage($container, $package, '/foo', 'SomeVersionScheme', '%%s?version=%%s'); $package = $container->getDefinition((string) $packages['images']); - $this->assertUrlPackage($container, $package, array('http://images1.example.com', 'http://images2.example.com'), '1.0.0', '%%s?version=%%s'); + $this->assertUrlPackage($container, $package, ['http://images1.example.com', 'http://images2.example.com'], '1.0.0', '%%s?version=%%s'); $package = $container->getDefinition((string) $packages['foo']); $this->assertPathPackage($container, $package, '', '1.0.0', '%%s-%%s'); $package = $container->getDefinition((string) $packages['bar']); - $this->assertUrlPackage($container, $package, array('https://bar2.example.com'), 'SomeVersionScheme', '%%s?version=%%s'); + $this->assertUrlPackage($container, $package, ['https://bar2.example.com'], 'SomeVersionScheme', '%%s?version=%%s'); $package = $container->getDefinition((string) $packages['bar_version_strategy']); $this->assertEquals('assets.custom_version_strategy', (string) $package->getArgument(1)); @@ -625,16 +625,16 @@ abstract class FrameworkExtensionTest extends TestCase $container = $this->createContainerFromFile('messenger_transports'); $this->assertTrue($container->hasDefinition('messenger.transport.default')); $this->assertTrue($container->getDefinition('messenger.transport.default')->hasTag('messenger.receiver')); - $this->assertEquals(array(array('alias' => 'default')), $container->getDefinition('messenger.transport.default')->getTag('messenger.receiver')); + $this->assertEquals([['alias' => 'default']], $container->getDefinition('messenger.transport.default')->getTag('messenger.receiver')); $this->assertTrue($container->hasDefinition('messenger.transport.customised')); $transportFactory = $container->getDefinition('messenger.transport.customised')->getFactory(); $transportArguments = $container->getDefinition('messenger.transport.customised')->getArguments(); - $this->assertEquals(array(new Reference('messenger.transport_factory'), 'createTransport'), $transportFactory); + $this->assertEquals([new Reference('messenger.transport_factory'), 'createTransport'], $transportFactory); $this->assertCount(2, $transportArguments); $this->assertSame('amqp://localhost/%2f/messages?exchange_name=exchange_name', $transportArguments[0]); - $this->assertSame(array('queue' => array('name' => 'Queue')), $transportArguments[1]); + $this->assertSame(['queue' => ['name' => 'Queue']], $transportArguments[1]); $this->assertTrue($container->hasDefinition('messenger.transport.amqp.factory')); } @@ -644,18 +644,18 @@ abstract class FrameworkExtensionTest extends TestCase $container = $this->createContainerFromFile('messenger_routing'); $senderLocatorDefinition = $container->getDefinition('messenger.senders_locator'); - $messageToSendAndHandleMapping = array( + $messageToSendAndHandleMapping = [ DummyMessage::class => false, SecondMessage::class => true, '*' => false, - ); + ]; $this->assertSame($messageToSendAndHandleMapping, $senderLocatorDefinition->getArgument(1)); $sendersMapping = $senderLocatorDefinition->getArgument(0); - $this->assertEquals(array( + $this->assertEquals([ 'amqp' => new Reference('messenger.transport.amqp'), 'audit' => new Reference('audit'), - ), $sendersMapping[DummyMessage::class]->getValues()); + ], $sendersMapping[DummyMessage::class]->getValues()); } /** @@ -684,7 +684,7 @@ abstract class FrameworkExtensionTest extends TestCase $serializerTransportDefinition = $container->getDefinition('messenger.transport.symfony_serializer'); $this->assertSame('csv', $serializerTransportDefinition->getArgument(1)); - $this->assertSame(array('enable_max_depth' => true), $serializerTransportDefinition->getArgument(2)); + $this->assertSame(['enable_max_depth' => true], $serializerTransportDefinition->getArgument(2)); } public function testMessengerWithMultipleBuses() @@ -692,26 +692,26 @@ abstract class FrameworkExtensionTest extends TestCase $container = $this->createContainerFromFile('messenger_multiple_buses'); $this->assertTrue($container->has('messenger.bus.commands')); - $this->assertSame(array(), $container->getDefinition('messenger.bus.commands')->getArgument(0)); - $this->assertEquals(array( - array('id' => 'logging'), - array('id' => 'send_message'), - array('id' => 'handle_message'), - ), $container->getParameter('messenger.bus.commands.middleware')); + $this->assertSame([], $container->getDefinition('messenger.bus.commands')->getArgument(0)); + $this->assertEquals([ + ['id' => 'logging'], + ['id' => 'send_message'], + ['id' => 'handle_message'], + ], $container->getParameter('messenger.bus.commands.middleware')); $this->assertTrue($container->has('messenger.bus.events')); - $this->assertSame(array(), $container->getDefinition('messenger.bus.events')->getArgument(0)); - $this->assertEquals(array( - array('id' => 'logging'), - array('id' => 'with_factory', 'arguments' => array('foo', true, array('bar' => 'baz'))), - array('id' => 'send_message'), - array('id' => 'handle_message'), - ), $container->getParameter('messenger.bus.events.middleware')); + $this->assertSame([], $container->getDefinition('messenger.bus.events')->getArgument(0)); + $this->assertEquals([ + ['id' => 'logging'], + ['id' => 'with_factory', 'arguments' => ['foo', true, ['bar' => 'baz']]], + ['id' => 'send_message'], + ['id' => 'handle_message'], + ], $container->getParameter('messenger.bus.events.middleware')); $this->assertTrue($container->has('messenger.bus.queries')); - $this->assertSame(array(), $container->getDefinition('messenger.bus.queries')->getArgument(0)); - $this->assertEquals(array( - array('id' => 'send_message', 'arguments' => array()), - array('id' => 'handle_message', 'arguments' => array()), - ), $container->getParameter('messenger.bus.queries.middleware')); + $this->assertSame([], $container->getDefinition('messenger.bus.queries')->getArgument(0)); + $this->assertEquals([ + ['id' => 'send_message', 'arguments' => []], + ['id' => 'handle_message', 'arguments' => []], + ], $container->getParameter('messenger.bus.queries.middleware')); $this->assertTrue($container->hasAlias('message_bus')); $this->assertSame('messenger.bus.commands', (string) $container->getAlias('message_bus')); @@ -764,7 +764,7 @@ abstract class FrameworkExtensionTest extends TestCase ); $calls = $container->getDefinition('translator.default')->getMethodCalls(); - $this->assertEquals(array('fr'), $calls[1][1][0]); + $this->assertEquals(['fr'], $calls[1][1][0]); } /** @@ -773,7 +773,7 @@ abstract class FrameworkExtensionTest extends TestCase */ public function testLegacyTranslationsDirectory() { - $container = $this->createContainerFromFile('full', array('kernel.root_dir' => __DIR__.'/Fixtures')); + $container = $this->createContainerFromFile('full', ['kernel.root_dir' => __DIR__.'/Fixtures']); $options = $container->getDefinition('translator.default')->getArgument(4); $files = array_map('realpath', $options['resource_files']['en']); @@ -786,7 +786,7 @@ abstract class FrameworkExtensionTest extends TestCase $container = $this->createContainerFromFile('translator_fallbacks'); $calls = $container->getDefinition('translator.default')->getMethodCalls(); - $this->assertEquals(array('en', 'fr'), $calls[1][1][0]); + $this->assertEquals(['en', 'fr'], $calls[1][1][0]); } /** @@ -796,7 +796,7 @@ abstract class FrameworkExtensionTest extends TestCase { $container = $this->createContainer(); $loader = new FrameworkExtension(); - $loader->load(array(array('templating' => null)), $container); + $loader->load([['templating' => null]], $container); } public function testValidation() @@ -805,10 +805,10 @@ abstract class FrameworkExtensionTest extends TestCase $projectDir = $container->getParameter('kernel.project_dir'); $ref = new \ReflectionClass('Symfony\Component\Form\Form'); - $xmlMappings = array( + $xmlMappings = [ \dirname($ref->getFileName()).'/Resources/config/validation.xml', strtr($projectDir.'/config/validator/foo.xml', '/', \DIRECTORY_SEPARATOR), - ); + ]; $calls = $container->getDefinition('validator.builder')->getMethodCalls(); @@ -816,33 +816,33 @@ abstract class FrameworkExtensionTest extends TestCase $this->assertCount($annotations ? 7 : 6, $calls); $this->assertSame('setConstraintValidatorFactory', $calls[0][0]); - $this->assertEquals(array(new Reference('validator.validator_factory')), $calls[0][1]); + $this->assertEquals([new Reference('validator.validator_factory')], $calls[0][1]); $this->assertSame('setTranslator', $calls[1][0]); - $this->assertEquals(array(new Reference('translator')), $calls[1][1]); + $this->assertEquals([new Reference('translator')], $calls[1][1]); $this->assertSame('setTranslationDomain', $calls[2][0]); - $this->assertSame(array('%validator.translation_domain%'), $calls[2][1]); + $this->assertSame(['%validator.translation_domain%'], $calls[2][1]); $this->assertSame('addXmlMappings', $calls[3][0]); - $this->assertSame(array($xmlMappings), $calls[3][1]); + $this->assertSame([$xmlMappings], $calls[3][1]); $i = 3; if ($annotations) { $this->assertSame('enableAnnotationMapping', $calls[++$i][0]); } $this->assertSame('addMethodMapping', $calls[++$i][0]); - $this->assertSame(array('loadValidatorMetadata'), $calls[$i][1]); + $this->assertSame(['loadValidatorMetadata'], $calls[$i][1]); $this->assertSame('setMetadataCache', $calls[++$i][0]); - $this->assertEquals(array(new Reference('validator.mapping.cache.symfony')), $calls[$i][1]); + $this->assertEquals([new Reference('validator.mapping.cache.symfony')], $calls[$i][1]); } public function testValidationService() { - $container = $this->createContainerFromFile('validation_annotations', array('kernel.charset' => 'UTF-8'), false); + $container = $this->createContainerFromFile('validation_annotations', ['kernel.charset' => 'UTF-8'], false); $this->assertInstanceOf('Symfony\Component\Validator\Validator\ValidatorInterface', $container->get('validator')); } public function testAnnotations() { - $container = $this->createContainerFromFile('full', array(), true, false); + $container = $this->createContainerFromFile('full', [], true, false); $container->addCompilerPass(new TestAnnotationsPass()); $container->compile(); @@ -869,11 +869,11 @@ abstract class FrameworkExtensionTest extends TestCase $this->assertCount(7, $calls); $this->assertSame('enableAnnotationMapping', $calls[4][0]); - $this->assertEquals(array(new Reference('annotation_reader')), $calls[4][1]); + $this->assertEquals([new Reference('annotation_reader')], $calls[4][1]); $this->assertSame('addMethodMapping', $calls[5][0]); - $this->assertSame(array('loadValidatorMetadata'), $calls[5][1]); + $this->assertSame(['loadValidatorMetadata'], $calls[5][1]); $this->assertSame('setMetadataCache', $calls[6][0]); - $this->assertEquals(array(new Reference('validator.mapping.cache.symfony')), $calls[6][1]); + $this->assertEquals([new Reference('validator.mapping.cache.symfony')], $calls[6][1]); // no cache this time } @@ -881,10 +881,10 @@ abstract class FrameworkExtensionTest extends TestCase { require_once __DIR__.'/Fixtures/TestBundle/TestBundle.php'; - $container = $this->createContainerFromFile('validation_annotations', array( - 'kernel.bundles' => array('TestBundle' => 'Symfony\\Bundle\\FrameworkBundle\\Tests\\TestBundle'), - 'kernel.bundles_metadata' => array('TestBundle' => array('namespace' => 'Symfony\\Bundle\\FrameworkBundle\\Tests', 'path' => __DIR__.'/Fixtures/TestBundle')), - )); + $container = $this->createContainerFromFile('validation_annotations', [ + 'kernel.bundles' => ['TestBundle' => 'Symfony\\Bundle\\FrameworkBundle\\Tests\\TestBundle'], + 'kernel.bundles_metadata' => ['TestBundle' => ['namespace' => 'Symfony\\Bundle\\FrameworkBundle\\Tests', 'path' => __DIR__.'/Fixtures/TestBundle']], + ]); $calls = $container->getDefinition('validator.builder')->getMethodCalls(); @@ -893,9 +893,9 @@ abstract class FrameworkExtensionTest extends TestCase $this->assertSame('addYamlMappings', $calls[4][0]); $this->assertSame('enableAnnotationMapping', $calls[5][0]); $this->assertSame('addMethodMapping', $calls[6][0]); - $this->assertSame(array('loadValidatorMetadata'), $calls[6][1]); + $this->assertSame(['loadValidatorMetadata'], $calls[6][1]); $this->assertSame('setMetadataCache', $calls[7][0]); - $this->assertEquals(array(new Reference('validator.mapping.cache.symfony')), $calls[7][1]); + $this->assertEquals([new Reference('validator.mapping.cache.symfony')], $calls[7][1]); $xmlMappings = $calls[3][1][0]; $this->assertCount(3, $xmlMappings); @@ -917,10 +917,10 @@ abstract class FrameworkExtensionTest extends TestCase { require_once __DIR__.'/Fixtures/CustomPathBundle/src/CustomPathBundle.php'; - $container = $this->createContainerFromFile('validation_annotations', array( - 'kernel.bundles' => array('CustomPathBundle' => 'Symfony\\Bundle\\FrameworkBundle\\Tests\\CustomPathBundle'), - 'kernel.bundles_metadata' => array('TestBundle' => array('namespace' => 'Symfony\\Bundle\\FrameworkBundle\\Tests', 'path' => __DIR__.'/Fixtures/CustomPathBundle')), - )); + $container = $this->createContainerFromFile('validation_annotations', [ + 'kernel.bundles' => ['CustomPathBundle' => 'Symfony\\Bundle\\FrameworkBundle\\Tests\\CustomPathBundle'], + 'kernel.bundles_metadata' => ['TestBundle' => ['namespace' => 'Symfony\\Bundle\\FrameworkBundle\\Tests', 'path' => __DIR__.'/Fixtures/CustomPathBundle']], + ]); $calls = $container->getDefinition('validator.builder')->getMethodCalls(); $xmlMappings = $calls[3][1][0]; @@ -955,7 +955,7 @@ abstract class FrameworkExtensionTest extends TestCase $this->assertSame('enableAnnotationMapping', $calls[++$i][0]); } $this->assertSame('setMetadataCache', $calls[++$i][0]); - $this->assertEquals(array(new Reference('validator.mapping.cache.symfony')), $calls[$i][1]); + $this->assertEquals([new Reference('validator.mapping.cache.symfony')], $calls[$i][1]); // no cache, no annotations, no static methods } @@ -1031,19 +1031,19 @@ abstract class FrameworkExtensionTest extends TestCase public function testStopwatchEnabledWithDebugModeEnabled() { - $container = $this->createContainerFromFile('default_config', array( + $container = $this->createContainerFromFile('default_config', [ 'kernel.container_class' => 'foo', 'kernel.debug' => true, - )); + ]); $this->assertTrue($container->has('debug.stopwatch')); } public function testStopwatchEnabledWithDebugModeDisabled() { - $container = $this->createContainerFromFile('default_config', array( + $container = $this->createContainerFromFile('default_config', [ 'kernel.container_class' => 'foo', - )); + ]); $this->assertTrue($container->has('debug.stopwatch')); } @@ -1066,8 +1066,8 @@ abstract class FrameworkExtensionTest extends TestCase $this->assertNull($container->getDefinition('serializer.mapping.class_metadata_factory')->getArgument(1)); $this->assertEquals(new Reference('serializer.name_converter.camel_case_to_snake_case'), $container->getDefinition('serializer.name_converter.metadata_aware')->getArgument(1)); $this->assertEquals(new Reference('property_info', ContainerBuilder::IGNORE_ON_INVALID_REFERENCE), $container->getDefinition('serializer.normalizer.object')->getArgument(3)); - $this->assertEquals(array('setCircularReferenceHandler', array(new Reference('my.circular.reference.handler'))), $container->getDefinition('serializer.normalizer.object')->getMethodCalls()[0]); - $this->assertEquals(array('setMaxDepthHandler', array(new Reference('my.max.depth.handler'))), $container->getDefinition('serializer.normalizer.object')->getMethodCalls()[1]); + $this->assertEquals(['setCircularReferenceHandler', [new Reference('my.circular.reference.handler')]], $container->getDefinition('serializer.normalizer.object')->getMethodCalls()[0]); + $this->assertEquals(['setMaxDepthHandler', [new Reference('my.max.depth.handler')]], $container->getDefinition('serializer.normalizer.object')->getMethodCalls()[1]); } public function testRegisterSerializerExtractor() @@ -1079,7 +1079,7 @@ abstract class FrameworkExtensionTest extends TestCase $this->assertEquals('serializer.mapping.class_metadata_factory', $serializerExtractorDefinition->getArgument(0)->__toString()); $this->assertFalse($serializerExtractorDefinition->isPublic()); $tag = $serializerExtractorDefinition->getTag('property_info.list_extractor'); - $this->assertEquals(array('priority' => -999), $tag[0]); + $this->assertEquals(['priority' => -999], $tag[0]); } public function testDataUriNormalizerRegistered() @@ -1153,25 +1153,25 @@ abstract class FrameworkExtensionTest extends TestCase public function testSerializerCacheDisabled() { - $container = $this->createContainerFromFile('serializer_enabled', array('kernel.debug' => true, 'kernel.container_class' => __CLASS__)); + $container = $this->createContainerFromFile('serializer_enabled', ['kernel.debug' => true, 'kernel.container_class' => __CLASS__]); $this->assertFalse($container->hasDefinition('serializer.mapping.cache_class_metadata_factory')); } public function testSerializerMapping() { - $container = $this->createContainerFromFile('serializer_mapping', array('kernel.bundles_metadata' => array('TestBundle' => array('namespace' => 'Symfony\\Bundle\\FrameworkBundle\\Tests', 'path' => __DIR__.'/Fixtures/TestBundle')))); + $container = $this->createContainerFromFile('serializer_mapping', ['kernel.bundles_metadata' => ['TestBundle' => ['namespace' => 'Symfony\\Bundle\\FrameworkBundle\\Tests', 'path' => __DIR__.'/Fixtures/TestBundle']]]); $projectDir = $container->getParameter('kernel.project_dir'); $configDir = __DIR__.'/Fixtures/TestBundle/Resources/config'; - $expectedLoaders = array( - new Definition(AnnotationLoader::class, array(new Reference('annotation_reader'))), - new Definition(XmlFileLoader::class, array($configDir.'/serialization.xml')), - new Definition(YamlFileLoader::class, array($configDir.'/serialization.yml')), - new Definition(YamlFileLoader::class, array($projectDir.'/config/serializer/foo.yml')), - new Definition(XmlFileLoader::class, array($configDir.'/serializer_mapping/files/foo.xml')), - new Definition(YamlFileLoader::class, array($configDir.'/serializer_mapping/files/foo.yml')), - new Definition(YamlFileLoader::class, array($configDir.'/serializer_mapping/serialization.yml')), - new Definition(YamlFileLoader::class, array($configDir.'/serializer_mapping/serialization.yaml')), - ); + $expectedLoaders = [ + new Definition(AnnotationLoader::class, [new Reference('annotation_reader')]), + new Definition(XmlFileLoader::class, [$configDir.'/serialization.xml']), + new Definition(YamlFileLoader::class, [$configDir.'/serialization.yml']), + new Definition(YamlFileLoader::class, [$projectDir.'/config/serializer/foo.yml']), + new Definition(XmlFileLoader::class, [$configDir.'/serializer_mapping/files/foo.xml']), + new Definition(YamlFileLoader::class, [$configDir.'/serializer_mapping/files/foo.yml']), + new Definition(YamlFileLoader::class, [$configDir.'/serializer_mapping/serialization.yml']), + new Definition(YamlFileLoader::class, [$configDir.'/serializer_mapping/serialization.yaml']), + ]; foreach ($expectedLoaders as $definition) { if (is_file($arg = $definition->getArgument(0))) { @@ -1241,9 +1241,9 @@ abstract class FrameworkExtensionTest extends TestCase public function testEventDispatcherService() { - $container = $this->createContainer(array('kernel.charset' => 'UTF-8', 'kernel.secret' => 'secret')); + $container = $this->createContainer(['kernel.charset' => 'UTF-8', 'kernel.secret' => 'secret']); $container->registerExtension(new FrameworkExtension()); - $container->getCompilerPassConfig()->setBeforeOptimizationPasses(array(new LoggerPass())); + $container->getCompilerPassConfig()->setBeforeOptimizationPasses([new LoggerPass()]); $this->loadFromFile($container, 'default_config'); $container ->register('foo', \stdClass::class) @@ -1294,18 +1294,18 @@ abstract class FrameworkExtensionTest extends TestCase public function testRemovesResourceCheckerConfigCacheFactoryArgumentOnlyIfNoDebug() { - $container = $this->createContainer(array('kernel.debug' => true)); - (new FrameworkExtension())->load(array(), $container); + $container = $this->createContainer(['kernel.debug' => true]); + (new FrameworkExtension())->load([], $container); $this->assertCount(1, $container->getDefinition('config_cache_factory')->getArguments()); - $container = $this->createContainer(array('kernel.debug' => false)); - (new FrameworkExtension())->load(array(), $container); + $container = $this->createContainer(['kernel.debug' => false]); + (new FrameworkExtension())->load([], $container); $this->assertEmpty($container->getDefinition('config_cache_factory')->getArguments()); } public function testLoggerAwareRegistration() { - $container = $this->createContainerFromFile('full', array(), true, false); + $container = $this->createContainerFromFile('full', [], true, false); $container->addCompilerPass(new ResolveInstanceofConditionalsPass()); $container->register('foo', LoggerAwareInterface::class) ->setAutoconfigured(true); @@ -1323,15 +1323,15 @@ abstract class FrameworkExtensionTest extends TestCase { $container = $this->createContainerFromFile('session_cookie_secure_auto'); - $expected = array('session', 'initialized_session', 'session_storage', 'request_stack'); + $expected = ['session', 'initialized_session', 'session_storage', 'request_stack']; $this->assertEquals($expected, array_keys($container->getDefinition('session_listener')->getArgument(0)->getValues())); } - protected function createContainer(array $data = array()) + protected function createContainer(array $data = []) { - return new ContainerBuilder(new ParameterBag(array_merge(array( - 'kernel.bundles' => array('FrameworkBundle' => 'Symfony\\Bundle\\FrameworkBundle\\FrameworkBundle'), - 'kernel.bundles_metadata' => array('FrameworkBundle' => array('namespace' => 'Symfony\\Bundle\\FrameworkBundle', 'path' => __DIR__.'/../..')), + return new ContainerBuilder(new ParameterBag(array_merge([ + 'kernel.bundles' => ['FrameworkBundle' => 'Symfony\\Bundle\\FrameworkBundle\\FrameworkBundle'], + 'kernel.bundles_metadata' => ['FrameworkBundle' => ['namespace' => 'Symfony\\Bundle\\FrameworkBundle', 'path' => __DIR__.'/../..']], 'kernel.cache_dir' => __DIR__, 'kernel.project_dir' => __DIR__, 'kernel.debug' => false, @@ -1342,10 +1342,10 @@ abstract class FrameworkExtensionTest extends TestCase 'container.build_hash' => 'Abc1234', 'container.build_id' => hash('crc32', 'Abc123423456789'), 'container.build_time' => 23456789, - ), $data))); + ], $data))); } - protected function createContainerFromFile($file, $data = array(), $resetCompilerPasses = true, $compile = true) + protected function createContainerFromFile($file, $data = [], $resetCompilerPasses = true, $compile = true) { $cacheKey = md5(\get_class($this).$file.serialize($data)); if ($compile && isset(self::$containerCache[$cacheKey])) { @@ -1356,12 +1356,12 @@ abstract class FrameworkExtensionTest extends TestCase $this->loadFromFile($container, $file); if ($resetCompilerPasses) { - $container->getCompilerPassConfig()->setOptimizationPasses(array()); - $container->getCompilerPassConfig()->setRemovingPasses(array()); + $container->getCompilerPassConfig()->setOptimizationPasses([]); + $container->getCompilerPassConfig()->setRemovingPasses([]); } - $container->getCompilerPassConfig()->setBeforeOptimizationPasses(array(new LoggerPass())); - $container->getCompilerPassConfig()->setBeforeRemovingPasses(array(new AddConstraintValidatorsPass(), new TranslatorPass('translator.default', 'translation.reader'))); - $container->getCompilerPassConfig()->setAfterRemovingPasses(array(new AddAnnotationsCachedReaderPass())); + $container->getCompilerPassConfig()->setBeforeOptimizationPasses([new LoggerPass()]); + $container->getCompilerPassConfig()->setBeforeRemovingPasses([new AddConstraintValidatorsPass(), new TranslatorPass('translator.default', 'translation.reader')]); + $container->getCompilerPassConfig()->setAfterRemovingPasses([new AddAnnotationsCachedReaderPass()]); if (!$compile) { return $container; @@ -1371,15 +1371,15 @@ abstract class FrameworkExtensionTest extends TestCase return self::$containerCache[$cacheKey] = $container; } - protected function createContainerFromClosure($closure, $data = array()) + protected function createContainerFromClosure($closure, $data = []) { $container = $this->createContainer($data); $container->registerExtension(new FrameworkExtension()); $loader = new ClosureLoader($container); $loader->load($closure); - $container->getCompilerPassConfig()->setOptimizationPasses(array()); - $container->getCompilerPassConfig()->setRemovingPasses(array()); + $container->getCompilerPassConfig()->setOptimizationPasses([]); + $container->getCompilerPassConfig()->setRemovingPasses([]); $container->compile(); return $container; diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/ContainerDebugCommandTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/ContainerDebugCommandTest.php index e34a30af2a..93028bf8c2 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/ContainerDebugCommandTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/ContainerDebugCommandTest.php @@ -70,21 +70,21 @@ class ContainerDebugCommandTest extends WebTestCase */ public function testIgnoreBackslashWhenFindingService(string $validServiceId) { - static::bootKernel(array('test_case' => 'ContainerDebug', 'root_config' => 'config.yml')); + static::bootKernel(['test_case' => 'ContainerDebug', 'root_config' => 'config.yml']); $application = new Application(static::$kernel); $application->setAutoExit(false); $tester = new ApplicationTester($application); - $tester->run(array('command' => 'debug:container', 'name' => $validServiceId)); + $tester->run(['command' => 'debug:container', 'name' => $validServiceId]); $this->assertNotContains('No services found', $tester->getDisplay()); } public function provideIgnoreBackslashWhenFindingService() { - return array( - array(BackslashClass::class), - array('FixturesBackslashClass'), - ); + return [ + [BackslashClass::class], + ['FixturesBackslashClass'], + ]; } } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/DebugAutowiringCommandTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/DebugAutowiringCommandTest.php index eccecc9d5d..1c64fbe6ee 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/DebugAutowiringCommandTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/DebugAutowiringCommandTest.php @@ -49,13 +49,13 @@ class DebugAutowiringCommandTest extends WebTestCase public function testSearchIgnoreBackslashWhenFindingService() { - static::bootKernel(array('test_case' => 'ContainerDebug', 'root_config' => 'config.yml')); + static::bootKernel(['test_case' => 'ContainerDebug', 'root_config' => 'config.yml']); $application = new Application(static::$kernel); $application->setAutoExit(false); $tester = new ApplicationTester($application); - $tester->run(array('command' => 'debug:autowiring', 'search' => 'HttpKernelHttpKernelInterface')); + $tester->run(['command' => 'debug:autowiring', 'search' => 'HttpKernelHttpKernelInterface']); $this->assertContains('Symfony\Component\HttpKernel\HttpKernelInterface', $tester->getDisplay()); } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Routing/DelegatingLoaderTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Routing/DelegatingLoaderTest.php index b382f55a03..1d576056eb 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Routing/DelegatingLoaderTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Routing/DelegatingLoaderTest.php @@ -39,29 +39,29 @@ class DelegatingLoaderTest extends TestCase ->willReturn($loader); $routeCollection = new RouteCollection(); - $routeCollection->add('foo', new Route('/', array(), array(), array('utf8' => false))); - $routeCollection->add('bar', new Route('/', array(), array(), array('foo' => 123))); + $routeCollection->add('foo', new Route('/', [], [], ['utf8' => false])); + $routeCollection->add('bar', new Route('/', [], [], ['foo' => 123])); $loader->expects($this->once()) ->method('load') ->willReturn($routeCollection); - $delegatingLoader = new DelegatingLoader($controllerNameParser, $loaderResolver, array('utf8' => true)); + $delegatingLoader = new DelegatingLoader($controllerNameParser, $loaderResolver, ['utf8' => true]); $loadedRouteCollection = $delegatingLoader->load('foo'); $this->assertCount(2, $loadedRouteCollection); - $expected = array( + $expected = [ 'compiler_class' => 'Symfony\Component\Routing\RouteCompiler', 'utf8' => false, - ); + ]; $this->assertSame($expected, $routeCollection->get('foo')->getOptions()); - $expected = array( + $expected = [ 'compiler_class' => 'Symfony\Component\Routing\RouteCompiler', 'foo' => 123, 'utf8' => true, - ); + ]; $this->assertSame($expected, $routeCollection->get('bar')->getOptions()); } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Fixtures/StubTranslator.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Fixtures/StubTranslator.php index 377a67d6be..9175b37115 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Fixtures/StubTranslator.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Fixtures/StubTranslator.php @@ -15,7 +15,7 @@ use Symfony\Contracts\Translation\TranslatorInterface; class StubTranslator implements TranslatorInterface { - public function trans($id, array $parameters = array(), $domain = null, $locale = null) + public function trans($id, array $parameters = [], $domain = null, $locale = null) { return '[trans]'.$id.'[/trans]'; } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/FormHelperDivLayoutTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/FormHelperDivLayoutTest.php index b74bc801cd..b00b6a10e5 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/FormHelperDivLayoutTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/FormHelperDivLayoutTest.php @@ -35,19 +35,19 @@ class FormHelperDivLayoutTest extends AbstractDivLayoutTest $root = realpath(\dirname($reflClass->getFileName()).'/Resources/views'); $rootTheme = realpath(__DIR__.'/Resources'); $templateNameParser = new StubTemplateNameParser($root, $rootTheme); - $loader = new FilesystemLoader(array()); + $loader = new FilesystemLoader([]); $this->engine = new PhpEngine($templateNameParser, $loader); $this->engine->addGlobal('global', ''); - $this->engine->setHelpers(array( + $this->engine->setHelpers([ new TranslatorHelper(new StubTranslator()), - )); + ]); - return array_merge(parent::getExtensions(), array( - new TemplatingExtension($this->engine, $this->csrfTokenManager, array( + return array_merge(parent::getExtensions(), [ + new TemplatingExtension($this->engine, $this->csrfTokenManager, [ 'FrameworkBundle:Form', - )), - )); + ]), + ]); } protected function tearDown() @@ -59,10 +59,10 @@ class FormHelperDivLayoutTest extends AbstractDivLayoutTest public function testStartTagHasNoActionAttributeWhenActionIsEmpty() { - $form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, array( + $form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, [ 'method' => 'get', 'action' => '', - )); + ]); $html = $this->renderStart($form->createView()); @@ -71,10 +71,10 @@ class FormHelperDivLayoutTest extends AbstractDivLayoutTest public function testStartTagHasActionAttributeWhenActionIsZero() { - $form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, array( + $form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, [ 'method' => 'get', 'action' => '0', - )); + ]); $html = $this->renderStart($form->createView()); @@ -95,12 +95,12 @@ class FormHelperDivLayoutTest extends AbstractDivLayoutTest public function testHelpAttr() { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, array( + $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, [ 'help' => 'Help text test!', - 'help_attr' => array( + 'help_attr' => [ 'class' => 'class-test', - ), - )); + ], + ]); $view = $form->createView(); $html = $this->renderHelp($view); @@ -113,12 +113,12 @@ class FormHelperDivLayoutTest extends AbstractDivLayoutTest ); } - protected function renderForm(FormView $view, array $vars = array()) + protected function renderForm(FormView $view, array $vars = []) { return (string) $this->engine->get('form')->form($view, $vars); } - protected function renderLabel(FormView $view, $label = null, array $vars = array()) + protected function renderLabel(FormView $view, $label = null, array $vars = []) { return (string) $this->engine->get('form')->label($view, $label, $vars); } @@ -133,27 +133,27 @@ class FormHelperDivLayoutTest extends AbstractDivLayoutTest return (string) $this->engine->get('form')->errors($view); } - protected function renderWidget(FormView $view, array $vars = array()) + protected function renderWidget(FormView $view, array $vars = []) { return (string) $this->engine->get('form')->widget($view, $vars); } - protected function renderRow(FormView $view, array $vars = array()) + protected function renderRow(FormView $view, array $vars = []) { return (string) $this->engine->get('form')->row($view, $vars); } - protected function renderRest(FormView $view, array $vars = array()) + protected function renderRest(FormView $view, array $vars = []) { return (string) $this->engine->get('form')->rest($view, $vars); } - protected function renderStart(FormView $view, array $vars = array()) + protected function renderStart(FormView $view, array $vars = []) { return (string) $this->engine->get('form')->start($view, $vars); } - protected function renderEnd(FormView $view, array $vars = array()) + protected function renderEnd(FormView $view, array $vars = []) { return (string) $this->engine->get('form')->end($view, $vars); } @@ -165,15 +165,15 @@ class FormHelperDivLayoutTest extends AbstractDivLayoutTest public static function themeBlockInheritanceProvider() { - return array( - array(array('TestBundle:Parent')), - ); + return [ + [['TestBundle:Parent']], + ]; } public static function themeInheritanceProvider() { - return array( - array(array('TestBundle:Parent'), array('TestBundle:Child')), - ); + return [ + [['TestBundle:Parent'], ['TestBundle:Child']], + ]; } } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/FormHelperTableLayoutTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/FormHelperTableLayoutTest.php index 741b9726de..8b1bf4cbdd 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/FormHelperTableLayoutTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/FormHelperTableLayoutTest.php @@ -53,12 +53,12 @@ class FormHelperTableLayoutTest extends AbstractTableLayoutTest public function testHelpAttr() { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, array( + $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, [ 'help' => 'Help text test!', - 'help_attr' => array( + 'help_attr' => [ 'class' => 'class-test', - ), - )); + ], + ]); $view = $form->createView(); $html = $this->renderHelp($view); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Translation/TranslatorTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Translation/TranslatorTest.php index 8a48fbebcf..6b276ca0b9 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Translation/TranslatorTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Translation/TranslatorTest.php @@ -52,10 +52,10 @@ class TranslatorTest extends TestCase $this->assertEquals('foo (FR)', $translator->trans('foo')); $this->assertEquals('bar (EN)', $translator->trans('bar')); $this->assertEquals('foobar (ES)', $translator->trans('foobar')); - $this->assertEquals('choice 0 (EN)', $translator->trans('choice', array('%count%' => 0))); + $this->assertEquals('choice 0 (EN)', $translator->trans('choice', ['%count%' => 0])); $this->assertEquals('no translation', $translator->trans('no translation')); $this->assertEquals('foobarfoo (PT-PT)', $translator->trans('foobarfoo')); - $this->assertEquals('other choice 1 (PT-BR)', $translator->trans('other choice', array('%count%' => 1))); + $this->assertEquals('other choice 1 (PT-BR)', $translator->trans('other choice', ['%count%' => 1])); $this->assertEquals('foobarbaz (fr.UTF-8)', $translator->trans('foobarbaz')); $this->assertEquals('foobarbax (sr@latin)', $translator->trans('foobarbax')); } @@ -67,7 +67,7 @@ class TranslatorTest extends TestCase { $translator = $this->getTranslator($this->getLoader()); $translator->setLocale('fr'); - $translator->setFallbackLocales(array('en', 'es', 'pt-PT', 'pt_BR', 'fr.UTF-8', 'sr@latin')); + $translator->setFallbackLocales(['en', 'es', 'pt-PT', 'pt_BR', 'fr.UTF-8', 'sr@latin']); $this->assertEquals('choice 0 (EN)', $translator->transChoice('choice', 0)); $this->assertEquals('other choice 1 (PT-BR)', $translator->transChoice('other choice', 1)); @@ -83,10 +83,10 @@ class TranslatorTest extends TestCase $this->assertEquals('foo (FR)', $translator->trans('foo')); $this->assertEquals('bar (EN)', $translator->trans('bar')); $this->assertEquals('foobar (ES)', $translator->trans('foobar')); - $this->assertEquals('choice 0 (EN)', $translator->trans('choice', array('%count%' => 0))); + $this->assertEquals('choice 0 (EN)', $translator->trans('choice', ['%count%' => 0])); $this->assertEquals('no translation', $translator->trans('no translation')); $this->assertEquals('foobarfoo (PT-PT)', $translator->trans('foobarfoo')); - $this->assertEquals('other choice 1 (PT-BR)', $translator->trans('other choice', array('%count%' => 1))); + $this->assertEquals('other choice 1 (PT-BR)', $translator->trans('other choice', ['%count%' => 1])); $this->assertEquals('foobarbaz (fr.UTF-8)', $translator->trans('foobarbaz')); $this->assertEquals('foobarbax (sr@latin)', $translator->trans('foobarbax')); @@ -113,9 +113,9 @@ class TranslatorTest extends TestCase public function testTransChoiceWithCaching() { // prime the cache - $translator = $this->getTranslator($this->getLoader(), array('cache_dir' => $this->tmpDir)); + $translator = $this->getTranslator($this->getLoader(), ['cache_dir' => $this->tmpDir]); $translator->setLocale('fr'); - $translator->setFallbackLocales(array('en', 'es', 'pt-PT', 'pt_BR', 'fr.UTF-8', 'sr@latin')); + $translator->setFallbackLocales(['en', 'es', 'pt-PT', 'pt_BR', 'fr.UTF-8', 'sr@latin']); $this->assertEquals('choice 0 (EN)', $translator->transChoice('choice', 0)); $this->assertEquals('other choice 1 (PT-BR)', $translator->transChoice('other choice', 1)); @@ -124,9 +124,9 @@ class TranslatorTest extends TestCase $loader = $this->getMockBuilder('Symfony\Component\Translation\Loader\LoaderInterface')->getMock(); $loader->expects($this->never())->method('load'); - $translator = $this->getTranslator($loader, array('cache_dir' => $this->tmpDir)); + $translator = $this->getTranslator($loader, ['cache_dir' => $this->tmpDir]); $translator->setLocale('fr'); - $translator->setFallbackLocales(array('en', 'es', 'pt-PT', 'pt_BR', 'fr.UTF-8', 'sr@latin')); + $translator->setFallbackLocales(['en', 'es', 'pt-PT', 'pt_BR', 'fr.UTF-8', 'sr@latin']); $this->assertEquals('choice 0 (EN)', $translator->transChoice('choice', 0)); $this->assertEquals('other choice 1 (PT-BR)', $translator->transChoice('other choice', 1)); diff --git a/src/Symfony/Bundle/SecurityBundle/DataCollector/SecurityDataCollector.php b/src/Symfony/Bundle/SecurityBundle/DataCollector/SecurityDataCollector.php index 393bd66542..3e55022f16 100644 --- a/src/Symfony/Bundle/SecurityBundle/DataCollector/SecurityDataCollector.php +++ b/src/Symfony/Bundle/SecurityBundle/DataCollector/SecurityDataCollector.php @@ -150,15 +150,15 @@ class SecurityDataCollector extends DataCollector implements LateDataCollectorIn // collect voter details $decisionLog = $this->accessDecisionManager->getDecisionLog(); foreach ($decisionLog as $key => $log) { - $decisionLog[$key]['voter_details'] = array(); + $decisionLog[$key]['voter_details'] = []; foreach ($log['voterDetails'] as $voterDetail) { $voterClass = \get_class($voterDetail['voter']); $classData = $this->hasVarDumper ? new ClassStub($voterClass) : $voterClass; - $decisionLog[$key]['voter_details'][] = array( + $decisionLog[$key]['voter_details'][] = [ 'class' => $classData, 'attributes' => $voterDetail['attributes'], // Only displayed for unanimous strategy 'vote' => $voterDetail['vote'], - ); + ]; } unset($decisionLog[$key]['voterDetails']); } diff --git a/src/Symfony/Bundle/SecurityBundle/Debug/WrappedListener.php b/src/Symfony/Bundle/SecurityBundle/Debug/WrappedListener.php index 3f3d2c9077..135ac29fc7 100644 --- a/src/Symfony/Bundle/SecurityBundle/Debug/WrappedListener.php +++ b/src/Symfony/Bundle/SecurityBundle/Debug/WrappedListener.php @@ -67,10 +67,10 @@ final class WrappedListener implements ListenerInterface $this->stub = self::$hasVarDumper ? new ClassStub(\get_class($this->listener)) : \get_class($this->listener); } - return array( + return [ 'response' => $this->response, 'time' => $this->time, 'stub' => $this->stub, - ); + ]; } } diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Compiler/AddExpressionLanguageProvidersPass.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Compiler/AddExpressionLanguageProvidersPass.php index 8a4bf0c6e6..898402d359 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Compiler/AddExpressionLanguageProvidersPass.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Compiler/AddExpressionLanguageProvidersPass.php @@ -30,7 +30,7 @@ class AddExpressionLanguageProvidersPass implements CompilerPassInterface if ($container->has('security.expression_language')) { $definition = $container->findDefinition('security.expression_language'); foreach ($container->findTaggedServiceIds('security.expression_language_provider', true) as $id => $attributes) { - $definition->addMethodCall('registerProvider', array(new Reference($id))); + $definition->addMethodCall('registerProvider', [new Reference($id)]); } } } diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Compiler/AddSecurityVotersPass.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Compiler/AddSecurityVotersPass.php index 2b76e2883e..87103c37a3 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Compiler/AddSecurityVotersPass.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Compiler/AddSecurityVotersPass.php @@ -44,7 +44,7 @@ class AddSecurityVotersPass implements CompilerPassInterface } $debug = $container->getParameter('kernel.debug'); - $voterServices = array(); + $voterServices = []; foreach ($voters as $voter) { $voterServiceId = (string) $voter; $definition = $container->getDefinition($voterServiceId); diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/JsonLoginLdapFactory.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/JsonLoginLdapFactory.php index df6d4fc2c9..bd0e8115e9 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/JsonLoginLdapFactory.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/JsonLoginLdapFactory.php @@ -39,7 +39,7 @@ class JsonLoginLdapFactory extends JsonLoginFactory ; if (!empty($config['query_string'])) { - $definition->addMethodCall('setQueryString', array($config['query_string'])); + $definition->addMethodCall('setQueryString', [$config['query_string']]); } return $provider; diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/RememberMeFactory.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/RememberMeFactory.php index 57559e0523..f7500f05e3 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/RememberMeFactory.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/RememberMeFactory.php @@ -142,9 +142,9 @@ class RememberMeFactory implements SecurityFactoryInterface foreach ($this->options as $name => $value) { if ('secure' === $name) { - $builder->enumNode($name)->values(array(true, false, 'auto'))->defaultValue('auto' === $value ? null : $value); + $builder->enumNode($name)->values([true, false, 'auto'])->defaultValue('auto' === $value ? null : $value); } elseif ('samesite' === $name) { - $builder->enumNode($name)->values(array(null, Cookie::SAMESITE_LAX, Cookie::SAMESITE_STRICT))->defaultValue($value); + $builder->enumNode($name)->values([null, Cookie::SAMESITE_LAX, Cookie::SAMESITE_STRICT])->defaultValue($value); } elseif (\is_bool($value)) { $builder->booleanNode($name)->defaultValue($value); } else { diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php index 69e605acf5..108afc2f7c 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php @@ -41,18 +41,18 @@ use Symfony\Component\Security\Http\Controller\UserValueResolver; */ class SecurityExtension extends Extension implements PrependExtensionInterface { - private $requestMatchers = array(); - private $expressions = array(); - private $contextListeners = array(); - private $listenerPositions = array('pre_auth', 'form', 'http', 'remember_me'); - private $factories = array(); - private $userProviderFactories = array(); - private $statelessFirewallKeys = array(); + private $requestMatchers = []; + private $expressions = []; + private $contextListeners = []; + private $listenerPositions = ['pre_auth', 'form', 'http', 'remember_me']; + private $factories = []; + private $userProviderFactories = []; + private $statelessFirewallKeys = []; public function __construct() { foreach ($this->listenerPositions as $position) { - $this->factories[$position] = array(); + $this->factories[$position] = []; } } @@ -183,7 +183,7 @@ class SecurityExtension extends Extension implements PrependExtensionInterface } $container->getDefinition('security.access_map') - ->addMethodCall('add', array($matcher, $attributes, $access['requires_channel'])); + ->addMethodCall('add', [$matcher, $attributes, $access['requires_channel']]); } // allow cache warm-up for expressions @@ -207,7 +207,7 @@ class SecurityExtension extends Extension implements PrependExtensionInterface // make the ContextListener aware of the configured user providers $contextListenerDefinition = $container->getDefinition('security.context_listener'); $arguments = $contextListenerDefinition->getArguments(); - $userProviders = array(); + $userProviders = []; foreach ($providerIds as $userProviderId) { $userProviders[] = new Reference($userProviderId); } @@ -222,7 +222,7 @@ class SecurityExtension extends Extension implements PrependExtensionInterface // load firewall map $mapDef = $container->getDefinition('security.firewall.map'); - $map = $authenticationProviders = $contextRefs = array(); + $map = $authenticationProviders = $contextRefs = []; foreach ($firewalls as $name => $firewall) { if (isset($firewall['user_checker']) && 'security.user_checker' !== $firewall['user_checker']) { $customUserChecker = true; @@ -275,7 +275,7 @@ class SecurityExtension extends Extension implements PrependExtensionInterface } elseif (isset($firewall['pattern']) || isset($firewall['host'])) { $pattern = isset($firewall['pattern']) ? $firewall['pattern'] : null; $host = isset($firewall['host']) ? $firewall['host'] : null; - $methods = isset($firewall['methods']) ? $firewall['methods'] : array(); + $methods = isset($firewall['methods']) ? $firewall['methods'] : []; $matcher = $this->createRequestMatcher($container, $pattern, $host, null, $methods); } @@ -284,7 +284,7 @@ class SecurityExtension extends Extension implements PrependExtensionInterface // Security disabled? if (false === $firewall['security']) { - return array($matcher, array(), null, null); + return [$matcher, [], null, null]; } $config->replaceArgument(4, $firewall['stateless']); @@ -303,8 +303,8 @@ class SecurityExtension extends Extension implements PrependExtensionInterface $config->replaceArgument(5, $defaultProvider); // Register listeners - $listeners = array(); - $listenerKeys = array(); + $listeners = []; + $listenerKeys = []; // Channel listener $listeners[] = new Reference('security.channel_listener'); @@ -328,11 +328,11 @@ class SecurityExtension extends Extension implements PrependExtensionInterface if (isset($firewall['logout'])) { $logoutListenerId = 'security.logout_listener.'.$id; $logoutListener = $container->setDefinition($logoutListenerId, new ChildDefinition('security.logout_listener')); - $logoutListener->replaceArgument(3, array( + $logoutListener->replaceArgument(3, [ 'csrf_parameter' => $firewall['logout']['csrf_parameter'], 'csrf_token_id' => $firewall['logout']['csrf_token_id'], 'logout_path' => $firewall['logout']['path'], - )); + ]); // add logout success handler if (isset($firewall['logout']['success_handler'])) { @@ -351,7 +351,7 @@ class SecurityExtension extends Extension implements PrependExtensionInterface // add session logout handler if (true === $firewall['logout']['invalidate_session'] && false === $firewall['stateless']) { - $logoutListener->addMethodCall('addHandler', array(new Reference('security.logout.handler.session'))); + $logoutListener->addMethodCall('addHandler', [new Reference('security.logout.handler.session')]); } // add cookie logout handler @@ -360,25 +360,25 @@ class SecurityExtension extends Extension implements PrependExtensionInterface $cookieHandler = $container->setDefinition($cookieHandlerId, new ChildDefinition('security.logout.handler.cookie_clearing')); $cookieHandler->addArgument($firewall['logout']['delete_cookies']); - $logoutListener->addMethodCall('addHandler', array(new Reference($cookieHandlerId))); + $logoutListener->addMethodCall('addHandler', [new Reference($cookieHandlerId)]); } // add custom handlers foreach ($firewall['logout']['handlers'] as $handlerId) { - $logoutListener->addMethodCall('addHandler', array(new Reference($handlerId))); + $logoutListener->addMethodCall('addHandler', [new Reference($handlerId)]); } // register with LogoutUrlGenerator $container ->getDefinition('security.logout_url_generator') - ->addMethodCall('registerListener', array( + ->addMethodCall('registerListener', [ $id, $firewall['logout']['path'], $firewall['logout']['csrf_token_id'], $firewall['logout']['csrf_parameter'], isset($firewall['logout']['csrf_token_generator']) ? new Reference($firewall['logout']['csrf_token_generator']) : null, false === $firewall['stateless'] && isset($firewall['context']) ? $firewall['context'] : null, - )) + ]) ; } @@ -425,7 +425,7 @@ class SecurityExtension extends Extension implements PrependExtensionInterface $config->replaceArgument(10, $listenerKeys); $config->replaceArgument(11, isset($firewall['switch_user']) ? $firewall['switch_user'] : null); - return array($matcher, $listeners, $exceptionListener, null !== $logoutListenerId ? new Reference($logoutListenerId) : null); + return [$matcher, $listeners, $exceptionListener, null !== $logoutListenerId ? new Reference($logoutListenerId) : null]; } private function createContextListener($container, $contextKey) @@ -443,7 +443,7 @@ class SecurityExtension extends Extension implements PrependExtensionInterface private function createAuthenticationListeners($container, $id, $firewall, &$authenticationProviders, $defaultProvider = null, array $providerIds, $defaultEntryPoint) { - $listeners = array(); + $listeners = []; $hasListeners = false; foreach ($this->listenerPositions as $position) { @@ -505,19 +505,19 @@ class SecurityExtension extends Extension implements PrependExtensionInterface throw new InvalidConfigurationException(sprintf('No authentication listener registered for firewall "%s".', $id)); } - return array($listeners, $defaultEntryPoint); + return [$listeners, $defaultEntryPoint]; } private function createEncoders($encoders, ContainerBuilder $container) { - $encoderMap = array(); + $encoderMap = []; foreach ($encoders as $class => $encoder) { $encoderMap[$class] = $this->createEncoder($encoder, $container); } $container ->getDefinition('security.encoder_factory.generic') - ->setArguments(array($encoderMap)) + ->setArguments([$encoderMap]) ; } @@ -530,33 +530,33 @@ class SecurityExtension extends Extension implements PrependExtensionInterface // plaintext encoder if ('plaintext' === $config['algorithm']) { - $arguments = array($config['ignore_case']); + $arguments = [$config['ignore_case']]; - return array( + return [ 'class' => 'Symfony\Component\Security\Core\Encoder\PlaintextPasswordEncoder', 'arguments' => $arguments, - ); + ]; } // pbkdf2 encoder if ('pbkdf2' === $config['algorithm']) { - return array( + return [ 'class' => 'Symfony\Component\Security\Core\Encoder\Pbkdf2PasswordEncoder', - 'arguments' => array( + 'arguments' => [ $config['hash_algorithm'], $config['encode_as_base64'], $config['iterations'], $config['key_length'], - ), - ); + ], + ]; } // bcrypt encoder if ('bcrypt' === $config['algorithm']) { - return array( + return [ 'class' => 'Symfony\Component\Security\Core\Encoder\BCryptPasswordEncoder', - 'arguments' => array($config['cost']), - ); + 'arguments' => [$config['cost']], + ]; } // Argon2i encoder @@ -569,14 +569,14 @@ class SecurityExtension extends Extension implements PrependExtensionInterface throw new InvalidConfigurationException('Argon2i algorithm is not supported. Install the libsodium extension or use BCrypt instead.'); } - return array( + return [ 'class' => 'Symfony\Component\Security\Core\Encoder\Argon2iPasswordEncoder', - 'arguments' => array( + 'arguments' => [ $config['memory_cost'], $config['time_cost'], $config['threads'], - ), - ); + ], + ]; } // run-time configured encoder @@ -586,7 +586,7 @@ class SecurityExtension extends Extension implements PrependExtensionInterface // Parses user providers and returns an array of their ids private function createUserProviders($config, ContainerBuilder $container) { - $providerIds = array(); + $providerIds = []; foreach ($config['providers'] as $name => $provider) { $id = $this->createUserDaoProvider($name, $provider, $container); $providerIds[str_replace('-', '_', $name)] = $id; @@ -620,7 +620,7 @@ class SecurityExtension extends Extension implements PrependExtensionInterface // Chain provider if (isset($provider['chain'])) { - $providers = array(); + $providers = []; foreach ($provider['chain']['providers'] as $providerName) { $providers[] = new Reference($this->getUserProviderId($providerName)); } @@ -697,20 +697,20 @@ class SecurityExtension extends Extension implements PrependExtensionInterface return $this->expressions[$id] = new Reference($id); } - private function createRequestMatcher($container, $path = null, $host = null, int $port = null, $methods = array(), $ip = null, array $attributes = array()) + private function createRequestMatcher($container, $path = null, $host = null, int $port = null, $methods = [], $ip = null, array $attributes = []) { if ($methods) { $methods = array_map('strtoupper', (array) $methods); } - $id = '.security.request_matcher.'.ContainerBuilder::hash(array($path, $host, $port, $methods, $ip, $attributes)); + $id = '.security.request_matcher.'.ContainerBuilder::hash([$path, $host, $port, $methods, $ip, $attributes]); if (isset($this->requestMatchers[$id])) { return $this->requestMatchers[$id]; } // only add arguments that are necessary - $arguments = array($path, $host, $methods, $ip, $attributes, null, $port); + $arguments = [$path, $host, $methods, $ip, $attributes, null, $port]; while (\count($arguments) > 0 && !end($arguments)) { array_pop($arguments); } diff --git a/src/Symfony/Bundle/SecurityBundle/EventListener/VoteListener.php b/src/Symfony/Bundle/SecurityBundle/EventListener/VoteListener.php index dd9dddf83b..30956dafcf 100644 --- a/src/Symfony/Bundle/SecurityBundle/EventListener/VoteListener.php +++ b/src/Symfony/Bundle/SecurityBundle/EventListener/VoteListener.php @@ -43,6 +43,6 @@ class VoteListener implements EventSubscriberInterface public static function getSubscribedEvents() { - return array('debug.security.authorization.vote' => 'onVoterVote'); + return ['debug.security.authorization.vote' => 'onVoterVote']; } } diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DataCollector/SecurityDataCollectorTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/DataCollector/SecurityDataCollectorTest.php index ff89aecfa4..e95b354d99 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DataCollector/SecurityDataCollectorTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/DataCollector/SecurityDataCollectorTest.php @@ -97,12 +97,12 @@ class SecurityDataCollectorTest extends TestCase public function testCollectImpersonatedToken() { - $adminToken = new UsernamePasswordToken('yceruto', 'P4$$w0rD', 'provider', array('ROLE_ADMIN')); + $adminToken = new UsernamePasswordToken('yceruto', 'P4$$w0rD', 'provider', ['ROLE_ADMIN']); - $userRoles = array( + $userRoles = [ 'ROLE_USER', new SwitchUserRole('ROLE_PREVIOUS_ADMIN', $adminToken), - ); + ]; $tokenStorage = new TokenStorage(); $tokenStorage->setToken(new UsernamePasswordToken('hhamon', 'P4$$w0rD', 'provider', $userRoles)); @@ -117,8 +117,8 @@ class SecurityDataCollectorTest extends TestCase $this->assertSame('yceruto', $collector->getImpersonatorUser()); $this->assertSame('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken', $collector->getTokenClass()->getValue()); $this->assertTrue($collector->supportsRoleHierarchy()); - $this->assertSame(array('ROLE_USER', 'ROLE_PREVIOUS_ADMIN'), $collector->getRoles()->getValue(true)); - $this->assertSame(array(), $collector->getInheritedRoles()->getValue(true)); + $this->assertSame(['ROLE_USER', 'ROLE_PREVIOUS_ADMIN'], $collector->getRoles()->getValue(true)); + $this->assertSame([], $collector->getInheritedRoles()->getValue(true)); $this->assertSame('hhamon', $collector->getUser()); } @@ -213,7 +213,7 @@ class SecurityDataCollectorTest extends TestCase ->expects($this->once()) ->method('getListeners') ->with($request) - ->willReturn(array(array($listener), null, null)); + ->willReturn([[$listener], null, null]); $firewall = new TraceableFirewallListener($firewallMap, new EventDispatcher(), new LogoutUrlGenerator()); $firewall->onKernelRequest($event); @@ -235,79 +235,79 @@ class SecurityDataCollectorTest extends TestCase $decoratedVoter1 = new TraceableVoter($voter1, $eventDispatcher); $decoratedVoter2 = new TraceableVoter($voter2, $eventDispatcher); - yield array( + yield [ AccessDecisionManager::STRATEGY_AFFIRMATIVE, - array(array( - 'attributes' => array('view'), + [[ + 'attributes' => ['view'], 'object' => new \stdClass(), 'result' => true, - 'voterDetails' => array( - array('voter' => $voter1, 'attributes' => array('view'), 'vote' => VoterInterface::ACCESS_ABSTAIN), - array('voter' => $voter2, 'attributes' => array('view'), 'vote' => VoterInterface::ACCESS_ABSTAIN), - ), - )), - array($decoratedVoter1, $decoratedVoter1), - array(\get_class($voter1), \get_class($voter2)), - array(array( - 'attributes' => array('view'), + 'voterDetails' => [ + ['voter' => $voter1, 'attributes' => ['view'], 'vote' => VoterInterface::ACCESS_ABSTAIN], + ['voter' => $voter2, 'attributes' => ['view'], 'vote' => VoterInterface::ACCESS_ABSTAIN], + ], + ]], + [$decoratedVoter1, $decoratedVoter1], + [\get_class($voter1), \get_class($voter2)], + [[ + 'attributes' => ['view'], 'object' => new \stdClass(), 'result' => true, - 'voter_details' => array( - array('class' => \get_class($voter1), 'attributes' => array('view'), 'vote' => VoterInterface::ACCESS_ABSTAIN), - array('class' => \get_class($voter2), 'attributes' => array('view'), 'vote' => VoterInterface::ACCESS_ABSTAIN), - ), - )), - ); + 'voter_details' => [ + ['class' => \get_class($voter1), 'attributes' => ['view'], 'vote' => VoterInterface::ACCESS_ABSTAIN], + ['class' => \get_class($voter2), 'attributes' => ['view'], 'vote' => VoterInterface::ACCESS_ABSTAIN], + ], + ]], + ]; - yield array( + yield [ AccessDecisionManager::STRATEGY_UNANIMOUS, - array( - array( - 'attributes' => array('view', 'edit'), + [ + [ + 'attributes' => ['view', 'edit'], 'object' => new \stdClass(), 'result' => false, - 'voterDetails' => array( - array('voter' => $voter1, 'attributes' => array('view'), 'vote' => VoterInterface::ACCESS_DENIED), - array('voter' => $voter1, 'attributes' => array('edit'), 'vote' => VoterInterface::ACCESS_DENIED), - array('voter' => $voter2, 'attributes' => array('view'), 'vote' => VoterInterface::ACCESS_GRANTED), - array('voter' => $voter2, 'attributes' => array('edit'), 'vote' => VoterInterface::ACCESS_GRANTED), - ), - ), - array( - 'attributes' => array('update'), + 'voterDetails' => [ + ['voter' => $voter1, 'attributes' => ['view'], 'vote' => VoterInterface::ACCESS_DENIED], + ['voter' => $voter1, 'attributes' => ['edit'], 'vote' => VoterInterface::ACCESS_DENIED], + ['voter' => $voter2, 'attributes' => ['view'], 'vote' => VoterInterface::ACCESS_GRANTED], + ['voter' => $voter2, 'attributes' => ['edit'], 'vote' => VoterInterface::ACCESS_GRANTED], + ], + ], + [ + 'attributes' => ['update'], 'object' => new \stdClass(), 'result' => true, - 'voterDetails' => array( - array('voter' => $voter1, 'attributes' => array('update'), 'vote' => VoterInterface::ACCESS_GRANTED), - array('voter' => $voter2, 'attributes' => array('update'), 'vote' => VoterInterface::ACCESS_GRANTED), - ), - ), - ), - array($decoratedVoter1, $decoratedVoter1), - array(\get_class($voter1), \get_class($voter2)), - array( - array( - 'attributes' => array('view', 'edit'), + 'voterDetails' => [ + ['voter' => $voter1, 'attributes' => ['update'], 'vote' => VoterInterface::ACCESS_GRANTED], + ['voter' => $voter2, 'attributes' => ['update'], 'vote' => VoterInterface::ACCESS_GRANTED], + ], + ], + ], + [$decoratedVoter1, $decoratedVoter1], + [\get_class($voter1), \get_class($voter2)], + [ + [ + 'attributes' => ['view', 'edit'], 'object' => new \stdClass(), 'result' => false, - 'voter_details' => array( - array('class' => \get_class($voter1), 'attributes' => array('view'), 'vote' => VoterInterface::ACCESS_DENIED), - array('class' => \get_class($voter1), 'attributes' => array('edit'), 'vote' => VoterInterface::ACCESS_DENIED), - array('class' => \get_class($voter2), 'attributes' => array('view'), 'vote' => VoterInterface::ACCESS_GRANTED), - array('class' => \get_class($voter2), 'attributes' => array('edit'), 'vote' => VoterInterface::ACCESS_GRANTED), - ), - ), - array( - 'attributes' => array('update'), + 'voter_details' => [ + ['class' => \get_class($voter1), 'attributes' => ['view'], 'vote' => VoterInterface::ACCESS_DENIED], + ['class' => \get_class($voter1), 'attributes' => ['edit'], 'vote' => VoterInterface::ACCESS_DENIED], + ['class' => \get_class($voter2), 'attributes' => ['view'], 'vote' => VoterInterface::ACCESS_GRANTED], + ['class' => \get_class($voter2), 'attributes' => ['edit'], 'vote' => VoterInterface::ACCESS_GRANTED], + ], + ], + [ + 'attributes' => ['update'], 'object' => new \stdClass(), 'result' => true, - 'voter_details' => array( - array('class' => \get_class($voter1), 'attributes' => array('update'), 'vote' => VoterInterface::ACCESS_GRANTED), - array('class' => \get_class($voter2), 'attributes' => array('update'), 'vote' => VoterInterface::ACCESS_GRANTED), - ), - ), - ), - ); + 'voter_details' => [ + ['class' => \get_class($voter1), 'attributes' => ['update'], 'vote' => VoterInterface::ACCESS_GRANTED], + ['class' => \get_class($voter2), 'attributes' => ['update'], 'vote' => VoterInterface::ACCESS_GRANTED], + ], + ], + ], + ]; } /** @@ -326,7 +326,7 @@ class SecurityDataCollectorTest extends TestCase $accessDecisionManager = $this ->getMockBuilder(TraceableAccessDecisionManager::class) ->disableOriginalConstructor() - ->setMethods(array('getStrategy', 'getVoters', 'getDecisionLog')) + ->setMethods(['getStrategy', 'getVoters', 'getDecisionLog']) ->getMock(); $accessDecisionManager @@ -359,43 +359,43 @@ class SecurityDataCollectorTest extends TestCase public function provideRoles() { - return array( + return [ // Basic roles - array( - array('ROLE_USER'), - array('ROLE_USER'), - array(), - ), - array( - array(new Role('ROLE_USER')), - array('ROLE_USER'), - array(), - ), + [ + ['ROLE_USER'], + ['ROLE_USER'], + [], + ], + [ + [new Role('ROLE_USER')], + ['ROLE_USER'], + [], + ], // Inherited roles - array( - array('ROLE_ADMIN'), - array('ROLE_ADMIN'), - array('ROLE_USER', 'ROLE_ALLOWED_TO_SWITCH'), - ), - array( - array(new Role('ROLE_ADMIN')), - array('ROLE_ADMIN'), - array('ROLE_USER', 'ROLE_ALLOWED_TO_SWITCH'), - ), - array( - array('ROLE_ADMIN', 'ROLE_OPERATOR'), - array('ROLE_ADMIN', 'ROLE_OPERATOR'), - array('ROLE_USER', 'ROLE_ALLOWED_TO_SWITCH'), - ), - ); + [ + ['ROLE_ADMIN'], + ['ROLE_ADMIN'], + ['ROLE_USER', 'ROLE_ALLOWED_TO_SWITCH'], + ], + [ + [new Role('ROLE_ADMIN')], + ['ROLE_ADMIN'], + ['ROLE_USER', 'ROLE_ALLOWED_TO_SWITCH'], + ], + [ + ['ROLE_ADMIN', 'ROLE_OPERATOR'], + ['ROLE_ADMIN', 'ROLE_OPERATOR'], + ['ROLE_USER', 'ROLE_ALLOWED_TO_SWITCH'], + ], + ]; } private function getRoleHierarchy() { - return new RoleHierarchy(array( - 'ROLE_ADMIN' => array('ROLE_USER', 'ROLE_ALLOWED_TO_SWITCH'), - 'ROLE_OPERATOR' => array('ROLE_USER'), - )); + return new RoleHierarchy([ + 'ROLE_ADMIN' => ['ROLE_USER', 'ROLE_ALLOWED_TO_SWITCH'], + 'ROLE_OPERATOR' => ['ROLE_USER'], + ]); } private function getRequest() diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/Debug/TraceableFirewallListenerTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/Debug/TraceableFirewallListenerTest.php index c77ed14dc6..bf5b8c5099 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/Debug/TraceableFirewallListenerTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/Debug/TraceableFirewallListenerTest.php @@ -51,7 +51,7 @@ class TraceableFirewallListenerTest extends TestCase ->expects($this->once()) ->method('getListeners') ->with($request) - ->willReturn(array(array($listener), null, null)); + ->willReturn([[$listener], null, null]); $firewall = new TraceableFirewallListener($firewallMap, new EventDispatcher(), new LogoutUrlGenerator()); $firewall->onKernelRequest($event); diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Compiler/AddSecurityVotersPassTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Compiler/AddSecurityVotersPassTest.php index 718e9703df..93d4121553 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Compiler/AddSecurityVotersPassTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Compiler/AddSecurityVotersPassTest.php @@ -86,7 +86,7 @@ class AddSecurityVotersPassTest extends TestCase $container ->register('security.access.decision_manager', AccessDecisionManager::class) - ->addArgument(array($voterDef1, $voterDef2)); + ->addArgument([$voterDef1, $voterDef2]); $container->setParameter('kernel.debug', true); $compilerPass = new AddSecurityVotersPass(); @@ -119,7 +119,7 @@ class AddSecurityVotersPassTest extends TestCase $container ->register('security.access.decision_manager', AccessDecisionManager::class) - ->addArgument(array($voterDef1, $voterDef2)); + ->addArgument([$voterDef1, $voterDef2]); $compilerPass = new AddSecurityVotersPass(); $compilerPass->process($container); diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Compiler/AddSessionDomainConstraintPassTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Compiler/AddSessionDomainConstraintPassTest.php index ba3d555cf6..7dcf7526bd 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Compiler/AddSessionDomainConstraintPassTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Compiler/AddSessionDomainConstraintPassTest.php @@ -22,7 +22,7 @@ class AddSessionDomainConstraintPassTest extends TestCase { public function testSessionCookie() { - $container = $this->createContainer(array('cookie_domain' => '.symfony.com.', 'cookie_secure' => true)); + $container = $this->createContainer(['cookie_domain' => '.symfony.com.', 'cookie_secure' => true]); $utils = $container->get('security.http_utils'); $request = Request::create('/', 'get'); @@ -37,7 +37,7 @@ class AddSessionDomainConstraintPassTest extends TestCase public function testSessionNoDomain() { - $container = $this->createContainer(array('cookie_secure' => true)); + $container = $this->createContainer(['cookie_secure' => true]); $utils = $container->get('security.http_utils'); $request = Request::create('/', 'get'); @@ -52,7 +52,7 @@ class AddSessionDomainConstraintPassTest extends TestCase public function testSessionNoSecure() { - $container = $this->createContainer(array('cookie_domain' => '.symfony.com.')); + $container = $this->createContainer(['cookie_domain' => '.symfony.com.']); $utils = $container->get('security.http_utils'); $request = Request::create('/', 'get'); @@ -67,7 +67,7 @@ class AddSessionDomainConstraintPassTest extends TestCase public function testSessionNoSecureAndNoDomain() { - $container = $this->createContainer(array()); + $container = $this->createContainer([]); $utils = $container->get('security.http_utils'); $request = Request::create('/', 'get'); @@ -98,7 +98,7 @@ class AddSessionDomainConstraintPassTest extends TestCase public function testSessionAutoSecure() { - $container = $this->createContainer(array('cookie_domain' => '.symfony.com.', 'cookie_secure' => 'auto')); + $container = $this->createContainer(['cookie_domain' => '.symfony.com.', 'cookie_secure' => 'auto']); $utils = $container->get('security.http_utils'); $request = Request::create('/', 'get'); @@ -119,7 +119,7 @@ class AddSessionDomainConstraintPassTest extends TestCase private function createContainer($sessionStorageOptions) { $container = new ContainerBuilder(); - $container->setParameter('kernel.bundles_metadata', array()); + $container->setParameter('kernel.bundles_metadata', []); $container->setParameter('kernel.cache_dir', __DIR__); $container->setParameter('kernel.charset', 'UTF-8'); $container->setParameter('kernel.container_class', 'cc'); @@ -133,15 +133,15 @@ class AddSessionDomainConstraintPassTest extends TestCase $container->setParameter('request_listener.http_port', 80); $container->setParameter('request_listener.https_port', 443); - $config = array( - 'security' => array( - 'providers' => array('some_provider' => array('id' => 'foo')), - 'firewalls' => array('some_firewall' => array('security' => false)), - ), - ); + $config = [ + 'security' => [ + 'providers' => ['some_provider' => ['id' => 'foo']], + 'firewalls' => ['some_firewall' => ['security' => false]], + ], + ]; $ext = new FrameworkExtension(); - $ext->load(array('framework' => array('csrf_protection' => false, 'router' => array('resource' => 'dummy'))), $container); + $ext->load(['framework' => ['csrf_protection' => false, 'router' => ['resource' => 'dummy']]], $container); $ext = new SecurityExtension(); $ext->load($config, $container); diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/CompleteConfigurationTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/CompleteConfigurationTest.php index 01908413bf..c2511ff280 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/CompleteConfigurationTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/CompleteConfigurationTest.php @@ -29,11 +29,11 @@ abstract class CompleteConfigurationTest extends TestCase public function testRolesHierarchy() { $container = $this->getContainer('container1'); - $this->assertEquals(array( - 'ROLE_ADMIN' => array('ROLE_USER'), - 'ROLE_SUPER_ADMIN' => array('ROLE_USER', 'ROLE_ADMIN', 'ROLE_ALLOWED_TO_SWITCH'), - 'ROLE_REMOTE' => array('ROLE_USER', 'ROLE_ADMIN'), - ), $container->getParameter('security.role_hierarchy.roles')); + $this->assertEquals([ + 'ROLE_ADMIN' => ['ROLE_USER'], + 'ROLE_SUPER_ADMIN' => ['ROLE_USER', 'ROLE_ADMIN', 'ROLE_ALLOWED_TO_SWITCH'], + 'ROLE_REMOTE' => ['ROLE_USER', 'ROLE_ADMIN'], + ], $container->getParameter('security.role_hierarchy.roles')); } public function testUserProviders() @@ -42,30 +42,30 @@ abstract class CompleteConfigurationTest extends TestCase $providers = array_values(array_filter($container->getServiceIds(), function ($key) { return 0 === strpos($key, 'security.user.provider.concrete'); })); - $expectedProviders = array( + $expectedProviders = [ 'security.user.provider.concrete.default', 'security.user.provider.concrete.digest', 'security.user.provider.concrete.basic', 'security.user.provider.concrete.service', 'security.user.provider.concrete.chain', - ); + ]; - $this->assertEquals(array(), array_diff($expectedProviders, $providers)); - $this->assertEquals(array(), array_diff($providers, $expectedProviders)); + $this->assertEquals([], array_diff($expectedProviders, $providers)); + $this->assertEquals([], array_diff($providers, $expectedProviders)); // chain provider - $this->assertEquals(array(new IteratorArgument(array( + $this->assertEquals([new IteratorArgument([ new Reference('security.user.provider.concrete.service'), new Reference('security.user.provider.concrete.basic'), - ))), $container->getDefinition('security.user.provider.concrete.chain')->getArguments()); + ])], $container->getDefinition('security.user.provider.concrete.chain')->getArguments()); } public function testFirewalls() { $container = $this->getContainer('container1'); $arguments = $container->getDefinition('security.firewall.map')->getArguments(); - $listeners = array(); - $configs = array(); + $listeners = []; + $configs = []; foreach (array_keys($arguments[1]->getValues()) as $contextId) { $contextDef = $container->getDefinition($contextId); $arguments = $contextDef->getArguments(); @@ -80,14 +80,14 @@ abstract class CompleteConfigurationTest extends TestCase $configs[0][2] = strtolower($configs[0][2]); $configs[2][2] = strtolower($configs[2][2]); - $this->assertEquals(array( - array( + $this->assertEquals([ + [ 'simple', 'security.user_checker', '.security.request_matcher.xmi9dcw', false, - ), - array( + ], + [ 'secure', 'security.user_checker', null, @@ -98,7 +98,7 @@ abstract class CompleteConfigurationTest extends TestCase 'security.authentication.form_entry_point.secure', null, null, - array( + [ 'switch_user', 'x509', 'remote_user', @@ -106,14 +106,14 @@ abstract class CompleteConfigurationTest extends TestCase 'http_basic', 'remember_me', 'anonymous', - ), - array( + ], + [ 'parameter' => '_switch_user', 'role' => 'ROLE_ALLOWED_TO_SWITCH', 'stateless' => false, - ), - ), - array( + ], + ], + [ 'host', 'security.user_checker', '.security.request_matcher.iw4hyjb', @@ -124,13 +124,13 @@ abstract class CompleteConfigurationTest extends TestCase 'security.authentication.basic_entry_point.host', null, null, - array( + [ 'http_basic', 'anonymous', - ), + ], null, - ), - array( + ], + [ 'with_user_checker', 'app.user_checker', null, @@ -141,17 +141,17 @@ abstract class CompleteConfigurationTest extends TestCase 'security.authentication.basic_entry_point.with_user_checker', null, null, - array( + [ 'http_basic', 'anonymous', - ), + ], null, - ), - ), $configs); + ], + ], $configs); - $this->assertEquals(array( - array(), - array( + $this->assertEquals([ + [], + [ 'security.channel_listener', 'security.authentication.listener.x509.secure', 'security.authentication.listener.remote_user.secure', @@ -161,22 +161,22 @@ abstract class CompleteConfigurationTest extends TestCase 'security.authentication.listener.anonymous.secure', 'security.authentication.switchuser_listener.secure', 'security.access_listener', - ), - array( + ], + [ 'security.channel_listener', 'security.context_listener.0', 'security.authentication.listener.basic.host', 'security.authentication.listener.anonymous.host', 'security.access_listener', - ), - array( + ], + [ 'security.channel_listener', 'security.context_listener.1', 'security.authentication.listener.basic.with_user_checker', 'security.authentication.listener.anonymous.with_user_checker', 'security.access_listener', - ), - ), $listeners); + ], + ], $listeners); $this->assertFalse($container->hasAlias('Symfony\Component\Security\Core\User\UserCheckerInterface', 'No user checker alias is registered when custom user checker services are registered')); } @@ -186,7 +186,7 @@ abstract class CompleteConfigurationTest extends TestCase $container = $this->getContainer('container1'); $arguments = $container->getDefinition('security.firewall.map')->getArguments(); - $matchers = array(); + $matchers = []; foreach ($arguments[1]->getValues() as $reference) { if ($reference instanceof Reference) { @@ -195,16 +195,16 @@ abstract class CompleteConfigurationTest extends TestCase } } - $this->assertEquals(array( - array( + $this->assertEquals([ + [ '/login', - ), - array( + ], + [ '/test', 'foo\\.example\\.org', - array('GET', 'POST'), - ), - ), $matchers); + ['GET', 'POST'], + ], + ], $matchers); } public function testUserCheckerAliasIsRegistered() @@ -219,14 +219,14 @@ abstract class CompleteConfigurationTest extends TestCase { $container = $this->getContainer('container1'); - $rules = array(); + $rules = []; foreach ($container->getDefinition('security.access_map')->getMethodCalls() as $call) { if ('add' == $call[0]) { - $rules[] = array((string) $call[1][0], $call[1][1], $call[1][2]); + $rules[] = [(string) $call[1][0], $call[1][1], $call[1][2]]; } } - $matcherIds = array(); + $matcherIds = []; foreach ($rules as list($matcherId, $attributes, $channel)) { $requestMatcher = $container->getDefinition($matcherId); @@ -235,17 +235,17 @@ abstract class CompleteConfigurationTest extends TestCase $i = \count($matcherIds); if (1 === $i) { - $this->assertEquals(array('ROLE_USER'), $attributes); + $this->assertEquals(['ROLE_USER'], $attributes); $this->assertEquals('https', $channel); $this->assertEquals( - array('/blog/524', null, array('GET', 'POST'), array(), array(), null, 8000), + ['/blog/524', null, ['GET', 'POST'], [], [], null, 8000], $requestMatcher->getArguments() ); } elseif (2 === $i) { - $this->assertEquals(array('IS_AUTHENTICATED_ANONYMOUSLY'), $attributes); + $this->assertEquals(['IS_AUTHENTICATED_ANONYMOUSLY'], $attributes); $this->assertNull($channel); $this->assertEquals( - array('/blog/.*'), + ['/blog/.*'], $requestMatcher->getArguments() ); } elseif (3 === $i) { @@ -260,22 +260,22 @@ abstract class CompleteConfigurationTest extends TestCase { $container = $this->getContainer('merge'); - $this->assertEquals(array( - 'FOO' => array('MOO'), - 'ADMIN' => array('USER'), - ), $container->getParameter('security.role_hierarchy.roles')); + $this->assertEquals([ + 'FOO' => ['MOO'], + 'ADMIN' => ['USER'], + ], $container->getParameter('security.role_hierarchy.roles')); } public function testEncoders() { $container = $this->getContainer('container1'); - $this->assertEquals(array(array( - 'JMS\FooBundle\Entity\User1' => array( + $this->assertEquals([[ + 'JMS\FooBundle\Entity\User1' => [ 'class' => 'Symfony\Component\Security\Core\Encoder\PlaintextPasswordEncoder', - 'arguments' => array(false), - ), - 'JMS\FooBundle\Entity\User2' => array( + 'arguments' => [false], + ], + 'JMS\FooBundle\Entity\User2' => [ 'algorithm' => 'sha1', 'encode_as_base64' => false, 'iterations' => 5, @@ -286,8 +286,8 @@ abstract class CompleteConfigurationTest extends TestCase 'memory_cost' => null, 'time_cost' => null, 'threads' => null, - ), - 'JMS\FooBundle\Entity\User3' => array( + ], + 'JMS\FooBundle\Entity\User3' => [ 'algorithm' => 'md5', 'hash_algorithm' => 'sha512', 'key_length' => 40, @@ -298,17 +298,17 @@ abstract class CompleteConfigurationTest extends TestCase 'memory_cost' => null, 'time_cost' => null, 'threads' => null, - ), + ], 'JMS\FooBundle\Entity\User4' => new Reference('security.encoder.foo'), - 'JMS\FooBundle\Entity\User5' => array( + 'JMS\FooBundle\Entity\User5' => [ 'class' => 'Symfony\Component\Security\Core\Encoder\Pbkdf2PasswordEncoder', - 'arguments' => array('sha1', false, 5, 30), - ), - 'JMS\FooBundle\Entity\User6' => array( + 'arguments' => ['sha1', false, 5, 30], + ], + 'JMS\FooBundle\Entity\User6' => [ 'class' => 'Symfony\Component\Security\Core\Encoder\BCryptPasswordEncoder', - 'arguments' => array(15), - ), - )), $container->getDefinition('security.encoder_factory.generic')->getArguments()); + 'arguments' => [15], + ], + ]], $container->getDefinition('security.encoder_factory.generic')->getArguments()); } public function testEncodersWithLibsodium() @@ -319,12 +319,12 @@ abstract class CompleteConfigurationTest extends TestCase $container = $this->getContainer('argon2i_encoder'); - $this->assertEquals(array(array( - 'JMS\FooBundle\Entity\User1' => array( + $this->assertEquals([[ + 'JMS\FooBundle\Entity\User1' => [ 'class' => 'Symfony\Component\Security\Core\Encoder\PlaintextPasswordEncoder', - 'arguments' => array(false), - ), - 'JMS\FooBundle\Entity\User2' => array( + 'arguments' => [false], + ], + 'JMS\FooBundle\Entity\User2' => [ 'algorithm' => 'sha1', 'encode_as_base64' => false, 'iterations' => 5, @@ -335,8 +335,8 @@ abstract class CompleteConfigurationTest extends TestCase 'memory_cost' => null, 'time_cost' => null, 'threads' => null, - ), - 'JMS\FooBundle\Entity\User3' => array( + ], + 'JMS\FooBundle\Entity\User3' => [ 'algorithm' => 'md5', 'hash_algorithm' => 'sha512', 'key_length' => 40, @@ -347,21 +347,21 @@ abstract class CompleteConfigurationTest extends TestCase 'memory_cost' => null, 'time_cost' => null, 'threads' => null, - ), + ], 'JMS\FooBundle\Entity\User4' => new Reference('security.encoder.foo'), - 'JMS\FooBundle\Entity\User5' => array( + 'JMS\FooBundle\Entity\User5' => [ 'class' => 'Symfony\Component\Security\Core\Encoder\Pbkdf2PasswordEncoder', - 'arguments' => array('sha1', false, 5, 30), - ), - 'JMS\FooBundle\Entity\User6' => array( + 'arguments' => ['sha1', false, 5, 30], + ], + 'JMS\FooBundle\Entity\User6' => [ 'class' => 'Symfony\Component\Security\Core\Encoder\BCryptPasswordEncoder', - 'arguments' => array(15), - ), - 'JMS\FooBundle\Entity\User7' => array( + 'arguments' => [15], + ], + 'JMS\FooBundle\Entity\User7' => [ 'class' => 'Symfony\Component\Security\Core\Encoder\Argon2iPasswordEncoder', - 'arguments' => array(256, 1, 2), - ), - )), $container->getDefinition('security.encoder_factory.generic')->getArguments()); + 'arguments' => [256, 1, 2], + ], + ]], $container->getDefinition('security.encoder_factory.generic')->getArguments()); } public function testRememberMeThrowExceptionsDefault() @@ -470,8 +470,8 @@ abstract class CompleteConfigurationTest extends TestCase { $container = $this->getContainer('simple_auth'); $arguments = $container->getDefinition('security.firewall.map')->getArguments(); - $listeners = array(); - $configs = array(); + $listeners = []; + $configs = []; foreach (array_keys($arguments[1]->getValues()) as $contextId) { $contextDef = $container->getDefinition($contextId); $arguments = $contextDef->getArguments(); @@ -481,7 +481,7 @@ abstract class CompleteConfigurationTest extends TestCase $configs[] = array_values($configDef->getArguments()); } - $this->assertSame(array(array( + $this->assertSame([[ 'simple_auth', 'security.user_checker', null, @@ -492,18 +492,18 @@ abstract class CompleteConfigurationTest extends TestCase 'security.authentication.form_entry_point.simple_auth', null, null, - array('simple_form', 'anonymous', - ), + ['simple_form', 'anonymous', + ], null, - )), $configs); + ]], $configs); - $this->assertSame(array(array( + $this->assertSame([[ 'security.channel_listener', 'security.context_listener.0', 'security.authentication.listener.simple_form.simple_auth', 'security.authentication.listener.anonymous.simple_auth', 'security.access_listener', - )), $listeners); + ]], $listeners); } protected function getContainer($file) @@ -520,8 +520,8 @@ abstract class CompleteConfigurationTest extends TestCase $bundle->build($container); // Attach all default factories $this->getLoader($container)->load($file); - $container->getCompilerPassConfig()->setOptimizationPasses(array()); - $container->getCompilerPassConfig()->setRemovingPasses(array()); + $container->getCompilerPassConfig()->setOptimizationPasses([]); + $container->getCompilerPassConfig()->setRemovingPasses([]); $container->compile(); return $container; diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Fixtures/php/container1.php b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Fixtures/php/container1.php index c2952a1ad0..f420d4d8af 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Fixtures/php/container1.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Fixtures/php/container1.php @@ -1,67 +1,67 @@ loadFromExtension('security', array( - 'encoders' => array( +$container->loadFromExtension('security', [ + 'encoders' => [ 'JMS\FooBundle\Entity\User1' => 'plaintext', - 'JMS\FooBundle\Entity\User2' => array( + 'JMS\FooBundle\Entity\User2' => [ 'algorithm' => 'sha1', 'encode_as_base64' => false, 'iterations' => 5, - ), - 'JMS\FooBundle\Entity\User3' => array( + ], + 'JMS\FooBundle\Entity\User3' => [ 'algorithm' => 'md5', - ), - 'JMS\FooBundle\Entity\User4' => array( + ], + 'JMS\FooBundle\Entity\User4' => [ 'id' => 'security.encoder.foo', - ), - 'JMS\FooBundle\Entity\User5' => array( + ], + 'JMS\FooBundle\Entity\User5' => [ 'algorithm' => 'pbkdf2', 'hash_algorithm' => 'sha1', 'encode_as_base64' => false, 'iterations' => 5, 'key_length' => 30, - ), - 'JMS\FooBundle\Entity\User6' => array( + ], + 'JMS\FooBundle\Entity\User6' => [ 'algorithm' => 'bcrypt', 'cost' => 15, - ), - ), - 'providers' => array( - 'default' => array( - 'memory' => array( - 'users' => array( - 'foo' => array('password' => 'foo', 'roles' => 'ROLE_USER'), - ), - ), - ), - 'digest' => array( - 'memory' => array( - 'users' => array( - 'foo' => array('password' => 'foo', 'roles' => 'ROLE_USER, ROLE_ADMIN'), - ), - ), - ), - 'basic' => array( - 'memory' => array( - 'users' => array( - 'foo' => array('password' => '0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33', 'roles' => 'ROLE_SUPER_ADMIN'), - 'bar' => array('password' => '0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33', 'roles' => array('ROLE_USER', 'ROLE_ADMIN')), - ), - ), - ), - 'service' => array( + ], + ], + 'providers' => [ + 'default' => [ + 'memory' => [ + 'users' => [ + 'foo' => ['password' => 'foo', 'roles' => 'ROLE_USER'], + ], + ], + ], + 'digest' => [ + 'memory' => [ + 'users' => [ + 'foo' => ['password' => 'foo', 'roles' => 'ROLE_USER, ROLE_ADMIN'], + ], + ], + ], + 'basic' => [ + 'memory' => [ + 'users' => [ + 'foo' => ['password' => '0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33', 'roles' => 'ROLE_SUPER_ADMIN'], + 'bar' => ['password' => '0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33', 'roles' => ['ROLE_USER', 'ROLE_ADMIN']], + ], + ], + ], + 'service' => [ 'id' => 'user.manager', - ), - 'chain' => array( - 'chain' => array( - 'providers' => array('service', 'basic'), - ), - ), - ), + ], + 'chain' => [ + 'chain' => [ + 'providers' => ['service', 'basic'], + ], + ], + ], - 'firewalls' => array( - 'simple' => array('provider' => 'default', 'pattern' => '/login', 'security' => false), - 'secure' => array('stateless' => true, + 'firewalls' => [ + 'simple' => ['provider' => 'default', 'pattern' => '/login', 'security' => false], + 'secure' => ['stateless' => true, 'provider' => 'default', 'http_basic' => true, 'form_login' => true, @@ -70,34 +70,34 @@ $container->loadFromExtension('security', array( 'x509' => true, 'remote_user' => true, 'logout' => true, - 'remember_me' => array('secret' => 'TheSecret'), + 'remember_me' => ['secret' => 'TheSecret'], 'user_checker' => null, - ), - 'host' => array( + ], + 'host' => [ 'provider' => 'default', 'pattern' => '/test', 'host' => 'foo\\.example\\.org', - 'methods' => array('GET', 'POST'), + 'methods' => ['GET', 'POST'], 'anonymous' => true, 'http_basic' => true, - ), - 'with_user_checker' => array( + ], + 'with_user_checker' => [ 'provider' => 'default', 'user_checker' => 'app.user_checker', 'anonymous' => true, 'http_basic' => true, - ), - ), + ], + ], - 'access_control' => array( - array('path' => '/blog/524', 'role' => 'ROLE_USER', 'requires_channel' => 'https', 'methods' => array('get', 'POST'), 'port' => 8000), - array('path' => '/blog/.*', 'role' => 'IS_AUTHENTICATED_ANONYMOUSLY'), - array('path' => '/blog/524', 'role' => 'IS_AUTHENTICATED_ANONYMOUSLY', 'allow_if' => "token.getUsername() matches '/^admin/'"), - ), + 'access_control' => [ + ['path' => '/blog/524', 'role' => 'ROLE_USER', 'requires_channel' => 'https', 'methods' => ['get', 'POST'], 'port' => 8000], + ['path' => '/blog/.*', 'role' => 'IS_AUTHENTICATED_ANONYMOUSLY'], + ['path' => '/blog/524', 'role' => 'IS_AUTHENTICATED_ANONYMOUSLY', 'allow_if' => "token.getUsername() matches '/^admin/'"], + ], - 'role_hierarchy' => array( + 'role_hierarchy' => [ 'ROLE_ADMIN' => 'ROLE_USER', - 'ROLE_SUPER_ADMIN' => array('ROLE_USER', 'ROLE_ADMIN', 'ROLE_ALLOWED_TO_SWITCH'), + 'ROLE_SUPER_ADMIN' => ['ROLE_USER', 'ROLE_ADMIN', 'ROLE_ALLOWED_TO_SWITCH'], 'ROLE_REMOTE' => 'ROLE_USER,ROLE_ADMIN', - ), -)); + ], +]); diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Fixtures/php/simple_auth.php b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Fixtures/php/simple_auth.php index a125dec6b5..05829defd1 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Fixtures/php/simple_auth.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Fixtures/php/simple_auth.php @@ -1,21 +1,21 @@ loadFromExtension('security', array( - 'providers' => array( - 'default' => array( - 'memory' => array( - 'users' => array( - 'foo' => array('password' => 'foo', 'roles' => 'ROLE_USER'), - ), - ), - ), - ), +$container->loadFromExtension('security', [ + 'providers' => [ + 'default' => [ + 'memory' => [ + 'users' => [ + 'foo' => ['password' => 'foo', 'roles' => 'ROLE_USER'], + ], + ], + ], + ], - 'firewalls' => array( - 'simple_auth' => array( + 'firewalls' => [ + 'simple_auth' => [ 'provider' => 'default', 'anonymous' => true, - 'simple_form' => array('authenticator' => 'simple_authenticator'), - ), - ), -)); + 'simple_form' => ['authenticator' => 'simple_authenticator'], + ], + ], +]); diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/SecurityExtensionTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/SecurityExtensionTest.php index 50c2a64cd6..3145d03572 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/SecurityExtensionTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/SecurityExtensionTest.php @@ -352,22 +352,22 @@ class SecurityExtensionTest extends TestCase $container = $this->getRawContainer(); $container->registerExtension(new FrameworkExtension()); - $container->setParameter('kernel.bundles_metadata', array()); + $container->setParameter('kernel.bundles_metadata', []); $container->setParameter('kernel.project_dir', __DIR__); $container->setParameter('kernel.root_dir', __DIR__); $container->setParameter('kernel.cache_dir', __DIR__); - $container->loadFromExtension('security', array( - 'firewalls' => array( - 'default' => array( + $container->loadFromExtension('security', [ + 'firewalls' => [ + 'default' => [ 'form_login' => null, - 'remember_me' => array('secret' => 'baz'), - ), - ), - )); - $container->loadFromExtension('framework', array( + 'remember_me' => ['secret' => 'baz'], + ], + ], + ]); + $container->loadFromExtension('framework', [ 'session' => $config, - )); + ]); $container->compile(); @@ -379,22 +379,22 @@ class SecurityExtensionTest extends TestCase public function sessionConfigurationProvider() { - return array( - array( + return [ + [ false, null, false, - ), - array( - array( + ], + [ + [ 'cookie_secure' => true, 'cookie_samesite' => 'lax', 'save_path' => null, - ), + ], 'lax', true, - ), - ); + ], + ]; } protected function getRawContainer() diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/EventListener/VoteListenerTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/EventListener/VoteListenerTest.php index 52333c85de..3406e16503 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/EventListener/VoteListenerTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/EventListener/VoteListenerTest.php @@ -26,15 +26,15 @@ class VoteListenerTest extends TestCase $traceableAccessDecisionManager = $this ->getMockBuilder(TraceableAccessDecisionManager::class) ->disableOriginalConstructor() - ->setMethods(array('addVoterVote')) + ->setMethods(['addVoterVote']) ->getMock(); $traceableAccessDecisionManager ->expects($this->once()) ->method('addVoterVote') - ->with($voter, array('myattr1', 'myattr2'), VoterInterface::ACCESS_GRANTED); + ->with($voter, ['myattr1', 'myattr2'], VoterInterface::ACCESS_GRANTED); $sut = new VoteListener($traceableAccessDecisionManager); - $sut->onVoterVote(new VoteEvent($voter, 'mysubject', array('myattr1', 'myattr2'), VoterInterface::ACCESS_GRANTED)); + $sut->onVoterVote(new VoteEvent($voter, 'mysubject', ['myattr1', 'myattr2'], VoterInterface::ACCESS_GRANTED)); } } diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/Functional/JsonLoginLdapTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/Functional/JsonLoginLdapTest.php index 09b22e2ffa..6b7dca4b42 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/Functional/JsonLoginLdapTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/Functional/JsonLoginLdapTest.php @@ -17,7 +17,7 @@ class JsonLoginLdapTest extends WebTestCase { public function testKernelBoot() { - $kernel = self::createKernel(array('test_case' => 'JsonLoginLdap', 'root_config' => 'config.yml')); + $kernel = self::createKernel(['test_case' => 'JsonLoginLdap', 'root_config' => 'config.yml']); $kernel->boot(); $this->assertInstanceOf(Kernel::class, $kernel); diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/Functional/app/JsonLoginLdap/bundles.php b/src/Symfony/Bundle/SecurityBundle/Tests/Functional/app/JsonLoginLdap/bundles.php index 336bd003a2..e3aef52a2e 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/Functional/app/JsonLoginLdap/bundles.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/Functional/app/JsonLoginLdap/bundles.php @@ -9,8 +9,8 @@ * file that was distributed with this source code. */ -return array( +return [ new Symfony\Bundle\SecurityBundle\SecurityBundle(), new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), -); +]; diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/Security/FirewallContextTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/Security/FirewallContextTest.php index ed8b655d76..b65b8af4e9 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/Security/FirewallContextTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/Security/FirewallContextTest.php @@ -46,7 +46,7 @@ class FirewallContextTest extends TestCase */ public function testFirewallConfigAs3rdConstructorArgument() { - new FirewallContext(array(), $this->getExceptionListenerMock(), new FirewallConfig('main', 'user_checker', 'request_matcher')); + new FirewallContext([], $this->getExceptionListenerMock(), new FirewallConfig('main', 'user_checker', 'request_matcher')); } private function getExceptionListenerMock() diff --git a/src/Symfony/Bundle/TwigBundle/DependencyInjection/Configuration.php b/src/Symfony/Bundle/TwigBundle/DependencyInjection/Configuration.php index 1ed2272e56..b635a752ab 100644 --- a/src/Symfony/Bundle/TwigBundle/DependencyInjection/Configuration.php +++ b/src/Symfony/Bundle/TwigBundle/DependencyInjection/Configuration.php @@ -54,11 +54,11 @@ class Configuration implements ConfigurationInterface ->arrayNode('form_themes') ->addDefaultChildrenIfNoneSet() ->prototype('scalar')->defaultValue('form_div_layout.html.twig')->end() - ->example(array('@My/form.html.twig')) + ->example(['@My/form.html.twig']) ->validate() ->ifTrue(function ($v) { return !\in_array('form_div_layout.html.twig', $v); }) ->then(function ($v) { - return array_merge(array('form_div_layout.html.twig'), $v); + return array_merge(['form_div_layout.html.twig'], $v); }) ->end() ->end() @@ -74,7 +74,7 @@ class Configuration implements ConfigurationInterface ->arrayNode('globals') ->normalizeKeys(false) ->useAttributeAsKey('key') - ->example(array('foo' => '"@bar"', 'pi' => 3.14)) + ->example(['foo' => '"@bar"', 'pi' => 3.14]) ->prototype('array') ->normalizeKeys(false) ->beforeNormalization() @@ -84,7 +84,7 @@ class Configuration implements ConfigurationInterface return substr($v, 1); } - return array('id' => substr($v, 1), 'type' => 'service'); + return ['id' => substr($v, 1), 'type' => 'service']; }) ->end() ->beforeNormalization() @@ -93,18 +93,18 @@ class Configuration implements ConfigurationInterface $keys = array_keys($v); sort($keys); - return $keys !== array('id', 'type') && $keys !== array('value'); + return $keys !== ['id', 'type'] && $keys !== ['value']; } return true; }) - ->then(function ($v) { return array('value' => $v); }) + ->then(function ($v) { return ['value' => $v]; }) ->end() ->children() ->scalarNode('id')->end() ->scalarNode('type') ->validate() - ->ifNotInArray(array('service')) + ->ifNotInArray(['service']) ->thenInvalid('The %s type is not supported') ->end() ->end() @@ -147,7 +147,7 @@ class Configuration implements ConfigurationInterface ->beforeNormalization() ->always() ->then(function ($paths) { - $normalized = array(); + $normalized = []; foreach ($paths as $path => $namespace) { if (\is_array($namespace)) { // xml diff --git a/src/Symfony/Bundle/TwigBundle/DependencyInjection/TwigExtension.php b/src/Symfony/Bundle/TwigBundle/DependencyInjection/TwigExtension.php index fbe05fd818..a9db7bf6a8 100644 --- a/src/Symfony/Bundle/TwigBundle/DependencyInjection/TwigExtension.php +++ b/src/Symfony/Bundle/TwigBundle/DependencyInjection/TwigExtension.php @@ -57,10 +57,10 @@ class TwigExtension extends Extension if (isset($config['globals'])) { foreach ($config['globals'] as $name => $value) { if (\is_array($value) && isset($value['key'])) { - $configs[$key]['globals'][$name] = array( + $configs[$key]['globals'][$name] = [ 'key' => $name, 'value' => $value, - ); + ]; } } } @@ -93,9 +93,9 @@ class TwigExtension extends Extension // register user-configured paths foreach ($config['paths'] as $path => $namespace) { if (!$namespace) { - $twigFilesystemLoaderDefinition->addMethodCall('addPath', array($path)); + $twigFilesystemLoaderDefinition->addMethodCall('addPath', [$path]); } else { - $twigFilesystemLoaderDefinition->addMethodCall('addPath', array($path, $namespace)); + $twigFilesystemLoaderDefinition->addMethodCall('addPath', [$path, $namespace]); } } @@ -106,12 +106,12 @@ class TwigExtension extends Extension foreach ($this->getBundleTemplatePaths($container, $config) as $name => $paths) { $namespace = $this->normalizeBundleName($name); foreach ($paths as $path) { - $twigFilesystemLoaderDefinition->addMethodCall('addPath', array($path, $namespace)); + $twigFilesystemLoaderDefinition->addMethodCall('addPath', [$path, $namespace]); } if ($paths) { // the last path must be the bundle views directory - $twigFilesystemLoaderDefinition->addMethodCall('addPath', array($path, '!'.$namespace)); + $twigFilesystemLoaderDefinition->addMethodCall('addPath', [$path, '!'.$namespace]); } } @@ -120,12 +120,12 @@ class TwigExtension extends Extension @trigger_error(sprintf('Templates directory "%s" is deprecated since Symfony 4.2, use "%s" instead.', $dir, $defaultTwigPath), E_USER_DEPRECATED); } - $twigFilesystemLoaderDefinition->addMethodCall('addPath', array($dir)); + $twigFilesystemLoaderDefinition->addMethodCall('addPath', [$dir]); } $container->addResource(new FileExistenceResource($dir)); if (file_exists($defaultTwigPath)) { - $twigFilesystemLoaderDefinition->addMethodCall('addPath', array($defaultTwigPath)); + $twigFilesystemLoaderDefinition->addMethodCall('addPath', [$defaultTwigPath]); } $container->addResource(new FileExistenceResource($defaultTwigPath)); @@ -133,9 +133,9 @@ class TwigExtension extends Extension $def = $container->getDefinition('twig'); foreach ($config['globals'] as $key => $global) { if (isset($global['type']) && 'service' === $global['type']) { - $def->addMethodCall('addGlobal', array($key, new Reference($global['id']))); + $def->addMethodCall('addGlobal', [$key, new Reference($global['id'])]); } else { - $def->addMethodCall('addGlobal', array($key, $global['value'])); + $def->addMethodCall('addGlobal', [$key, $global['value']]); } } } @@ -147,7 +147,7 @@ class TwigExtension extends Extension ); if (isset($config['autoescape_service']) && isset($config['autoescape_service_method'])) { - $config['autoescape'] = array(new Reference($config['autoescape_service']), $config['autoescape_service_method']); + $config['autoescape'] = [new Reference($config['autoescape_service']), $config['autoescape_service_method']]; } unset($config['autoescape_service'], $config['autoescape_service_method']); @@ -167,7 +167,7 @@ class TwigExtension extends Extension private function getBundleTemplatePaths(ContainerBuilder $container, array $config) { - $bundleHierarchy = array(); + $bundleHierarchy = []; foreach ($container->getParameter('kernel.bundles_metadata') as $name => $bundle) { $defaultOverrideBundlePath = $container->getParameterBag()->resolveValue($config['default_path']).'/bundles/'.$name; diff --git a/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/TwigExtensionTest.php b/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/TwigExtensionTest.php index 3666ef6d33..0a227930bd 100644 --- a/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/TwigExtensionTest.php +++ b/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/TwigExtensionTest.php @@ -29,9 +29,9 @@ class TwigExtensionTest extends TestCase { $container = $this->createContainer(); $container->registerExtension(new TwigExtension()); - $container->loadFromExtension('twig', array( + $container->loadFromExtension('twig', [ 'strict_variables' => false, // to be removed in 5.0 relying on default - )); + ]); $this->compileContainer($container); $this->assertEquals('Twig\Environment', $container->getDefinition('twig')->getClass(), '->load() loads the twig.xml file'); @@ -74,9 +74,9 @@ class TwigExtensionTest extends TestCase $this->assertEquals(3.14, $calls[4][1][1], '->load() registers variables as Twig globals'); // Yaml and Php specific configs - if (\in_array($format, array('yml', 'php'))) { + if (\in_array($format, ['yml', 'php'])) { $this->assertEquals('bad', $calls[5][1][0], '->load() registers variables as Twig globals'); - $this->assertEquals(array('key' => 'foo'), $calls[5][1][1], '->load() registers variables as Twig globals'); + $this->assertEquals(['key' => 'foo'], $calls[5][1][1], '->load() registers variables as Twig globals'); } // Twig options @@ -101,7 +101,7 @@ class TwigExtensionTest extends TestCase $this->compileContainer($container); $options = $container->getDefinition('twig')->getArgument(1); - $this->assertEquals(array(new Reference('my_project.some_bundle.template_escaping_guesser'), 'guess'), $options['autoescape']); + $this->assertEquals([new Reference('my_project.some_bundle.template_escaping_guesser'), 'guess'], $options['autoescape']); } /** @@ -140,8 +140,8 @@ class TwigExtensionTest extends TestCase public function testGlobalsWithDifferentTypesAndValues() { - $globals = array( - 'array' => array(), + $globals = [ + 'array' => [], 'false' => false, 'float' => 2.0, 'integer' => 3, @@ -149,14 +149,14 @@ class TwigExtensionTest extends TestCase 'object' => new \stdClass(), 'string' => 'foo', 'true' => true, - ); + ]; $container = $this->createContainer(); $container->registerExtension(new TwigExtension()); - $container->loadFromExtension('twig', array( + $container->loadFromExtension('twig', [ 'globals' => $globals, 'strict_variables' => false, // // to be removed in 5.0 relying on default - )); + ]); $this->compileContainer($container); $calls = $container->getDefinition('twig')->getMethodCalls(); @@ -180,24 +180,24 @@ class TwigExtensionTest extends TestCase $this->compileContainer($container); $def = $container->getDefinition('twig.loader.native_filesystem'); - $paths = array(); + $paths = []; foreach ($def->getMethodCalls() as $call) { if ('addPath' === $call[0] && false === strpos($call[1][0], 'Form')) { $paths[] = $call[1]; } } - $this->assertEquals(array( - array('path1'), - array('path2'), - array('namespaced_path1', 'namespace1'), - array('namespaced_path2', 'namespace2'), - array('namespaced_path3', 'namespace3'), - array(__DIR__.'/Fixtures/templates/bundles/TwigBundle', 'Twig'), - array(realpath(__DIR__.'/../..').'/Resources/views', 'Twig'), - array(realpath(__DIR__.'/../..').'/Resources/views', '!Twig'), - array(__DIR__.'/Fixtures/templates'), - ), $paths); + $this->assertEquals([ + ['path1'], + ['path2'], + ['namespaced_path1', 'namespace1'], + ['namespaced_path2', 'namespace2'], + ['namespaced_path3', 'namespace3'], + [__DIR__.'/Fixtures/templates/bundles/TwigBundle', 'Twig'], + [realpath(__DIR__.'/../..').'/Resources/views', 'Twig'], + [realpath(__DIR__.'/../..').'/Resources/views', '!Twig'], + [__DIR__.'/Fixtures/templates'], + ], $paths); } /** @@ -215,35 +215,35 @@ class TwigExtensionTest extends TestCase $this->compileContainer($container); $def = $container->getDefinition('twig.loader.native_filesystem'); - $paths = array(); + $paths = []; foreach ($def->getMethodCalls() as $call) { if ('addPath' === $call[0] && false === strpos($call[1][0], 'Form')) { $paths[] = $call[1]; } } - $this->assertEquals(array( - array('path1'), - array('path2'), - array('namespaced_path1', 'namespace1'), - array('namespaced_path2', 'namespace2'), - array('namespaced_path3', 'namespace3'), - array(__DIR__.'/../Fixtures/templates/Resources/TwigBundle/views', 'Twig'), - array(__DIR__.'/Fixtures/templates/bundles/TwigBundle', 'Twig'), - array(realpath(__DIR__.'/../..').'/Resources/views', 'Twig'), - array(realpath(__DIR__.'/../..').'/Resources/views', '!Twig'), - array(__DIR__.'/../Fixtures/templates/Resources/views'), - array(__DIR__.'/Fixtures/templates'), - ), $paths); + $this->assertEquals([ + ['path1'], + ['path2'], + ['namespaced_path1', 'namespace1'], + ['namespaced_path2', 'namespace2'], + ['namespaced_path3', 'namespace3'], + [__DIR__.'/../Fixtures/templates/Resources/TwigBundle/views', 'Twig'], + [__DIR__.'/Fixtures/templates/bundles/TwigBundle', 'Twig'], + [realpath(__DIR__.'/../..').'/Resources/views', 'Twig'], + [realpath(__DIR__.'/../..').'/Resources/views', '!Twig'], + [__DIR__.'/../Fixtures/templates/Resources/views'], + [__DIR__.'/Fixtures/templates'], + ], $paths); } public function getFormats() { - return array( - array('php'), - array('yml'), - array('xml'), - ); + return [ + ['php'], + ['yml'], + ['xml'], + ]; } /** @@ -257,9 +257,9 @@ class TwigExtensionTest extends TestCase $container->register('debug.stopwatch', 'Symfony\Component\Stopwatch\Stopwatch'); } $container->registerExtension(new TwigExtension()); - $container->loadFromExtension('twig', array( + $container->loadFromExtension('twig', [ 'strict_variables' => false, // to be removed in 5.0 relying on default - )); + ]); $container->setAlias('test.twig.extension.debug.stopwatch', 'twig.extension.debug.stopwatch')->setPublic(true); $this->compileContainer($container); @@ -272,21 +272,21 @@ class TwigExtensionTest extends TestCase public function stopwatchExtensionAvailabilityProvider() { - return array( - 'debug-and-stopwatch-enabled' => array(true, true, true), - 'only-stopwatch-enabled' => array(false, true, false), - 'only-debug-enabled' => array(true, false, false), - 'debug-and-stopwatch-disabled' => array(false, false, false), - ); + return [ + 'debug-and-stopwatch-enabled' => [true, true, true], + 'only-stopwatch-enabled' => [false, true, false], + 'only-debug-enabled' => [true, false, false], + 'debug-and-stopwatch-disabled' => [false, false, false], + ]; } public function testRuntimeLoader() { $container = $this->createContainer(); $container->registerExtension(new TwigExtension()); - $container->loadFromExtension('twig', array( + $container->loadFromExtension('twig', [ 'strict_variables' => false, // to be removed in 5.0 relying on default - )); + ]); $container->setParameter('kernel.environment', 'test'); $container->setParameter('debug.file_link_format', 'test'); $container->setParameter('foo', 'FooClass'); @@ -295,7 +295,7 @@ class TwigExtensionTest extends TestCase $container->register('templating.name_parser', 'FooClass'); $container->register('foo', '%foo%')->addTag('twig.runtime'); $container->addCompilerPass(new RuntimeLoaderPass(), PassConfig::TYPE_BEFORE_REMOVING); - $container->getCompilerPassConfig()->setRemovingPasses(array()); + $container->getCompilerPassConfig()->setRemovingPasses([]); $container->compile(); $loader = $container->getDefinition('twig.runtime_loader'); @@ -308,30 +308,30 @@ class TwigExtensionTest extends TestCase private function createContainer(string $rootDir = __DIR__.'/Fixtures') { - $container = new ContainerBuilder(new ParameterBag(array( + $container = new ContainerBuilder(new ParameterBag([ 'kernel.cache_dir' => __DIR__, 'kernel.root_dir' => $rootDir, 'kernel.project_dir' => __DIR__, 'kernel.charset' => 'UTF-8', 'kernel.debug' => false, - 'kernel.bundles' => array( + 'kernel.bundles' => [ 'TwigBundle' => 'Symfony\\Bundle\\TwigBundle\\TwigBundle', - ), - 'kernel.bundles_metadata' => array( - 'TwigBundle' => array( + ], + 'kernel.bundles_metadata' => [ + 'TwigBundle' => [ 'namespace' => 'Symfony\\Bundle\\TwigBundle', 'path' => realpath(__DIR__.'/../..'), - ), - ), - ))); + ], + ], + ])); return $container; } private function compileContainer(ContainerBuilder $container) { - $container->getCompilerPassConfig()->setOptimizationPasses(array()); - $container->getCompilerPassConfig()->setRemovingPasses(array()); + $container->getCompilerPassConfig()->setOptimizationPasses([]); + $container->getCompilerPassConfig()->setRemovingPasses([]); $container->compile(); } diff --git a/src/Symfony/Bundle/TwigBundle/Tests/Functional/NoTemplatingEntryTest.php b/src/Symfony/Bundle/TwigBundle/Tests/Functional/NoTemplatingEntryTest.php index 8c0495028a..f1e7709072 100644 --- a/src/Symfony/Bundle/TwigBundle/Tests/Functional/NoTemplatingEntryTest.php +++ b/src/Symfony/Bundle/TwigBundle/Tests/Functional/NoTemplatingEntryTest.php @@ -55,21 +55,21 @@ class NoTemplatingEntryKernel extends Kernel { public function registerBundles() { - return array(new FrameworkBundle(), new TwigBundle()); + return [new FrameworkBundle(), new TwigBundle()]; } public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load(function ($container) { $container - ->loadFromExtension('framework', array( + ->loadFromExtension('framework', [ 'secret' => '$ecret', - 'form' => array('enabled' => false), - )) - ->loadFromExtension('twig', array( + 'form' => ['enabled' => false], + ]) + ->loadFromExtension('twig', [ 'strict_variables' => false, // to be removed in 5.0 relying on default 'default_path' => __DIR__.'/templates', - )) + ]) ; }); } diff --git a/src/Symfony/Bundle/WebServerBundle/WebServer.php b/src/Symfony/Bundle/WebServerBundle/WebServer.php index 1195853b08..5ea058fa26 100644 --- a/src/Symfony/Bundle/WebServerBundle/WebServer.php +++ b/src/Symfony/Bundle/WebServerBundle/WebServer.php @@ -150,14 +150,14 @@ class WebServer throw new \RuntimeException('Unable to find the PHP binary.'); } - $xdebugArgs = ini_get('xdebug.profiler_enable_trigger') ? array('-dxdebug.profiler_enable_trigger=1') : array(); + $xdebugArgs = ini_get('xdebug.profiler_enable_trigger') ? ['-dxdebug.profiler_enable_trigger=1'] : []; - $process = new Process(array_merge(array($binary), $finder->findArguments(), $xdebugArgs, array('-dvariables_order=EGPCS', '-S', $config->getAddress(), $config->getRouter()))); + $process = new Process(array_merge([$binary], $finder->findArguments(), $xdebugArgs, ['-dvariables_order=EGPCS', '-S', $config->getAddress(), $config->getRouter()])); $process->setWorkingDirectory($config->getDocumentRoot()); $process->setTimeout(null); if (\in_array('APP_ENV', explode(',', getenv('SYMFONY_DOTENV_VARS')))) { - $process->setEnv(array('APP_ENV' => false)); + $process->setEnv(['APP_ENV' => false]); $process->inheritEnvironmentVariables(); } diff --git a/src/Symfony/Component/Asset/Tests/UrlPackageTest.php b/src/Symfony/Component/Asset/Tests/UrlPackageTest.php index ff6d5f49ec..097c1a891d 100644 --- a/src/Symfony/Component/Asset/Tests/UrlPackageTest.php +++ b/src/Symfony/Component/Asset/Tests/UrlPackageTest.php @@ -29,33 +29,33 @@ class UrlPackageTest extends TestCase public function getConfigs() { - return array( - array('http://example.net', '', 'http://example.com/foo', 'http://example.com/foo'), - array('http://example.net', '', 'https://example.com/foo', 'https://example.com/foo'), - array('http://example.net', '', '//example.com/foo', '//example.com/foo'), - array('file:///example/net', '', 'file:///example/com/foo', 'file:///example/com/foo'), - array('ftp://example.net', '', 'ftp://example.com', 'ftp://example.com'), + return [ + ['http://example.net', '', 'http://example.com/foo', 'http://example.com/foo'], + ['http://example.net', '', 'https://example.com/foo', 'https://example.com/foo'], + ['http://example.net', '', '//example.com/foo', '//example.com/foo'], + ['file:///example/net', '', 'file:///example/com/foo', 'file:///example/com/foo'], + ['ftp://example.net', '', 'ftp://example.com', 'ftp://example.com'], - array('http://example.com', '', '/foo', 'http://example.com/foo?v1'), - array('http://example.com', '', 'foo', 'http://example.com/foo?v1'), - array('http://example.com/', '', 'foo', 'http://example.com/foo?v1'), - array('http://example.com/foo', '', 'foo', 'http://example.com/foo/foo?v1'), - array('http://example.com/foo/', '', 'foo', 'http://example.com/foo/foo?v1'), - array('file:///example/com/foo/', '', 'foo', 'file:///example/com/foo/foo?v1'), + ['http://example.com', '', '/foo', 'http://example.com/foo?v1'], + ['http://example.com', '', 'foo', 'http://example.com/foo?v1'], + ['http://example.com/', '', 'foo', 'http://example.com/foo?v1'], + ['http://example.com/foo', '', 'foo', 'http://example.com/foo/foo?v1'], + ['http://example.com/foo/', '', 'foo', 'http://example.com/foo/foo?v1'], + ['file:///example/com/foo/', '', 'foo', 'file:///example/com/foo/foo?v1'], - array(array('http://example.com'), '', '/foo', 'http://example.com/foo?v1'), - array(array('http://example.com', 'http://example.net'), '', '/foo', 'http://example.com/foo?v1'), - array(array('http://example.com', 'http://example.net'), '', '/fooa', 'http://example.net/fooa?v1'), - array(array('file:///example/com', 'file:///example/net'), '', '/foo', 'file:///example/com/foo?v1'), - array(array('ftp://example.com', 'ftp://example.net'), '', '/fooa', 'ftp://example.net/fooa?v1'), + [['http://example.com'], '', '/foo', 'http://example.com/foo?v1'], + [['http://example.com', 'http://example.net'], '', '/foo', 'http://example.com/foo?v1'], + [['http://example.com', 'http://example.net'], '', '/fooa', 'http://example.net/fooa?v1'], + [['file:///example/com', 'file:///example/net'], '', '/foo', 'file:///example/com/foo?v1'], + [['ftp://example.com', 'ftp://example.net'], '', '/fooa', 'ftp://example.net/fooa?v1'], - array('http://example.com', 'version-%2$s/%1$s', '/foo', 'http://example.com/version-v1/foo'), - array('http://example.com', 'version-%2$s/%1$s', 'foo', 'http://example.com/version-v1/foo'), - array('http://example.com', 'version-%2$s/%1$s', 'foo/', 'http://example.com/version-v1/foo/'), - array('http://example.com', 'version-%2$s/%1$s', '/foo/', 'http://example.com/version-v1/foo/'), - array('file:///example/com', 'version-%2$s/%1$s', '/foo/', 'file:///example/com/version-v1/foo/'), - array('ftp://example.com', 'version-%2$s/%1$s', '/foo/', 'ftp://example.com/version-v1/foo/'), - ); + ['http://example.com', 'version-%2$s/%1$s', '/foo', 'http://example.com/version-v1/foo'], + ['http://example.com', 'version-%2$s/%1$s', 'foo', 'http://example.com/version-v1/foo'], + ['http://example.com', 'version-%2$s/%1$s', 'foo/', 'http://example.com/version-v1/foo/'], + ['http://example.com', 'version-%2$s/%1$s', '/foo/', 'http://example.com/version-v1/foo/'], + ['file:///example/com', 'version-%2$s/%1$s', '/foo/', 'file:///example/com/version-v1/foo/'], + ['ftp://example.com', 'version-%2$s/%1$s', '/foo/', 'ftp://example.com/version-v1/foo/'], + ]; } /** @@ -70,18 +70,18 @@ class UrlPackageTest extends TestCase public function getContextConfigs() { - return array( - array(false, 'http://example.com', '', 'foo', 'http://example.com/foo?v1'), - array(false, array('http://example.com'), '', 'foo', 'http://example.com/foo?v1'), - array(false, array('http://example.com', 'https://example.com'), '', 'foo', 'http://example.com/foo?v1'), - array(false, array('http://example.com', 'https://example.com'), '', 'fooa', 'https://example.com/fooa?v1'), - array(false, array('http://example.com/bar'), '', 'foo', 'http://example.com/bar/foo?v1'), - array(false, array('http://example.com/bar/'), '', 'foo', 'http://example.com/bar/foo?v1'), - array(false, array('//example.com/bar/'), '', 'foo', '//example.com/bar/foo?v1'), + return [ + [false, 'http://example.com', '', 'foo', 'http://example.com/foo?v1'], + [false, ['http://example.com'], '', 'foo', 'http://example.com/foo?v1'], + [false, ['http://example.com', 'https://example.com'], '', 'foo', 'http://example.com/foo?v1'], + [false, ['http://example.com', 'https://example.com'], '', 'fooa', 'https://example.com/fooa?v1'], + [false, ['http://example.com/bar'], '', 'foo', 'http://example.com/bar/foo?v1'], + [false, ['http://example.com/bar/'], '', 'foo', 'http://example.com/bar/foo?v1'], + [false, ['//example.com/bar/'], '', 'foo', '//example.com/bar/foo?v1'], - array(true, array('http://example.com'), '', 'foo', 'http://example.com/foo?v1'), - array(true, array('http://example.com', 'https://example.com'), '', 'foo', 'https://example.com/foo?v1'), - ); + [true, ['http://example.com'], '', 'foo', 'http://example.com/foo?v1'], + [true, ['http://example.com', 'https://example.com'], '', 'foo', 'https://example.com/foo?v1'], + ]; } public function testVersionStrategyGivesAbsoluteURL() @@ -100,7 +100,7 @@ class UrlPackageTest extends TestCase */ public function testNoBaseUrls() { - new UrlPackage(array(), new EmptyVersionStrategy()); + new UrlPackage([], new EmptyVersionStrategy()); } /** @@ -115,10 +115,10 @@ class UrlPackageTest extends TestCase public function getWrongBaseUrlConfig() { - return array( - array('not-a-url'), - array('not-a-url-with-query?query=://'), - ); + return [ + ['not-a-url'], + ['not-a-url-with-query?query=://'], + ]; } private function getContext($secure) diff --git a/src/Symfony/Component/BrowserKit/Client.php b/src/Symfony/Component/BrowserKit/Client.php index 7658967fab..c2a94af5ac 100644 --- a/src/Symfony/Component/BrowserKit/Client.php +++ b/src/Symfony/Component/BrowserKit/Client.php @@ -334,7 +334,7 @@ abstract class Client * @param string $method The HTTP method used to submit the form * @param array $serverParameters These values override the ones stored in $_SERVER (HTTP headers must include a HTTP_ prefix as PHP does) */ - public function submitForm(string $button, array $fieldValues = array(), string $method = 'POST', array $serverParameters = array()): Crawler + public function submitForm(string $button, array $fieldValues = [], string $method = 'POST', array $serverParameters = []): Crawler { if (null === $this->crawler) { throw new BadMethodCallException(sprintf('The "request()" method must be called before "%s()".', __METHOD__)); @@ -343,7 +343,7 @@ abstract class Client $buttonNode = $this->crawler->selectButton($button); $form = $buttonNode->form($fieldValues, $method); - return $this->submit($form, array(), $serverParameters); + return $this->submit($form, [], $serverParameters); } /** @@ -634,7 +634,7 @@ abstract class Client private function getMetaRefreshUrl(): ?string { $metaRefresh = $this->getCrawler()->filter('head meta[http-equiv="refresh"]'); - foreach ($metaRefresh->extract(array('content')) as $content) { + foreach ($metaRefresh->extract(['content']) as $content) { if (preg_match('/^\s*0\s*;\s*URL\s*=\s*(?|\'([^\']++)|"([^"]++)|([^\'"].*))/i', $content, $m)) { return str_replace("\t\r\n", '', rtrim($m[1])); } diff --git a/src/Symfony/Component/BrowserKit/Cookie.php b/src/Symfony/Component/BrowserKit/Cookie.php index 6efef3f1d8..ee786e69c2 100644 --- a/src/Symfony/Component/BrowserKit/Cookie.php +++ b/src/Symfony/Component/BrowserKit/Cookie.php @@ -22,7 +22,7 @@ class Cookie * Handles dates as defined by RFC 2616 section 3.3.1, and also some other * non-standard, but common formats. */ - private static $dateFormats = array( + private static $dateFormats = [ 'D, d M Y H:i:s T', 'D, d-M-y H:i:s T', 'D, d-M-Y H:i:s T', @@ -30,7 +30,7 @@ class Cookie 'D, d-m-Y H:i:s T', 'D M j G:i:s Y', 'D M d H:i:s Y T', - ); + ]; protected $name; protected $value; @@ -136,7 +136,7 @@ class Cookie list($name, $value) = explode('=', array_shift($parts), 2); - $values = array( + $values = [ 'name' => trim($name), 'value' => trim($value), 'expires' => null, @@ -146,7 +146,7 @@ class Cookie 'httponly' => false, 'passedRawValue' => true, 'samesite' => null, - ); + ]; if (null !== $url) { if ((false === $urlParts = parse_url($url)) || !isset($urlParts['host'])) { diff --git a/src/Symfony/Component/BrowserKit/Tests/ClientTest.php b/src/Symfony/Component/BrowserKit/Tests/ClientTest.php index 50d9ae35bd..4f6355012b 100644 --- a/src/Symfony/Component/BrowserKit/Tests/ClientTest.php +++ b/src/Symfony/Component/BrowserKit/Tests/ClientTest.php @@ -375,12 +375,12 @@ class ClientTest extends TestCase $client->setNextResponse(new Response('
')); $client->request('GET', 'http://www.example.com/foo/foobar'); - $client->submitForm('Register', array( + $client->submitForm('Register', [ 'username' => 'new username', 'password' => 'new password', - ), 'PUT', array( + ], 'PUT', [ 'HTTP_USER_AGENT' => 'Symfony User Agent', - )); + ]); $this->assertEquals('http://www.example.com/foo', $client->getRequest()->getUri(), '->submitForm() submit forms'); $this->assertEquals('PUT', $client->getRequest()->getMethod(), '->submitForm() allows to change the method'); @@ -396,10 +396,10 @@ class ClientTest extends TestCase $client->request('GET', 'http://www.example.com/foo/foobar'); try { - $client->submitForm('Register', array( + $client->submitForm('Register', [ 'username' => 'username', 'password' => 'password', - ), 'POST'); + ], 'POST'); $this->fail('->submitForm() throws a \InvalidArgumentException if the form could not be found'); } catch (\Exception $e) { $this->assertInstanceOf('InvalidArgumentException', $e, '->submitForm() throws a \InvalidArgumentException if the form could not be found'); @@ -670,23 +670,23 @@ class ClientTest extends TestCase public function getTestsForMetaRefresh() { - return array( - array('', 'http://www.example.com/redirected'), - array('', 'http://www.example.com/redirected'), - array('', 'http://www.example.com/redirected'), - array('', 'http://www.example.com/redirected'), - array('', 'http://www.example.com/redirected'), - array('', 'http://www.example.com/redirected'), - array('', 'http://www.example.com/redirected'), - array('', 'http://www.example.com/redirected'), + return [ + ['', 'http://www.example.com/redirected'], + ['', 'http://www.example.com/redirected'], + ['', 'http://www.example.com/redirected'], + ['', 'http://www.example.com/redirected'], + ['', 'http://www.example.com/redirected'], + ['', 'http://www.example.com/redirected'], + ['', 'http://www.example.com/redirected'], + ['', 'http://www.example.com/redirected'], // Non-zero timeout should not result in a redirect. - array('', 'http://www.example.com/foo/foobar'), - array('', 'http://www.example.com/foo/foobar'), + ['', 'http://www.example.com/foo/foobar'], + ['', 'http://www.example.com/foo/foobar'], // Invalid meta tag placement should not result in a redirect. - array('', 'http://www.example.com/foo/foobar'), + ['', 'http://www.example.com/foo/foobar'], // Valid meta refresh should not be followed if disabled. - array('', 'http://www.example.com/foo/foobar', false), - ); + ['', 'http://www.example.com/foo/foobar', false], + ]; } public function testBack() @@ -927,7 +927,7 @@ class ClassThatInheritClient extends Client return $response; } - public function submit(DomCrawlerForm $form, array $values = array()) + public function submit(DomCrawlerForm $form, array $values = []) { return parent::submit($form, $values); } diff --git a/src/Symfony/Component/Cache/Adapter/AbstractAdapter.php b/src/Symfony/Component/Cache/Adapter/AbstractAdapter.php index 571eb1468a..d93ae711bd 100644 --- a/src/Symfony/Component/Cache/Adapter/AbstractAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/AbstractAdapter.php @@ -64,12 +64,12 @@ abstract class AbstractAdapter implements AdapterInterface, CacheInterface, Logg null, CacheItem::class ); - $getId = \Closure::fromCallable(array($this, 'getId')); + $getId = \Closure::fromCallable([$this, 'getId']); $this->mergeByLifetime = \Closure::bind( function ($deferred, $namespace, &$expiredIds) use ($getId) { - $byLifetime = array(); + $byLifetime = []; $now = microtime(true); - $expiredIds = array(); + $expiredIds = []; foreach ($deferred as $key => $item) { $key = (string) $key; @@ -83,7 +83,7 @@ abstract class AbstractAdapter implements AdapterInterface, CacheInterface, Logg unset($metadata[CacheItem::METADATA_TAGS]); } // For compactness, expiry and creation duration are packed in the key of an array, using magic numbers as separators - $byLifetime[$ttl][$getId($key)] = $metadata ? array("\x9D".pack('VN', (int) $metadata[CacheItem::METADATA_EXPIRY] - CacheItem::METADATA_EXPIRY_OFFSET, $metadata[CacheItem::METADATA_CTIME])."\x5F" => $item->value) : $item->value; + $byLifetime[$ttl][$getId($key)] = $metadata ? ["\x9D".pack('VN', (int) $metadata[CacheItem::METADATA_EXPIRY] - CacheItem::METADATA_EXPIRY_OFFSET, $metadata[CacheItem::METADATA_CTIME])."\x5F" => $item->value] : $item->value; } return $byLifetime; @@ -131,7 +131,7 @@ abstract class AbstractAdapter implements AdapterInterface, CacheInterface, Logg return $apcu; } - public static function createConnection($dsn, array $options = array()) + public static function createConnection($dsn, array $options = []) { if (!\is_string($dsn)) { throw new InvalidArgumentException(sprintf('The %s() method expect argument #1 to be string, %s given.', __METHOD__, \gettype($dsn))); @@ -161,11 +161,11 @@ abstract class AbstractAdapter implements AdapterInterface, CacheInterface, Logg $value = null; try { - foreach ($this->doFetch(array($id)) as $value) { + foreach ($this->doFetch([$id]) as $value) { $isHit = true; } } catch (\Exception $e) { - CacheItem::log($this->logger, 'Failed to fetch key "{key}"', array('key' => $key, 'exception' => $e)); + CacheItem::log($this->logger, 'Failed to fetch key "{key}"', ['key' => $key, 'exception' => $e]); } return $f($key, $value, $isHit); @@ -174,12 +174,12 @@ abstract class AbstractAdapter implements AdapterInterface, CacheInterface, Logg /** * {@inheritdoc} */ - public function getItems(array $keys = array()) + public function getItems(array $keys = []) { if ($this->deferred) { $this->commit(); } - $ids = array(); + $ids = []; foreach ($keys as $key) { $ids[] = $this->getId($key); @@ -187,8 +187,8 @@ abstract class AbstractAdapter implements AdapterInterface, CacheInterface, Logg try { $items = $this->doFetch($ids); } catch (\Exception $e) { - CacheItem::log($this->logger, 'Failed to fetch requested items', array('keys' => $keys, 'exception' => $e)); - $items = array(); + CacheItem::log($this->logger, 'Failed to fetch requested items', ['keys' => $keys, 'exception' => $e]); + $items = []; } $ids = array_combine($ids, $keys); @@ -229,7 +229,7 @@ abstract class AbstractAdapter implements AdapterInterface, CacheInterface, Logg $ok = true; $byLifetime = $this->mergeByLifetime; $byLifetime = $byLifetime($this->deferred, $this->namespace, $expiredIds); - $retry = $this->deferred = array(); + $retry = $this->deferred = []; if ($expiredIds) { $this->doDelete($expiredIds); @@ -239,7 +239,7 @@ abstract class AbstractAdapter implements AdapterInterface, CacheInterface, Logg $e = $this->doSave($values, $lifetime); } catch (\Exception $e) { } - if (true === $e || array() === $e) { + if (true === $e || [] === $e) { continue; } if (\is_array($e) || 1 === \count($values)) { @@ -247,7 +247,7 @@ abstract class AbstractAdapter implements AdapterInterface, CacheInterface, Logg $ok = false; $v = $values[$id]; $type = \is_object($v) ? \get_class($v) : \gettype($v); - CacheItem::log($this->logger, 'Failed to save key "{key}" ({type})', array('key' => substr($id, \strlen($this->namespace)), 'type' => $type, 'exception' => $e instanceof \Exception ? $e : null)); + CacheItem::log($this->logger, 'Failed to save key "{key}" ({type})', ['key' => substr($id, \strlen($this->namespace)), 'type' => $type, 'exception' => $e instanceof \Exception ? $e : null]); } } else { foreach ($values as $id => $v) { @@ -261,15 +261,15 @@ abstract class AbstractAdapter implements AdapterInterface, CacheInterface, Logg foreach ($ids as $id) { try { $v = $byLifetime[$lifetime][$id]; - $e = $this->doSave(array($id => $v), $lifetime); + $e = $this->doSave([$id => $v], $lifetime); } catch (\Exception $e) { } - if (true === $e || array() === $e) { + if (true === $e || [] === $e) { continue; } $ok = false; $type = \is_object($v) ? \get_class($v) : \gettype($v); - CacheItem::log($this->logger, 'Failed to save key "{key}" ({type})', array('key' => substr($id, \strlen($this->namespace)), 'type' => $type, 'exception' => $e instanceof \Exception ? $e : null)); + CacheItem::log($this->logger, 'Failed to save key "{key}" ({type})', ['key' => substr($id, \strlen($this->namespace)), 'type' => $type, 'exception' => $e instanceof \Exception ? $e : null]); } } @@ -297,7 +297,7 @@ abstract class AbstractAdapter implements AdapterInterface, CacheInterface, Logg yield $key => $f($key, $value, true); } } catch (\Exception $e) { - CacheItem::log($this->logger, 'Failed to fetch requested items', array('keys' => array_values($keys), 'exception' => $e)); + CacheItem::log($this->logger, 'Failed to fetch requested items', ['keys' => array_values($keys), 'exception' => $e]); } foreach ($keys as $key) { diff --git a/src/Symfony/Component/Cache/Adapter/ArrayAdapter.php b/src/Symfony/Component/Cache/Adapter/ArrayAdapter.php index 97b6b7f780..bbb1f846e4 100644 --- a/src/Symfony/Component/Cache/Adapter/ArrayAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/ArrayAdapter.php @@ -83,7 +83,7 @@ class ArrayAdapter implements AdapterInterface, CacheInterface, LoggerAwareInter /** * {@inheritdoc} */ - public function getItems(array $keys = array()) + public function getItems(array $keys = []) { foreach ($keys as $key) { if (!\is_string($key) || !isset($this->expiries[$key])) { diff --git a/src/Symfony/Component/Cache/Adapter/ChainAdapter.php b/src/Symfony/Component/Cache/Adapter/ChainAdapter.php index 0417a22cd1..80aa7c6d1b 100644 --- a/src/Symfony/Component/Cache/Adapter/ChainAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/ChainAdapter.php @@ -33,7 +33,7 @@ class ChainAdapter implements AdapterInterface, CacheInterface, PruneableInterfa { use ContractsTrait; - private $adapters = array(); + private $adapters = []; private $adapterCount; private $syncItem; @@ -118,7 +118,7 @@ class ChainAdapter implements AdapterInterface, CacheInterface, PruneableInterfa public function getItem($key) { $syncItem = $this->syncItem; - $misses = array(); + $misses = []; foreach ($this->adapters as $i => $adapter) { $item = $adapter->getItem($key); @@ -140,15 +140,15 @@ class ChainAdapter implements AdapterInterface, CacheInterface, PruneableInterfa /** * {@inheritdoc} */ - public function getItems(array $keys = array()) + public function getItems(array $keys = []) { return $this->generateItems($this->adapters[0]->getItems($keys), 0); } private function generateItems($items, $adapterIndex) { - $missing = array(); - $misses = array(); + $missing = []; + $misses = []; $nextAdapterIndex = $adapterIndex + 1; $nextAdapter = isset($this->adapters[$nextAdapterIndex]) ? $this->adapters[$nextAdapterIndex] : null; diff --git a/src/Symfony/Component/Cache/Adapter/PdoAdapter.php b/src/Symfony/Component/Cache/Adapter/PdoAdapter.php index eb35fb38a9..c2a18cdd4b 100644 --- a/src/Symfony/Component/Cache/Adapter/PdoAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/PdoAdapter.php @@ -47,7 +47,7 @@ class PdoAdapter extends AbstractAdapter implements PruneableInterface * @throws InvalidArgumentException When PDO error mode is not PDO::ERRMODE_EXCEPTION * @throws InvalidArgumentException When namespace contains invalid characters */ - public function __construct($connOrDsn, string $namespace = '', int $defaultLifetime = 0, array $options = array(), MarshallerInterface $marshaller = null) + public function __construct($connOrDsn, string $namespace = '', int $defaultLifetime = 0, array $options = [], MarshallerInterface $marshaller = null) { $this->init($connOrDsn, $namespace, $defaultLifetime, $options, $marshaller); } diff --git a/src/Symfony/Component/Cache/Adapter/ProxyAdapter.php b/src/Symfony/Component/Cache/Adapter/ProxyAdapter.php index 1f0c00ffe8..f7536b1ee2 100644 --- a/src/Symfony/Component/Cache/Adapter/ProxyAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/ProxyAdapter.php @@ -78,7 +78,7 @@ class ProxyAdapter implements AdapterInterface, CacheInterface, PruneableInterfa } if ($metadata) { // For compactness, expiry and creation duration are packed in the key of an array, using magic numbers as separators - $item["\0*\0value"] = array("\x9D".pack('VN', (int) $metadata[CacheItem::METADATA_EXPIRY] - CacheItem::METADATA_EXPIRY_OFFSET, $metadata[CacheItem::METADATA_CTIME])."\x5F" => $item["\0*\0value"]); + $item["\0*\0value"] = ["\x9D".pack('VN', (int) $metadata[CacheItem::METADATA_EXPIRY] - CacheItem::METADATA_EXPIRY_OFFSET, $metadata[CacheItem::METADATA_CTIME])."\x5F" => $item["\0*\0value"]]; } $innerItem->set($item["\0*\0value"]); $innerItem->expiresAt(null !== $item["\0*\0expiry"] ? \DateTime::createFromFormat('U.u', sprintf('%.6f', $item["\0*\0expiry"])) : null); diff --git a/src/Symfony/Component/Cache/Adapter/TagAwareAdapter.php b/src/Symfony/Component/Cache/Adapter/TagAwareAdapter.php index 41b9257b52..e54044b60a 100644 --- a/src/Symfony/Component/Cache/Adapter/TagAwareAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/TagAwareAdapter.php @@ -84,7 +84,7 @@ class TagAwareAdapter implements TagAwareAdapterInterface, TagAwareCacheInterfac function ($deferred) { $tagsByKey = []; foreach ($deferred as $key => $item) { - $tagsByKey[$key] = $item->newMetadata[CacheItem::METADATA_TAGS] ?? array(); + $tagsByKey[$key] = $item->newMetadata[CacheItem::METADATA_TAGS] ?? []; } return $tagsByKey; diff --git a/src/Symfony/Component/Cache/CacheItem.php b/src/Symfony/Component/Cache/CacheItem.php index e0500756a4..92eb9c39df 100644 --- a/src/Symfony/Component/Cache/CacheItem.php +++ b/src/Symfony/Component/Cache/CacheItem.php @@ -28,8 +28,8 @@ final class CacheItem implements ItemInterface protected $isHit = false; protected $expiry; protected $defaultLifetime; - protected $metadata = array(); - protected $newMetadata = array(); + protected $metadata = []; + protected $newMetadata = []; protected $innerItem; protected $poolHash; protected $isTaggable = false; @@ -111,7 +111,7 @@ final class CacheItem implements ItemInterface throw new LogicException(sprintf('Cache item "%s" comes from a non tag-aware pool: you cannot tag it.', $this->key)); } if (!\is_iterable($tags)) { - $tags = array($tags); + $tags = [$tags]; } foreach ($tags as $tag) { if (!\is_string($tag)) { @@ -151,7 +151,7 @@ final class CacheItem implements ItemInterface { @trigger_error(sprintf('The "%s()" method is deprecated since Symfony 4.2, use the "getMetadata()" method instead.', __METHOD__), E_USER_DEPRECATED); - return $this->metadata[self::METADATA_TAGS] ?? array(); + return $this->metadata[self::METADATA_TAGS] ?? []; } /** @@ -183,12 +183,12 @@ final class CacheItem implements ItemInterface * * @internal */ - public static function log(LoggerInterface $logger = null, $message, $context = array()) + public static function log(LoggerInterface $logger = null, $message, $context = []) { if ($logger) { $logger->warning($message, $context); } else { - $replace = array(); + $replace = []; foreach ($context as $k => $v) { if (is_scalar($v)) { $replace['{'.$k.'}'] = $v; diff --git a/src/Symfony/Component/Cache/DependencyInjection/CacheCollectorPass.php b/src/Symfony/Component/Cache/DependencyInjection/CacheCollectorPass.php index f93f97b88e..6193d34798 100644 --- a/src/Symfony/Component/Cache/DependencyInjection/CacheCollectorPass.php +++ b/src/Symfony/Component/Cache/DependencyInjection/CacheCollectorPass.php @@ -56,16 +56,16 @@ class CacheCollectorPass implements CompilerPassInterface $recorder = new Definition(is_subclass_of($definition->getClass(), TagAwareAdapterInterface::class) ? TraceableTagAwareAdapter::class : TraceableAdapter::class); $recorder->setTags($definition->getTags()); $recorder->setPublic($definition->isPublic()); - $recorder->setArguments(array(new Reference($innerId = $id.$this->cachePoolRecorderInnerSuffix))); + $recorder->setArguments([new Reference($innerId = $id.$this->cachePoolRecorderInnerSuffix)]); - $definition->setTags(array()); + $definition->setTags([]); $definition->setPublic(false); $container->setDefinition($innerId, $definition); $container->setDefinition($id, $recorder); // Tell the collector to add the new instance - $collectorDefinition->addMethodCall('addInstance', array($id, new Reference($id))); + $collectorDefinition->addMethodCall('addInstance', [$id, new Reference($id)]); $collectorDefinition->setPublic(false); } } diff --git a/src/Symfony/Component/Cache/DependencyInjection/CachePoolClearerPass.php b/src/Symfony/Component/Cache/DependencyInjection/CachePoolClearerPass.php index be315b636d..3ca89a36a5 100644 --- a/src/Symfony/Component/Cache/DependencyInjection/CachePoolClearerPass.php +++ b/src/Symfony/Component/Cache/DependencyInjection/CachePoolClearerPass.php @@ -36,7 +36,7 @@ class CachePoolClearerPass implements CompilerPassInterface foreach ($container->findTaggedServiceIds($this->cachePoolClearerTag) as $id => $attr) { $clearer = $container->getDefinition($id); - $pools = array(); + $pools = []; foreach ($clearer->getArgument(0) as $name => $ref) { if ($container->hasDefinition($ref)) { $pools[$name] = new Reference($ref); diff --git a/src/Symfony/Component/Cache/DependencyInjection/CachePoolPass.php b/src/Symfony/Component/Cache/DependencyInjection/CachePoolPass.php index 92e2017e6f..b1af39755e 100644 --- a/src/Symfony/Component/Cache/DependencyInjection/CachePoolPass.php +++ b/src/Symfony/Component/Cache/DependencyInjection/CachePoolPass.php @@ -54,15 +54,15 @@ class CachePoolPass implements CompilerPassInterface } $seed .= '.'.$container->getParameter('kernel.container_class'); - $pools = array(); - $clearers = array(); - $attributes = array( + $pools = []; + $clearers = []; + $attributes = [ 'provider', 'name', 'namespace', 'default_lifetime', 'reset', - ); + ]; foreach ($container->findTaggedServiceIds($this->cachePoolTag) as $id => $tags) { $adapter = $pool = $container->getDefinition($id); if ($pool->isAbstract()) { @@ -97,7 +97,7 @@ class CachePoolPass implements CompilerPassInterface // no-op } elseif ('reset' === $attr) { if ($tags[0][$attr]) { - $pool->addTag($this->kernelResetTag, array('method' => $tags[0][$attr])); + $pool->addTag($this->kernelResetTag, ['method' => $tags[0][$attr]]); } } elseif ('namespace' !== $attr || ArrayAdapter::class !== $adapter->getClass()) { $pool->replaceArgument($i++, $tags[0][$attr]); @@ -156,8 +156,8 @@ class CachePoolPass implements CompilerPassInterface if (!$container->hasDefinition($name = '.cache_connection.'.ContainerBuilder::hash($dsn))) { $definition = new Definition(AbstractAdapter::class); $definition->setPublic(false); - $definition->setFactory(array(AbstractAdapter::class, 'createConnection')); - $definition->setArguments(array($dsn, array('lazy' => true))); + $definition->setFactory([AbstractAdapter::class, 'createConnection']); + $definition->setArguments([$dsn, ['lazy' => true]]); $container->setDefinition($name, $definition); } } diff --git a/src/Symfony/Component/Cache/DependencyInjection/CachePoolPrunerPass.php b/src/Symfony/Component/Cache/DependencyInjection/CachePoolPrunerPass.php index 21266a871e..e5699623e5 100644 --- a/src/Symfony/Component/Cache/DependencyInjection/CachePoolPrunerPass.php +++ b/src/Symfony/Component/Cache/DependencyInjection/CachePoolPrunerPass.php @@ -41,7 +41,7 @@ class CachePoolPrunerPass implements CompilerPassInterface return; } - $services = array(); + $services = []; foreach ($container->findTaggedServiceIds($this->cachePoolTag) as $id => $tags) { $class = $container->getParameterBag()->resolveValue($container->getDefinition($id)->getClass()); diff --git a/src/Symfony/Component/Cache/LockRegistry.php b/src/Symfony/Component/Cache/LockRegistry.php index 0aadf33d61..e0318e900c 100644 --- a/src/Symfony/Component/Cache/LockRegistry.php +++ b/src/Symfony/Component/Cache/LockRegistry.php @@ -25,13 +25,13 @@ use Symfony\Contracts\Cache\ItemInterface; */ class LockRegistry { - private static $openedFiles = array(); - private static $lockedFiles = array(); + private static $openedFiles = []; + private static $lockedFiles = []; /** * The number of items in this list controls the max number of concurrent processes. */ - private static $files = array( + private static $files = [ __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'AbstractAdapter.php', __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'AdapterInterface.php', __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'ApcuAdapter.php', @@ -51,7 +51,7 @@ class LockRegistry __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'TagAwareAdapterInterface.php', __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'TraceableAdapter.php', __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'TraceableTagAwareAdapter.php', - ); + ]; /** * Defines a set of existing files that will be used as keys to acquire locks. @@ -69,7 +69,7 @@ class LockRegistry fclose($file); } } - self::$openedFiles = self::$lockedFiles = array(); + self::$openedFiles = self::$lockedFiles = []; return $previousFiles; } diff --git a/src/Symfony/Component/Cache/Marshaller/DefaultMarshaller.php b/src/Symfony/Component/Cache/Marshaller/DefaultMarshaller.php index 16c02bb08f..9c1ef46015 100644 --- a/src/Symfony/Component/Cache/Marshaller/DefaultMarshaller.php +++ b/src/Symfony/Component/Cache/Marshaller/DefaultMarshaller.php @@ -37,7 +37,7 @@ class DefaultMarshaller implements MarshallerInterface */ public function marshall(array $values, ?array &$failed): array { - $serialized = $failed = array(); + $serialized = $failed = []; foreach ($values as $id => $value) { try { diff --git a/src/Symfony/Component/Cache/Simple/ArrayCache.php b/src/Symfony/Component/Cache/Simple/ArrayCache.php index 6785943787..e36dacb829 100644 --- a/src/Symfony/Component/Cache/Simple/ArrayCache.php +++ b/src/Symfony/Component/Cache/Simple/ArrayCache.php @@ -104,7 +104,7 @@ class ArrayCache implements CacheInterface, LoggerAwareInterface, ResettableInte CacheItem::validateKey($key); } - return $this->setMultiple(array($key => $value), $ttl); + return $this->setMultiple([$key => $value], $ttl); } /** @@ -115,7 +115,7 @@ class ArrayCache implements CacheInterface, LoggerAwareInterface, ResettableInte if (!\is_array($values) && !$values instanceof \Traversable) { throw new InvalidArgumentException(sprintf('Cache values must be array or Traversable, "%s" given', \is_object($values) ? \get_class($values) : \gettype($values))); } - $valuesArray = array(); + $valuesArray = []; foreach ($values as $key => $value) { if (!\is_int($key) && !(\is_string($key) && isset($this->expiries[$key]))) { diff --git a/src/Symfony/Component/Cache/Simple/PdoCache.php b/src/Symfony/Component/Cache/Simple/PdoCache.php index 076370c97e..985753fe7b 100644 --- a/src/Symfony/Component/Cache/Simple/PdoCache.php +++ b/src/Symfony/Component/Cache/Simple/PdoCache.php @@ -45,7 +45,7 @@ class PdoCache extends AbstractCache implements PruneableInterface * @throws InvalidArgumentException When PDO error mode is not PDO::ERRMODE_EXCEPTION * @throws InvalidArgumentException When namespace contains invalid characters */ - public function __construct($connOrDsn, string $namespace = '', int $defaultLifetime = 0, array $options = array(), MarshallerInterface $marshaller = null) + public function __construct($connOrDsn, string $namespace = '', int $defaultLifetime = 0, array $options = [], MarshallerInterface $marshaller = null) { $this->init($connOrDsn, $namespace, $defaultLifetime, $options, $marshaller); } diff --git a/src/Symfony/Component/Cache/Simple/Psr6Cache.php b/src/Symfony/Component/Cache/Simple/Psr6Cache.php index 4b373a03d0..29c039f2c1 100644 --- a/src/Symfony/Component/Cache/Simple/Psr6Cache.php +++ b/src/Symfony/Component/Cache/Simple/Psr6Cache.php @@ -170,7 +170,7 @@ class Psr6Cache implements CacheInterface, PruneableInterface, ResettableInterfa unset($metadata[CacheItem::METADATA_TAGS]); if ($metadata) { - $values[$key] = array("\x9D".pack('VN', (int) $metadata[CacheItem::METADATA_EXPIRY] - self::METADATA_EXPIRY_OFFSET, $metadata[CacheItem::METADATA_CTIME])."\x5F" => $values[$key]); + $values[$key] = ["\x9D".pack('VN', (int) $metadata[CacheItem::METADATA_EXPIRY] - self::METADATA_EXPIRY_OFFSET, $metadata[CacheItem::METADATA_CTIME])."\x5F" => $values[$key]]; } } diff --git a/src/Symfony/Component/Cache/Tests/Adapter/AdapterTestCase.php b/src/Symfony/Component/Cache/Tests/Adapter/AdapterTestCase.php index 1e5d9382c7..8a7d147808 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/AdapterTestCase.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/AdapterTestCase.php @@ -77,10 +77,10 @@ abstract class AdapterTestCase extends CachePoolTest $item = $cache->getItem('foo'); - $expected = array( + $expected = [ CacheItem::METADATA_EXPIRY => 9.5 + time(), CacheItem::METADATA_CTIME => 1000, - ); + ]; $this->assertEquals($expected, $item->getMetadata(), 'Item metadata should embed expiry and ctime.', .6); } diff --git a/src/Symfony/Component/Cache/Tests/Adapter/ArrayAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/ArrayAdapterTest.php index 7b65061cd1..5c72dc6e0b 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/ArrayAdapterTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/ArrayAdapterTest.php @@ -18,11 +18,11 @@ use Symfony\Component\Cache\Adapter\ArrayAdapter; */ class ArrayAdapterTest extends AdapterTestCase { - protected $skippedTests = array( + protected $skippedTests = [ 'testGetMetadata' => 'ArrayAdapter does not keep metadata.', 'testDeferredSaveWithoutCommit' => 'Assumes a shared cache which ArrayAdapter is not.', 'testSaveWithoutExpire' => 'Assumes a shared cache which ArrayAdapter is not.', - ); + ]; public function createCachePool($defaultLifetime = 0) { diff --git a/src/Symfony/Component/Cache/Tests/Adapter/ChainAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/ChainAdapterTest.php index 09ba6e444c..61b039b57b 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/ChainAdapterTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/ChainAdapterTest.php @@ -27,10 +27,10 @@ class ChainAdapterTest extends AdapterTestCase public function createCachePool($defaultLifetime = 0, $testMethod = null) { if ('testGetMetadata' === $testMethod) { - return new ChainAdapter(array(new FilesystemAdapter('', $defaultLifetime)), $defaultLifetime); + return new ChainAdapter([new FilesystemAdapter('', $defaultLifetime)], $defaultLifetime); } - return new ChainAdapter(array(new ArrayAdapter($defaultLifetime), new ExternalAdapter(), new FilesystemAdapter('', $defaultLifetime)), $defaultLifetime); + return new ChainAdapter([new ArrayAdapter($defaultLifetime), new ExternalAdapter(), new FilesystemAdapter('', $defaultLifetime)], $defaultLifetime); } /** @@ -39,7 +39,7 @@ class ChainAdapterTest extends AdapterTestCase */ public function testEmptyAdaptersException() { - new ChainAdapter(array()); + new ChainAdapter([]); } /** @@ -48,7 +48,7 @@ class ChainAdapterTest extends AdapterTestCase */ public function testInvalidAdapterException() { - new ChainAdapter(array(new \stdClass())); + new ChainAdapter([new \stdClass()]); } public function testPrune() @@ -57,18 +57,18 @@ class ChainAdapterTest extends AdapterTestCase $this->markTestSkipped($this->skippedTests[__FUNCTION__]); } - $cache = new ChainAdapter(array( + $cache = new ChainAdapter([ $this->getPruneableMock(), $this->getNonPruneableMock(), $this->getPruneableMock(), - )); + ]); $this->assertTrue($cache->prune()); - $cache = new ChainAdapter(array( + $cache = new ChainAdapter([ $this->getPruneableMock(), $this->getFailingPruneableMock(), $this->getPruneableMock(), - )); + ]); $this->assertFalse($cache->prune()); } diff --git a/src/Symfony/Component/Cache/Tests/Adapter/MaxIdLengthAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/MaxIdLengthAdapterTest.php index 7613afa7f9..fec985e6da 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/MaxIdLengthAdapterTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/MaxIdLengthAdapterTest.php @@ -19,15 +19,15 @@ class MaxIdLengthAdapterTest extends TestCase public function testLongKey() { $cache = $this->getMockBuilder(MaxIdLengthAdapter::class) - ->setConstructorArgs(array(str_repeat('-', 10))) - ->setMethods(array('doHave', 'doFetch', 'doDelete', 'doSave', 'doClear')) + ->setConstructorArgs([str_repeat('-', 10)]) + ->setMethods(['doHave', 'doFetch', 'doDelete', 'doSave', 'doClear']) ->getMock(); $cache->expects($this->exactly(2)) ->method('doHave') ->withConsecutive( - array($this->equalTo('----------:nWfzGiCgLczv3SSUzXL3kg:')), - array($this->equalTo('----------:---------------------------------------')) + [$this->equalTo('----------:nWfzGiCgLczv3SSUzXL3kg:')], + [$this->equalTo('----------:---------------------------------------')] ); $cache->hasItem(str_repeat('-', 40)); @@ -37,7 +37,7 @@ class MaxIdLengthAdapterTest extends TestCase public function testLongKeyVersioning() { $cache = $this->getMockBuilder(MaxIdLengthAdapter::class) - ->setConstructorArgs(array(str_repeat('-', 26))) + ->setConstructorArgs([str_repeat('-', 26)]) ->getMock(); $reflectionClass = new \ReflectionClass(AbstractAdapter::class); @@ -46,20 +46,20 @@ class MaxIdLengthAdapterTest extends TestCase $reflectionMethod->setAccessible(true); // No versioning enabled - $this->assertEquals('--------------------------:------------', $reflectionMethod->invokeArgs($cache, array(str_repeat('-', 12)))); - $this->assertLessThanOrEqual(50, \strlen($reflectionMethod->invokeArgs($cache, array(str_repeat('-', 12))))); - $this->assertLessThanOrEqual(50, \strlen($reflectionMethod->invokeArgs($cache, array(str_repeat('-', 23))))); - $this->assertLessThanOrEqual(50, \strlen($reflectionMethod->invokeArgs($cache, array(str_repeat('-', 40))))); + $this->assertEquals('--------------------------:------------', $reflectionMethod->invokeArgs($cache, [str_repeat('-', 12)])); + $this->assertLessThanOrEqual(50, \strlen($reflectionMethod->invokeArgs($cache, [str_repeat('-', 12)]))); + $this->assertLessThanOrEqual(50, \strlen($reflectionMethod->invokeArgs($cache, [str_repeat('-', 23)]))); + $this->assertLessThanOrEqual(50, \strlen($reflectionMethod->invokeArgs($cache, [str_repeat('-', 40)]))); $reflectionProperty = $reflectionClass->getProperty('versioningIsEnabled'); $reflectionProperty->setAccessible(true); $reflectionProperty->setValue($cache, true); // Versioning enabled - $this->assertEquals('--------------------------:1/------------', $reflectionMethod->invokeArgs($cache, array(str_repeat('-', 12)))); - $this->assertLessThanOrEqual(50, \strlen($reflectionMethod->invokeArgs($cache, array(str_repeat('-', 12))))); - $this->assertLessThanOrEqual(50, \strlen($reflectionMethod->invokeArgs($cache, array(str_repeat('-', 23))))); - $this->assertLessThanOrEqual(50, \strlen($reflectionMethod->invokeArgs($cache, array(str_repeat('-', 40))))); + $this->assertEquals('--------------------------:1/------------', $reflectionMethod->invokeArgs($cache, [str_repeat('-', 12)])); + $this->assertLessThanOrEqual(50, \strlen($reflectionMethod->invokeArgs($cache, [str_repeat('-', 12)]))); + $this->assertLessThanOrEqual(50, \strlen($reflectionMethod->invokeArgs($cache, [str_repeat('-', 23)]))); + $this->assertLessThanOrEqual(50, \strlen($reflectionMethod->invokeArgs($cache, [str_repeat('-', 40)]))); } /** @@ -69,7 +69,7 @@ class MaxIdLengthAdapterTest extends TestCase public function testTooLongNamespace() { $cache = $this->getMockBuilder(MaxIdLengthAdapter::class) - ->setConstructorArgs(array(str_repeat('-', 40))) + ->setConstructorArgs([str_repeat('-', 40)]) ->getMock(); } } diff --git a/src/Symfony/Component/Cache/Tests/Adapter/MemcachedAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/MemcachedAdapterTest.php index 161a5739f3..59f33f3aee 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/MemcachedAdapterTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/MemcachedAdapterTest.php @@ -203,40 +203,40 @@ class MemcachedAdapterTest extends AdapterTestCase $dsn = 'memcached:?host[localhost]&host[localhost:12345]&host[/some/memcached.sock:]=3'; $client = MemcachedAdapter::createConnection($dsn); - $expected = array( - 0 => array( + $expected = [ + 0 => [ 'host' => 'localhost', 'port' => 11211, 'type' => 'TCP', - ), - 1 => array( + ], + 1 => [ 'host' => 'localhost', 'port' => 12345, 'type' => 'TCP', - ), - 2 => array( + ], + 2 => [ 'host' => '/some/memcached.sock', 'port' => 0, 'type' => 'SOCKET', - ), - ); + ], + ]; $this->assertSame($expected, $client->getServerList()); $dsn = 'memcached://localhost?host[foo.bar]=3'; $client = MemcachedAdapter::createConnection($dsn); - $expected = array( - 0 => array( + $expected = [ + 0 => [ 'host' => 'localhost', 'port' => 11211, 'type' => 'TCP', - ), - 1 => array( + ], + 1 => [ 'host' => 'foo.bar', 'port' => 11211, 'type' => 'TCP', - ), - ); + ], + ]; $this->assertSame($expected, $client->getServerList()); } } diff --git a/src/Symfony/Component/Cache/Tests/Adapter/PdoDbalAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/PdoDbalAdapterTest.php index eea89b7458..1c9fd5140c 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/PdoDbalAdapterTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/PdoDbalAdapterTest.php @@ -32,7 +32,7 @@ class PdoDbalAdapterTest extends AdapterTestCase self::$dbFile = tempnam(sys_get_temp_dir(), 'sf_sqlite_cache'); - $pool = new PdoAdapter(DriverManager::getConnection(array('driver' => 'pdo_sqlite', 'path' => self::$dbFile))); + $pool = new PdoAdapter(DriverManager::getConnection(['driver' => 'pdo_sqlite', 'path' => self::$dbFile])); } public static function tearDownAfterClass() @@ -42,6 +42,6 @@ class PdoDbalAdapterTest extends AdapterTestCase public function createCachePool($defaultLifetime = 0) { - return new PdoAdapter(DriverManager::getConnection(array('driver' => 'pdo_sqlite', 'path' => self::$dbFile)), '', $defaultLifetime); + return new PdoAdapter(DriverManager::getConnection(['driver' => 'pdo_sqlite', 'path' => self::$dbFile]), '', $defaultLifetime); } } diff --git a/src/Symfony/Component/Cache/Tests/Adapter/PhpArrayAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/PhpArrayAdapterTest.php index 1a6898de58..cee80ac196 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/PhpArrayAdapterTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/PhpArrayAdapterTest.php @@ -21,7 +21,7 @@ use Symfony\Component\Cache\Adapter\PhpArrayAdapter; */ class PhpArrayAdapterTest extends AdapterTestCase { - protected $skippedTests = array( + protected $skippedTests = [ 'testGet' => 'PhpArrayAdapter is read-only.', 'testBasicUsage' => 'PhpArrayAdapter is read-only.', 'testBasicUsageWithLongKey' => 'PhpArrayAdapter is read-only.', @@ -53,7 +53,7 @@ class PhpArrayAdapterTest extends AdapterTestCase 'testDefaultLifeTime' => 'PhpArrayAdapter does not allow configuring a default lifetime.', 'testPrune' => 'PhpArrayAdapter just proxies', - ); + ]; protected static $file; @@ -80,22 +80,22 @@ class PhpArrayAdapterTest extends AdapterTestCase public function testStore() { - $arrayWithRefs = array(); + $arrayWithRefs = []; $arrayWithRefs[0] = 123; $arrayWithRefs[1] = &$arrayWithRefs[0]; - $object = (object) array( + $object = (object) [ 'foo' => 'bar', 'foo2' => 'bar2', - ); + ]; - $expected = array( + $expected = [ 'null' => null, 'serializedString' => serialize($object), 'arrayWithRefs' => $arrayWithRefs, 'object' => $object, - 'arrayWithObject' => array('bar' => $object), - ); + 'arrayWithObject' => ['bar' => $object], + ]; $adapter = $this->createCachePool(); $adapter->warmUp($expected); @@ -107,29 +107,29 @@ class PhpArrayAdapterTest extends AdapterTestCase public function testStoredFile() { - $data = array( + $data = [ 'integer' => 42, 'float' => 42.42, 'boolean' => true, - 'array_simple' => array('foo', 'bar'), - 'array_associative' => array('foo' => 'bar', 'foo2' => 'bar2'), - ); - $expected = array( - array( + 'array_simple' => ['foo', 'bar'], + 'array_associative' => ['foo' => 'bar', 'foo2' => 'bar2'], + ]; + $expected = [ + [ 'integer' => 0, 'float' => 1, 'boolean' => 2, 'array_simple' => 3, 'array_associative' => 4, - ), - array( + ], + [ 0 => 42, 1 => 42.42, 2 => true, - 3 => array('foo', 'bar'), - 4 => array('foo' => 'bar', 'foo2' => 'bar2'), - ), - ); + 3 => ['foo', 'bar'], + 4 => ['foo' => 'bar', 'foo2' => 'bar2'], + ], + ]; $adapter = $this->createCachePool(); $adapter->warmUp($data); @@ -142,7 +142,7 @@ class PhpArrayAdapterTest extends AdapterTestCase class PhpArrayAdapterWrapper extends PhpArrayAdapter { - protected $data = array(); + protected $data = []; public function save(CacheItemInterface $item) { diff --git a/src/Symfony/Component/Cache/Tests/Adapter/PredisAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/PredisAdapterTest.php index c65515b54d..abe0a21094 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/PredisAdapterTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/PredisAdapterTest.php @@ -19,20 +19,20 @@ class PredisAdapterTest extends AbstractRedisAdapterTest public static function setupBeforeClass() { parent::setupBeforeClass(); - self::$redis = new \Predis\Client(array('host' => getenv('REDIS_HOST'))); + self::$redis = new \Predis\Client(['host' => getenv('REDIS_HOST')]); } public function testCreateConnection() { $redisHost = getenv('REDIS_HOST'); - $redis = RedisAdapter::createConnection('redis://'.$redisHost.'/1', array('class' => \Predis\Client::class, 'timeout' => 3)); + $redis = RedisAdapter::createConnection('redis://'.$redisHost.'/1', ['class' => \Predis\Client::class, 'timeout' => 3]); $this->assertInstanceOf(\Predis\Client::class, $redis); $connection = $redis->getConnection(); $this->assertInstanceOf(StreamConnection::class, $connection); - $params = array( + $params = [ 'scheme' => 'tcp', 'host' => 'localhost', 'port' => 6379, @@ -41,7 +41,7 @@ class PredisAdapterTest extends AbstractRedisAdapterTest 'read_write_timeout' => 0, 'tcp_nodelay' => true, 'database' => '1', - ); + ]; $this->assertSame($params, $connection->getParameters()->toArray()); } } diff --git a/src/Symfony/Component/Cache/Tests/Adapter/PredisRedisClusterAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/PredisRedisClusterAdapterTest.php index 9974e93635..c819c348d9 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/PredisRedisClusterAdapterTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/PredisRedisClusterAdapterTest.php @@ -21,7 +21,7 @@ class PredisRedisClusterAdapterTest extends AbstractRedisAdapterTest self::markTestSkipped('REDIS_CLUSTER_HOSTS env var is not defined.'); } - self::$redis = RedisAdapter::createConnection('redis:?host['.str_replace(' ', ']&host[', $hosts).']', array('class' => \Predis\Client::class, 'redis_cluster' => true)); + self::$redis = RedisAdapter::createConnection('redis:?host['.str_replace(' ', ']&host[', $hosts).']', ['class' => \Predis\Client::class, 'redis_cluster' => true]); } public static function tearDownAfterClass() diff --git a/src/Symfony/Component/Cache/Tests/Adapter/RedisAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/RedisAdapterTest.php index 340304cb50..c83abaf91b 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/RedisAdapterTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/RedisAdapterTest.php @@ -35,7 +35,7 @@ class RedisAdapterTest extends AbstractRedisAdapterTest { $redis = RedisAdapter::createConnection('redis:?host[h1]&host[h2]&host[/foo:]'); $this->assertInstanceOf(\RedisArray::class, $redis); - $this->assertSame(array('h1:6379', 'h2:6379', '/foo'), $redis->_hosts()); + $this->assertSame(['h1:6379', 'h2:6379', '/foo'], $redis->_hosts()); @$redis = null; // some versions of phpredis connect on destruct, let's silence the warning $redisHost = getenv('REDIS_HOST'); diff --git a/src/Symfony/Component/Cache/Tests/Adapter/RedisClusterAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/RedisClusterAdapterTest.php index 344f1d0743..75dd2790cc 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/RedisClusterAdapterTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/RedisClusterAdapterTest.php @@ -26,7 +26,7 @@ class RedisClusterAdapterTest extends AbstractRedisAdapterTest self::markTestSkipped('REDIS_CLUSTER_HOSTS env var is not defined.'); } - self::$redis = AbstractAdapter::createConnection('redis:?host['.str_replace(' ', ']&host[', $hosts).']', array('lazy' => true, 'redis_cluster' => true)); + self::$redis = AbstractAdapter::createConnection('redis:?host['.str_replace(' ', ']&host[', $hosts).']', ['lazy' => true, 'redis_cluster' => true]); } public function createCachePool($defaultLifetime = 0) @@ -49,10 +49,10 @@ class RedisClusterAdapterTest extends AbstractRedisAdapterTest public function provideFailedCreateConnection() { - return array( - array('redis://localhost:1234?redis_cluster=1'), - array('redis://foo@localhost?redis_cluster=1'), - array('redis://localhost/123?redis_cluster=1'), - ); + return [ + ['redis://localhost:1234?redis_cluster=1'], + ['redis://foo@localhost?redis_cluster=1'], + ['redis://localhost/123?redis_cluster=1'], + ]; } } diff --git a/src/Symfony/Component/Cache/Tests/Adapter/TagAwareAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/TagAwareAdapterTest.php index b56cf6e04b..7b8895b700 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/TagAwareAdapterTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/TagAwareAdapterTest.php @@ -161,7 +161,7 @@ class TagAwareAdapterTest extends AdapterTestCase $pool->save($i->tag('foo')); $i = $pool->getItem('k'); - $this->assertSame(array('foo' => 'foo'), $i->getMetadata()[CacheItem::METADATA_TAGS]); + $this->assertSame(['foo' => 'foo'], $i->getMetadata()[CacheItem::METADATA_TAGS]); } public function testPrune() diff --git a/src/Symfony/Component/Cache/Tests/CacheItemTest.php b/src/Symfony/Component/Cache/Tests/CacheItemTest.php index 395c003bd3..0e3f4b9a73 100644 --- a/src/Symfony/Component/Cache/Tests/CacheItemTest.php +++ b/src/Symfony/Component/Cache/Tests/CacheItemTest.php @@ -33,23 +33,23 @@ class CacheItemTest extends TestCase public function provideInvalidKey() { - return array( - array(''), - array('{'), - array('}'), - array('('), - array(')'), - array('/'), - array('\\'), - array('@'), - array(':'), - array(true), - array(null), - array(1), - array(1.1), - array(array(array())), - array(new \Exception('foo')), - ); + return [ + [''], + ['{'], + ['}'], + ['('], + [')'], + ['/'], + ['\\'], + ['@'], + [':'], + [true], + [null], + [1], + [1.1], + [[[]]], + [new \Exception('foo')], + ]; } public function testTag() @@ -60,10 +60,10 @@ class CacheItemTest extends TestCase $r->setValue($item, true); $this->assertSame($item, $item->tag('foo')); - $this->assertSame($item, $item->tag(array('bar', 'baz'))); + $this->assertSame($item, $item->tag(['bar', 'baz'])); (\Closure::bind(function () use ($item) { - $this->assertSame(array('foo' => 'foo', 'bar' => 'bar', 'baz' => 'baz'), $item->newMetadata[CacheItem::METADATA_TAGS]); + $this->assertSame(['foo' => 'foo', 'bar' => 'bar', 'baz' => 'baz'], $item->newMetadata[CacheItem::METADATA_TAGS]); }, $this, CacheItem::class))(); } @@ -93,6 +93,6 @@ class CacheItemTest extends TestCase $r->setAccessible(true); $r->setValue($item, 'foo'); - $item->tag(array()); + $item->tag([]); } } diff --git a/src/Symfony/Component/Cache/Tests/DependencyInjection/CacheCollectorPassTest.php b/src/Symfony/Component/Cache/Tests/DependencyInjection/CacheCollectorPassTest.php index 421f5764de..7e77491de8 100644 --- a/src/Symfony/Component/Cache/Tests/DependencyInjection/CacheCollectorPassTest.php +++ b/src/Symfony/Component/Cache/Tests/DependencyInjection/CacheCollectorPassTest.php @@ -37,10 +37,10 @@ class CacheCollectorPassTest extends TestCase $collector = $container->register('data_collector.cache', CacheDataCollector::class); (new CacheCollectorPass())->process($container); - $this->assertEquals(array( - array('addInstance', array('fs', new Reference('fs'))), - array('addInstance', array('tagged_fs', new Reference('tagged_fs'))), - ), $collector->getMethodCalls()); + $this->assertEquals([ + ['addInstance', ['fs', new Reference('fs')]], + ['addInstance', ['tagged_fs', new Reference('tagged_fs')]], + ], $collector->getMethodCalls()); $this->assertSame(TraceableAdapter::class, $container->findDefinition('fs')->getClass()); $this->assertSame(TraceableTagAwareAdapter::class, $container->getDefinition('tagged_fs')->getClass()); diff --git a/src/Symfony/Component/Cache/Tests/DependencyInjection/CachePoolClearerPassTest.php b/src/Symfony/Component/Cache/Tests/DependencyInjection/CachePoolClearerPassTest.php index 6aa68c29cd..533aa14aff 100644 --- a/src/Symfony/Component/Cache/Tests/DependencyInjection/CachePoolClearerPassTest.php +++ b/src/Symfony/Component/Cache/Tests/DependencyInjection/CachePoolClearerPassTest.php @@ -34,18 +34,18 @@ class CachePoolClearerPassTest extends TestCase $publicPool = new Definition(); $publicPool->addArgument('namespace'); - $publicPool->addTag('cache.pool', array('clearer' => 'clearer_alias')); + $publicPool->addTag('cache.pool', ['clearer' => 'clearer_alias']); $container->setDefinition('public.pool', $publicPool); $publicPool = new Definition(); $publicPool->addArgument('namespace'); - $publicPool->addTag('cache.pool', array('clearer' => 'clearer_alias', 'name' => 'pool2')); + $publicPool->addTag('cache.pool', ['clearer' => 'clearer_alias', 'name' => 'pool2']); $container->setDefinition('public.pool2', $publicPool); $privatePool = new Definition(); $privatePool->setPublic(false); $privatePool->addArgument('namespace'); - $privatePool->addTag('cache.pool', array('clearer' => 'clearer_alias')); + $privatePool->addTag('cache.pool', ['clearer' => 'clearer_alias']); $container->setDefinition('private.pool', $privatePool); $clearer = new Definition(); @@ -55,18 +55,18 @@ class CachePoolClearerPassTest extends TestCase $pass = new RemoveUnusedDefinitionsPass(); foreach ($container->getCompiler()->getPassConfig()->getRemovingPasses() as $removingPass) { if ($removingPass instanceof RepeatedPass) { - $pass->setRepeatedPass(new RepeatedPass(array($pass))); + $pass->setRepeatedPass(new RepeatedPass([$pass])); break; } } - foreach (array(new CachePoolPass(), $pass, new CachePoolClearerPass()) as $pass) { + foreach ([new CachePoolPass(), $pass, new CachePoolClearerPass()] as $pass) { $pass->process($container); } - $expected = array(array( + $expected = [[ 'public.pool' => new Reference('public.pool'), 'pool2' => new Reference('public.pool2'), - )); + ]]; $this->assertEquals($expected, $clearer->getArguments()); $this->assertEquals($expected, $globalClearer->getArguments()); } diff --git a/src/Symfony/Component/Cache/Tests/DependencyInjection/CachePoolPassTest.php b/src/Symfony/Component/Cache/Tests/DependencyInjection/CachePoolPassTest.php index f757e79821..f307aa5386 100644 --- a/src/Symfony/Component/Cache/Tests/DependencyInjection/CachePoolPassTest.php +++ b/src/Symfony/Component/Cache/Tests/DependencyInjection/CachePoolPassTest.php @@ -71,10 +71,10 @@ class CachePoolPassTest extends TestCase $container->setParameter('kernel.container_class', 'app'); $container->setParameter('cache.prefix.seed', 'foo'); $cachePool = new Definition(); - $cachePool->addTag('cache.pool', array( + $cachePool->addTag('cache.pool', [ 'provider' => 'foobar', 'default_lifetime' => 3, - )); + ]); $cachePool->addArgument(null); $cachePool->addArgument(null); $cachePool->addArgument(null); @@ -94,10 +94,10 @@ class CachePoolPassTest extends TestCase $container->setParameter('kernel.container_class', 'app'); $container->setParameter('cache.prefix.seed', 'foo'); $cachePool = new Definition(); - $cachePool->addTag('cache.pool', array( + $cachePool->addTag('cache.pool', [ 'name' => 'foobar', 'provider' => 'foobar', - )); + ]); $cachePool->addArgument(null); $cachePool->addArgument(null); $cachePool->addArgument(null); @@ -122,7 +122,7 @@ class CachePoolPassTest extends TestCase $adapter->addTag('cache.pool'); $container->setDefinition('app.cache_adapter', $adapter); $cachePool = new ChildDefinition('app.cache_adapter'); - $cachePool->addTag('cache.pool', array('foobar' => 123)); + $cachePool->addTag('cache.pool', ['foobar' => 123]); $container->setDefinition('app.cache_pool', $cachePool); $this->cachePoolPass->process($container); diff --git a/src/Symfony/Component/Cache/Tests/DependencyInjection/CachePoolPrunerPassTest.php b/src/Symfony/Component/Cache/Tests/DependencyInjection/CachePoolPrunerPassTest.php index e4de6f6807..128ee243c6 100644 --- a/src/Symfony/Component/Cache/Tests/DependencyInjection/CachePoolPrunerPassTest.php +++ b/src/Symfony/Component/Cache/Tests/DependencyInjection/CachePoolPrunerPassTest.php @@ -24,17 +24,17 @@ class CachePoolPrunerPassTest extends TestCase public function testCompilerPassReplacesCommandArgument() { $container = new ContainerBuilder(); - $container->register('console.command.cache_pool_prune')->addArgument(array()); + $container->register('console.command.cache_pool_prune')->addArgument([]); $container->register('pool.foo', FilesystemAdapter::class)->addTag('cache.pool'); $container->register('pool.bar', PhpFilesAdapter::class)->addTag('cache.pool'); $pass = new CachePoolPrunerPass(); $pass->process($container); - $expected = array( + $expected = [ 'pool.foo' => new Reference('pool.foo'), 'pool.bar' => new Reference('pool.bar'), - ); + ]; $argument = $container->getDefinition('console.command.cache_pool_prune')->getArgument(0); $this->assertInstanceOf(IteratorArgument::class, $argument); @@ -63,7 +63,7 @@ class CachePoolPrunerPassTest extends TestCase public function testCompilerPassThrowsOnInvalidDefinitionClass() { $container = new ContainerBuilder(); - $container->register('console.command.cache_pool_prune')->addArgument(array()); + $container->register('console.command.cache_pool_prune')->addArgument([]); $container->register('pool.not-found', NotFound::class)->addTag('cache.pool'); $pass = new CachePoolPrunerPass(); diff --git a/src/Symfony/Component/Cache/Tests/Fixtures/ArrayCache.php b/src/Symfony/Component/Cache/Tests/Fixtures/ArrayCache.php index 27fb82de01..95b39d54bd 100644 --- a/src/Symfony/Component/Cache/Tests/Fixtures/ArrayCache.php +++ b/src/Symfony/Component/Cache/Tests/Fixtures/ArrayCache.php @@ -6,7 +6,7 @@ use Doctrine\Common\Cache\CacheProvider; class ArrayCache extends CacheProvider { - private $data = array(); + private $data = []; protected function doFetch($id) { @@ -26,7 +26,7 @@ class ArrayCache extends CacheProvider protected function doSave($id, $data, $lifeTime = 0) { - $this->data[$id] = array($data, $lifeTime ? microtime(true) + $lifeTime : false); + $this->data[$id] = [$data, $lifeTime ? microtime(true) + $lifeTime : false]; return true; } @@ -40,7 +40,7 @@ class ArrayCache extends CacheProvider protected function doFlush() { - $this->data = array(); + $this->data = []; return true; } diff --git a/src/Symfony/Component/Cache/Tests/LockRegistryTest.php b/src/Symfony/Component/Cache/Tests/LockRegistryTest.php index 3f7d959570..0771347ed6 100644 --- a/src/Symfony/Component/Cache/Tests/LockRegistryTest.php +++ b/src/Symfony/Component/Cache/Tests/LockRegistryTest.php @@ -18,7 +18,7 @@ class LockRegistryTest extends TestCase { public function testFiles() { - $lockFiles = LockRegistry::setFiles(array()); + $lockFiles = LockRegistry::setFiles([]); LockRegistry::setFiles($lockFiles); $expected = array_map('realpath', glob(__DIR__.'/../Adapter/*')); $this->assertSame($expected, $lockFiles); diff --git a/src/Symfony/Component/Cache/Tests/Marshaller/DefaultMarshallerTest.php b/src/Symfony/Component/Cache/Tests/Marshaller/DefaultMarshallerTest.php index fc625d12fc..daa1fd19f4 100644 --- a/src/Symfony/Component/Cache/Tests/Marshaller/DefaultMarshallerTest.php +++ b/src/Symfony/Component/Cache/Tests/Marshaller/DefaultMarshallerTest.php @@ -19,14 +19,14 @@ class DefaultMarshallerTest extends TestCase public function testSerialize() { $marshaller = new DefaultMarshaller(); - $values = array( + $values = [ 'a' => 123, 'b' => function () {}, - ); + ]; - $expected = array('a' => \extension_loaded('igbinary') ? igbinary_serialize(123) : serialize(123)); + $expected = ['a' => \extension_loaded('igbinary') ? igbinary_serialize(123) : serialize(123)]; $this->assertSame($expected, $marshaller->marshall($values, $failed)); - $this->assertSame(array('b'), $failed); + $this->assertSame(['b'], $failed); } public function testNativeUnserialize() diff --git a/src/Symfony/Component/Cache/Tests/Simple/PhpArrayCacheTest.php b/src/Symfony/Component/Cache/Tests/Simple/PhpArrayCacheTest.php index 724744cb9a..ba4bde3139 100644 --- a/src/Symfony/Component/Cache/Tests/Simple/PhpArrayCacheTest.php +++ b/src/Symfony/Component/Cache/Tests/Simple/PhpArrayCacheTest.php @@ -20,7 +20,7 @@ use Symfony\Component\Cache\Tests\Adapter\FilesystemAdapterTest; */ class PhpArrayCacheTest extends CacheTestCase { - protected $skippedTests = array( + protected $skippedTests = [ 'testBasicUsageWithLongKey' => 'PhpArrayCache does no writes', 'testDelete' => 'PhpArrayCache does no writes', @@ -45,7 +45,7 @@ class PhpArrayCacheTest extends CacheTestCase 'testDefaultLifeTime' => 'PhpArrayCache does not allow configuring a default lifetime.', 'testPrune' => 'PhpArrayCache just proxies', - ); + ]; protected static $file; @@ -68,22 +68,22 @@ class PhpArrayCacheTest extends CacheTestCase public function testStore() { - $arrayWithRefs = array(); + $arrayWithRefs = []; $arrayWithRefs[0] = 123; $arrayWithRefs[1] = &$arrayWithRefs[0]; - $object = (object) array( + $object = (object) [ 'foo' => 'bar', 'foo2' => 'bar2', - ); + ]; - $expected = array( + $expected = [ 'null' => null, 'serializedString' => serialize($object), 'arrayWithRefs' => $arrayWithRefs, 'object' => $object, - 'arrayWithObject' => array('bar' => $object), - ); + 'arrayWithObject' => ['bar' => $object], + ]; $cache = new PhpArrayCache(self::$file, new NullCache()); $cache->warmUp($expected); @@ -95,29 +95,29 @@ class PhpArrayCacheTest extends CacheTestCase public function testStoredFile() { - $data = array( + $data = [ 'integer' => 42, 'float' => 42.42, 'boolean' => true, - 'array_simple' => array('foo', 'bar'), - 'array_associative' => array('foo' => 'bar', 'foo2' => 'bar2'), - ); - $expected = array( - array( + 'array_simple' => ['foo', 'bar'], + 'array_associative' => ['foo' => 'bar', 'foo2' => 'bar2'], + ]; + $expected = [ + [ 'integer' => 0, 'float' => 1, 'boolean' => 2, 'array_simple' => 3, 'array_associative' => 4, - ), - array( + ], + [ 0 => 42, 1 => 42.42, 2 => true, - 3 => array('foo', 'bar'), - 4 => array('foo' => 'bar', 'foo2' => 'bar2'), - ), - ); + 3 => ['foo', 'bar'], + 4 => ['foo' => 'bar', 'foo2' => 'bar2'], + ], + ]; $cache = new PhpArrayCache(self::$file, new NullCache()); $cache->warmUp($data); @@ -130,7 +130,7 @@ class PhpArrayCacheTest extends CacheTestCase class PhpArrayCacheWrapper extends PhpArrayCache { - protected $data = array(); + protected $data = []; public function set($key, $value, $ttl = null) { diff --git a/src/Symfony/Component/Cache/Traits/AbstractTrait.php b/src/Symfony/Component/Cache/Traits/AbstractTrait.php index 01351f11c9..2553ea75cb 100644 --- a/src/Symfony/Component/Cache/Traits/AbstractTrait.php +++ b/src/Symfony/Component/Cache/Traits/AbstractTrait.php @@ -26,8 +26,8 @@ trait AbstractTrait private $namespace; private $namespaceVersion = ''; private $versioningIsEnabled = false; - private $deferred = array(); - private $ids = array(); + private $deferred = []; + private $ids = []; /** * @var int|null The maximum length to enforce for identifiers or null when no limit applies @@ -94,7 +94,7 @@ trait AbstractTrait try { return $this->doHave($id); } catch (\Exception $e) { - CacheItem::log($this->logger, 'Failed to check if key "{key}" is cached', array('key' => $key, 'exception' => $e)); + CacheItem::log($this->logger, 'Failed to check if key "{key}" is cached', ['key' => $key, 'exception' => $e]); return false; } @@ -105,24 +105,24 @@ trait AbstractTrait */ public function clear() { - $this->deferred = array(); + $this->deferred = []; if ($cleared = $this->versioningIsEnabled) { $namespaceVersion = substr_replace(base64_encode(pack('V', mt_rand())), ':', 5); try { - $cleared = $this->doSave(array('/'.$this->namespace => $namespaceVersion), 0); + $cleared = $this->doSave(['/'.$this->namespace => $namespaceVersion], 0); } catch (\Exception $e) { $cleared = false; } - if ($cleared = true === $cleared || array() === $cleared) { + if ($cleared = true === $cleared || [] === $cleared) { $this->namespaceVersion = $namespaceVersion; - $this->ids = array(); + $this->ids = []; } } try { return $this->doClear($this->namespace) || $cleared; } catch (\Exception $e) { - CacheItem::log($this->logger, 'Failed to clear the cache', array('exception' => $e)); + CacheItem::log($this->logger, 'Failed to clear the cache', ['exception' => $e]); return false; } @@ -133,7 +133,7 @@ trait AbstractTrait */ public function deleteItem($key) { - return $this->deleteItems(array($key)); + return $this->deleteItems([$key]); } /** @@ -141,7 +141,7 @@ trait AbstractTrait */ public function deleteItems(array $keys) { - $ids = array(); + $ids = []; foreach ($keys as $key) { $ids[$key] = $this->getId($key); @@ -161,12 +161,12 @@ trait AbstractTrait foreach ($ids as $key => $id) { try { $e = null; - if ($this->doDelete(array($id))) { + if ($this->doDelete([$id])) { continue; } } catch (\Exception $e) { } - CacheItem::log($this->logger, 'Failed to delete key "{key}"', array('key' => $key, 'exception' => $e)); + CacheItem::log($this->logger, 'Failed to delete key "{key}"', ['key' => $key, 'exception' => $e]); $ok = false; } @@ -190,7 +190,7 @@ trait AbstractTrait $wasEnabled = $this->versioningIsEnabled; $this->versioningIsEnabled = (bool) $enable; $this->namespaceVersion = ''; - $this->ids = array(); + $this->ids = []; return $wasEnabled; } @@ -204,7 +204,7 @@ trait AbstractTrait $this->commit(); } $this->namespaceVersion = ''; - $this->ids = array(); + $this->ids = []; } /** @@ -241,15 +241,15 @@ trait AbstractTrait private function getId($key) { if ($this->versioningIsEnabled && '' === $this->namespaceVersion) { - $this->ids = array(); + $this->ids = []; $this->namespaceVersion = '1/'; try { - foreach ($this->doFetch(array('/'.$this->namespace)) as $v) { + foreach ($this->doFetch(['/'.$this->namespace]) as $v) { $this->namespaceVersion = $v; } if ('1:' === $this->namespaceVersion) { $this->namespaceVersion = substr_replace(base64_encode(pack('V', time())), ':', 5); - $this->doSave(array('@'.$this->namespace => $this->namespaceVersion), 0); + $this->doSave(['@'.$this->namespace => $this->namespaceVersion], 0); } } catch (\Exception $e) { } diff --git a/src/Symfony/Component/Cache/Traits/ApcuTrait.php b/src/Symfony/Component/Cache/Traits/ApcuTrait.php index a93fc812a1..c86b043ae1 100644 --- a/src/Symfony/Component/Cache/Traits/ApcuTrait.php +++ b/src/Symfony/Component/Cache/Traits/ApcuTrait.php @@ -53,8 +53,8 @@ trait ApcuTrait { $unserializeCallbackHandler = ini_set('unserialize_callback_func', __CLASS__.'::handleUnserializeCallback'); try { - $values = array(); - foreach (apcu_fetch($ids, $ok) ?: array() as $k => $v) { + $values = []; + foreach (apcu_fetch($ids, $ok) ?: [] as $k => $v) { if (null !== $v || $ok) { $values[$k] = $v; } diff --git a/src/Symfony/Component/Cache/Traits/ArrayTrait.php b/src/Symfony/Component/Cache/Traits/ArrayTrait.php index 8268e40db4..e585c3d48c 100644 --- a/src/Symfony/Component/Cache/Traits/ArrayTrait.php +++ b/src/Symfony/Component/Cache/Traits/ArrayTrait.php @@ -24,8 +24,8 @@ trait ArrayTrait use LoggerAwareTrait; private $storeSerialized; - private $values = array(); - private $expiries = array(); + private $values = []; + private $expiries = []; /** * Returns all cached values, with cache miss as null. @@ -69,7 +69,7 @@ trait ArrayTrait */ public function clear() { - $this->values = $this->expiries = array(); + $this->values = $this->expiries = []; return true; } @@ -128,7 +128,7 @@ trait ArrayTrait $serialized = serialize($value); } catch (\Exception $e) { $type = \is_object($value) ? \get_class($value) : \gettype($value); - CacheItem::log($this->logger, 'Failed to save key "{key}" ({type})', array('key' => $key, 'type' => $type, 'exception' => $e)); + CacheItem::log($this->logger, 'Failed to save key "{key}" ({type})', ['key' => $key, 'type' => $type, 'exception' => $e]); return; } @@ -150,7 +150,7 @@ trait ArrayTrait try { $value = unserialize($value); } catch (\Exception $e) { - CacheItem::log($this->logger, 'Failed to unserialize key "{key}"', array('key' => $key, 'exception' => $e)); + CacheItem::log($this->logger, 'Failed to unserialize key "{key}"', ['key' => $key, 'exception' => $e]); $value = false; } if (false === $value) { diff --git a/src/Symfony/Component/Cache/Traits/ContractsTrait.php b/src/Symfony/Component/Cache/Traits/ContractsTrait.php index f755e65fc3..8b1eb5a244 100644 --- a/src/Symfony/Component/Cache/Traits/ContractsTrait.php +++ b/src/Symfony/Component/Cache/Traits/ContractsTrait.php @@ -30,7 +30,7 @@ trait ContractsTrait doGet as private contractsGet; } - private $callbackWrapper = array(LockRegistry::class, 'compute'); + private $callbackWrapper = [LockRegistry::class, 'compute']; /** * Wraps the callback passed to ->get() in a callable. diff --git a/src/Symfony/Component/Cache/Traits/MemcachedTrait.php b/src/Symfony/Component/Cache/Traits/MemcachedTrait.php index 1e1718a412..b25f29f524 100644 --- a/src/Symfony/Component/Cache/Traits/MemcachedTrait.php +++ b/src/Symfony/Component/Cache/Traits/MemcachedTrait.php @@ -24,12 +24,12 @@ use Symfony\Component\Cache\Marshaller\MarshallerInterface; */ trait MemcachedTrait { - private static $defaultClientOptions = array( + private static $defaultClientOptions = [ 'persistent_id' => null, 'username' => null, 'password' => null, 'serializer' => 'php', - ); + ]; private $marshaller; private $client; @@ -77,10 +77,10 @@ trait MemcachedTrait * * @throws \ErrorException When invalid options or servers are provided */ - public static function createConnection($servers, array $options = array()) + public static function createConnection($servers, array $options = []) { if (\is_string($servers)) { - $servers = array($servers); + $servers = [$servers]; } elseif (!\is_array($servers)) { throw new InvalidArgumentException(sprintf('MemcachedAdapter::createClient() expects array or string as first argument, %s given.', \gettype($servers))); } @@ -104,7 +104,7 @@ trait MemcachedTrait } $params = preg_replace_callback('#^memcached:(//)?(?:([^@]*+)@)?#', function ($m) use (&$username, &$password) { if (!empty($m[2])) { - list($username, $password) = explode(':', $m[2], 2) + array(1 => null); + list($username, $password) = explode(':', $m[2], 2) + [1 => null]; } return 'file:'.($m[1] ?? ''); @@ -112,7 +112,7 @@ trait MemcachedTrait if (false === $params = parse_url($params)) { throw new InvalidArgumentException(sprintf('Invalid Memcached DSN: %s', $dsn)); } - $query = $hosts = array(); + $query = $hosts = []; if (isset($params['query'])) { parse_str($params['query'], $query); @@ -122,9 +122,9 @@ trait MemcachedTrait } foreach ($hosts as $host => $weight) { if (false === $port = strrpos($host, ':')) { - $hosts[$host] = array($host, 11211, (int) $weight); + $hosts[$host] = [$host, 11211, (int) $weight]; } else { - $hosts[$host] = array(substr($host, 0, $port), (int) substr($host, 1 + $port), (int) $weight); + $hosts[$host] = [substr($host, 0, $port), (int) substr($host, 1 + $port), (int) $weight]; } } $hosts = array_values($hosts); @@ -143,17 +143,17 @@ trait MemcachedTrait $params['weight'] = $m[1]; $params['path'] = substr($params['path'], 0, -\strlen($m[0])); } - $params += array( + $params += [ 'host' => isset($params['host']) ? $params['host'] : $params['path'], 'port' => isset($params['host']) ? 11211 : null, 'weight' => 0, - ); + ]; if ($query) { $params += $query; $options = $query + $options; } - $servers[$i] = array($params['host'], $params['port'], $params['weight']); + $servers[$i] = [$params['host'], $params['port'], $params['weight']]; if ($hosts) { $servers = array_merge($servers, $hosts); @@ -185,12 +185,12 @@ trait MemcachedTrait // set client's servers, taking care of persistent connections if (!$client->isPristine()) { - $oldServers = array(); + $oldServers = []; foreach ($client->getServerList() as $server) { - $oldServers[] = array($server['host'], $server['port']); + $oldServers[] = [$server['host'], $server['port']]; } - $newServers = array(); + $newServers = []; foreach ($servers as $server) { if (1 < \count($server)) { $server = array_values($server); @@ -234,7 +234,7 @@ trait MemcachedTrait $lifetime += time(); } - $encodedValues = array(); + $encodedValues = []; foreach ($values as $key => $value) { $encodedValues[rawurlencode($key)] = $value; } @@ -252,7 +252,7 @@ trait MemcachedTrait $encodedResult = $this->checkResultCode($this->getClient()->getMulti($encodedIds)); - $result = array(); + $result = []; foreach ($encodedResult as $key => $value) { $result[rawurldecode($key)] = $this->marshaller->unmarshall($value); } diff --git a/src/Symfony/Component/Cache/Traits/PdoTrait.php b/src/Symfony/Component/Cache/Traits/PdoTrait.php index ea4feee4ac..9917bd91f5 100644 --- a/src/Symfony/Component/Cache/Traits/PdoTrait.php +++ b/src/Symfony/Component/Cache/Traits/PdoTrait.php @@ -37,7 +37,7 @@ trait PdoTrait private $timeCol = 'item_time'; private $username = ''; private $password = ''; - private $connectionOptions = array(); + private $connectionOptions = []; private $namespace; private function init($connOrDsn, $namespace, $defaultLifetime, array $options, ?MarshallerInterface $marshaller) @@ -90,24 +90,24 @@ trait PdoTrait $conn = $this->getConnection(); if ($conn instanceof Connection) { - $types = array( + $types = [ 'mysql' => 'binary', 'sqlite' => 'text', 'pgsql' => 'string', 'oci' => 'string', 'sqlsrv' => 'string', - ); + ]; if (!isset($types[$this->driver])) { throw new \DomainException(sprintf('Creating the cache table is currently not implemented for PDO driver "%s".', $this->driver)); } $schema = new Schema(); $table = $schema->createTable($this->table); - $table->addColumn($this->idCol, $types[$this->driver], array('length' => 255)); - $table->addColumn($this->dataCol, 'blob', array('length' => 16777215)); - $table->addColumn($this->lifetimeCol, 'integer', array('unsigned' => true, 'notnull' => false)); - $table->addColumn($this->timeCol, 'integer', array('unsigned' => true)); - $table->setPrimaryKey(array($this->idCol)); + $table->addColumn($this->idCol, $types[$this->driver], ['length' => 255]); + $table->addColumn($this->dataCol, 'blob', ['length' => 16777215]); + $table->addColumn($this->lifetimeCol, 'integer', ['unsigned' => true, 'notnull' => false]); + $table->addColumn($this->timeCol, 'integer', ['unsigned' => true]); + $table->setPrimaryKey([$this->idCol]); foreach ($schema->toSql($conn->getDatabasePlatform()) as $sql) { $conn->exec($sql); @@ -175,7 +175,7 @@ trait PdoTrait protected function doFetch(array $ids) { $now = time(); - $expired = array(); + $expired = []; $sql = str_pad('', (\count($ids) << 1) - 1, '?,'); $sql = "SELECT $this->idCol, CASE WHEN $this->lifetimeCol IS NULL OR $this->lifetimeCol + $this->timeCol > ? THEN $this->dataCol ELSE NULL END FROM $this->table WHERE $this->idCol IN ($sql)"; @@ -309,7 +309,7 @@ trait PdoTrait try { $stmt = $conn->prepare($sql); } catch (TableNotFoundException $e) { - if (!$conn->isTransactionActive() || \in_array($this->driver, array('pgsql', 'sqlite', 'sqlsrv'), true)) { + if (!$conn->isTransactionActive() || \in_array($this->driver, ['pgsql', 'sqlite', 'sqlsrv'], true)) { $this->createTable(); } $stmt = $conn->prepare($sql); diff --git a/src/Symfony/Component/Cache/Traits/PhpArrayTrait.php b/src/Symfony/Component/Cache/Traits/PhpArrayTrait.php index 587da5a498..3d3bab97de 100644 --- a/src/Symfony/Component/Cache/Traits/PhpArrayTrait.php +++ b/src/Symfony/Component/Cache/Traits/PhpArrayTrait.php @@ -57,7 +57,7 @@ trait PhpArrayTrait } $dumpedValues = ''; - $dumpedMap = array(); + $dumpedMap = []; $dump = <<<'EOF' keys = $this->values = array(); + $this->keys = $this->values = []; $cleared = @unlink($this->file) || !file_exists($this->file); @@ -137,14 +137,14 @@ EOF; private function initialize() { if (!file_exists($this->file)) { - $this->keys = $this->values = array(); + $this->keys = $this->values = []; return; } - $values = (include $this->file) ?: array(array(), array()); + $values = (include $this->file) ?: [[], []]; if (2 !== \count($values) || !isset($values[0], $values[1])) { - $this->keys = $this->values = array(); + $this->keys = $this->values = []; } else { list($this->keys, $this->values) = $values; } diff --git a/src/Symfony/Component/Cache/Traits/PhpFilesTrait.php b/src/Symfony/Component/Cache/Traits/PhpFilesTrait.php index 636ad3d99b..dd7518a47a 100644 --- a/src/Symfony/Component/Cache/Traits/PhpFilesTrait.php +++ b/src/Symfony/Component/Cache/Traits/PhpFilesTrait.php @@ -31,8 +31,8 @@ trait PhpFilesTrait private $includeHandler; private $appendOnly; - private $values = array(); - private $files = array(); + private $values = []; + private $files = []; private static $startTime; @@ -78,13 +78,13 @@ trait PhpFilesTrait { if ($this->appendOnly) { $now = 0; - $missingIds = array(); + $missingIds = []; } else { $now = time(); $missingIds = $ids; - $ids = array(); + $ids = []; } - $values = array(); + $values = []; begin: foreach ($ids as $id) { @@ -124,7 +124,7 @@ trait PhpFilesTrait } $ids = $missingIds; - $missingIds = array(); + $missingIds = []; goto begin; } @@ -215,7 +215,7 @@ trait PhpFilesTrait */ protected function doClear($namespace) { - $this->values = array(); + $this->values = []; return $this->doCommonClear($namespace); } diff --git a/src/Symfony/Component/Cache/Traits/RedisTrait.php b/src/Symfony/Component/Cache/Traits/RedisTrait.php index a7224d216f..43dbb43639 100644 --- a/src/Symfony/Component/Cache/Traits/RedisTrait.php +++ b/src/Symfony/Component/Cache/Traits/RedisTrait.php @@ -27,7 +27,7 @@ use Symfony\Component\Cache\Marshaller\MarshallerInterface; */ trait RedisTrait { - private static $defaultConnectionOptions = array( + private static $defaultConnectionOptions = [ 'class' => null, 'persistent' => 0, 'persistent_id' => null, @@ -40,7 +40,7 @@ trait RedisTrait 'redis_cluster' => false, 'dbindex' => 0, 'failover' => 'none', - ); + ]; private $redis; private $marshaller; @@ -78,7 +78,7 @@ trait RedisTrait * * @return \Redis|\RedisCluster|\Predis\Client According to the "class" option */ - public static function createConnection($dsn, array $options = array()) + public static function createConnection($dsn, array $options = []) { if (0 !== strpos($dsn, 'redis:')) { throw new InvalidArgumentException(sprintf('Invalid Redis DSN: %s does not start with "redis:".', $dsn)); @@ -100,7 +100,7 @@ trait RedisTrait throw new InvalidArgumentException(sprintf('Invalid Redis DSN: %s', $dsn)); } - $query = $hosts = array(); + $query = $hosts = []; if (isset($params['query'])) { parse_str($params['query'], $query); @@ -114,11 +114,11 @@ trait RedisTrait parse_str($parameters, $parameters); } if (false === $i = strrpos($host, ':')) { - $hosts[$host] = array('scheme' => 'tcp', 'host' => $host, 'port' => 6379) + $parameters; + $hosts[$host] = ['scheme' => 'tcp', 'host' => $host, 'port' => 6379] + $parameters; } elseif ($port = (int) substr($host, 1 + $i)) { - $hosts[$host] = array('scheme' => 'tcp', 'host' => substr($host, 0, $i), 'port' => $port) + $parameters; + $hosts[$host] = ['scheme' => 'tcp', 'host' => substr($host, 0, $i), 'port' => $port] + $parameters; } else { - $hosts[$host] = array('scheme' => 'unix', 'path' => substr($host, 0, $i)) + $parameters; + $hosts[$host] = ['scheme' => 'unix', 'path' => substr($host, 0, $i)] + $parameters; } } $hosts = array_values($hosts); @@ -132,9 +132,9 @@ trait RedisTrait } if (isset($params['host'])) { - array_unshift($hosts, array('scheme' => 'tcp', 'host' => $params['host'], 'port' => $params['port'] ?? 6379)); + array_unshift($hosts, ['scheme' => 'tcp', 'host' => $params['host'], 'port' => $params['port'] ?? 6379]); } else { - array_unshift($hosts, array('scheme' => 'unix', 'path' => $params['path'])); + array_unshift($hosts, ['scheme' => 'unix', 'path' => $params['path']]); } } @@ -243,13 +243,13 @@ trait RedisTrait if ($params['redis_cluster']) { $params['cluster'] = 'redis'; } - $params += array('parameters' => array()); - $params['parameters'] += array( + $params += ['parameters' => []]; + $params['parameters'] += [ 'persistent' => $params['persistent'], 'timeout' => $params['timeout'], 'read_write_timeout' => $params['read_timeout'], 'tcp_nodelay' => true, - ); + ]; if ($params['dbindex']) { $params['parameters']['database'] = $params['dbindex']; } @@ -258,9 +258,9 @@ trait RedisTrait } if (1 === \count($hosts) && !$params['redis_cluster']) { $hosts = $hosts[0]; - } elseif (\in_array($params['failover'], array('slaves', 'distribute'), true) && !isset($params['replication'])) { + } elseif (\in_array($params['failover'], ['slaves', 'distribute'], true) && !isset($params['replication'])) { $params['replication'] = true; - $hosts[0] += array('alias' => 'master'); + $hosts[0] += ['alias' => 'master']; } $redis = new $class($hosts, array_diff_key($params, self::$defaultConnectionOptions)); @@ -279,15 +279,15 @@ trait RedisTrait protected function doFetch(array $ids) { if (!$ids) { - return array(); + return []; } - $result = array(); + $result = []; if ($this->redis instanceof \Predis\Client) { $values = $this->pipeline(function () use ($ids) { foreach ($ids as $id) { - yield 'get' => array($id); + yield 'get' => [$id]; } }); } else { @@ -317,26 +317,26 @@ trait RedisTrait protected function doClear($namespace) { $cleared = true; - $hosts = array($this->redis); - $evalArgs = array(array($namespace), 0); + $hosts = [$this->redis]; + $evalArgs = [[$namespace], 0]; if ($this->redis instanceof \Predis\Client) { - $evalArgs = array(0, $namespace); + $evalArgs = [0, $namespace]; $connection = $this->redis->getConnection(); if ($connection instanceof ClusterInterface && $connection instanceof \Traversable) { - $hosts = array(); + $hosts = []; foreach ($connection as $c) { $hosts[] = new \Predis\Client($c); } } } elseif ($this->redis instanceof \RedisArray) { - $hosts = array(); + $hosts = []; foreach ($this->redis->_hosts() as $host) { $hosts[] = $this->redis->_instance($host); } } elseif ($this->redis instanceof RedisClusterProxy || $this->redis instanceof \RedisCluster) { - $hosts = array(); + $hosts = []; foreach ($this->redis->_masters() as $host) { $hosts[] = $h = new \Redis(); $h->connect($host[0], $host[1]); @@ -388,7 +388,7 @@ trait RedisTrait if ($this->redis instanceof \Predis\Client) { $this->pipeline(function () use ($ids) { foreach ($ids as $id) { - yield 'del' => array($id); + yield 'del' => [$id]; } })->rewind(); } else { @@ -410,9 +410,9 @@ trait RedisTrait $results = $this->pipeline(function () use ($values, $lifetime) { foreach ($values as $id => $value) { if (0 >= $lifetime) { - yield 'set' => array($id, $value); + yield 'set' => [$id, $value]; } else { - yield 'setEx' => array($id, $lifetime, $value); + yield 'setEx' => [$id, $lifetime, $value]; } } }); @@ -427,13 +427,13 @@ trait RedisTrait private function pipeline(\Closure $generator) { - $ids = array(); + $ids = []; if ($this->redis instanceof RedisClusterProxy || $this->redis instanceof \RedisCluster || ($this->redis instanceof \Predis\Client && $this->redis->getConnection() instanceof RedisCluster)) { // phpredis & predis don't support pipelining with RedisCluster // see https://github.com/phpredis/phpredis/blob/develop/cluster.markdown#pipelining // see https://github.com/nrk/predis/issues/267#issuecomment-123781423 - $results = array(); + $results = []; foreach ($generator() as $command => $args) { $results[] = $this->redis->{$command}(...$args); $ids[] = $args[0]; @@ -446,14 +446,14 @@ trait RedisTrait } }); } elseif ($this->redis instanceof \RedisArray) { - $connections = $results = $ids = array(); + $connections = $results = $ids = []; foreach ($generator() as $command => $args) { if (!isset($connections[$h = $this->redis->_target($args[0])])) { - $connections[$h] = array($this->redis->_instance($h), -1); + $connections[$h] = [$this->redis->_instance($h), -1]; $connections[$h][0]->multi(\Redis::PIPELINE); } $connections[$h][0]->{$command}(...$args); - $results[] = array($h, ++$connections[$h][1]); + $results[] = [$h, ++$connections[$h][1]]; $ids[] = $args[0]; } foreach ($connections as $h => $c) { diff --git a/src/Symfony/Component/Config/Definition/ArrayNode.php b/src/Symfony/Component/Config/Definition/ArrayNode.php index b221fafeeb..dd908c999e 100644 --- a/src/Symfony/Component/Config/Definition/ArrayNode.php +++ b/src/Symfony/Component/Config/Definition/ArrayNode.php @@ -306,7 +306,7 @@ class ArrayNode extends BaseNode implements PrototypeNodeInterface if (\count($value) && !$this->ignoreExtraKeys) { $proposals = array_keys($this->children); sort($proposals); - $guesses = array(); + $guesses = []; foreach (array_keys($value) as $subject) { $minScore = INF; diff --git a/src/Symfony/Component/Config/Loader/FileLoader.php b/src/Symfony/Component/Config/Loader/FileLoader.php index d7bf2c9559..ab48492a4b 100644 --- a/src/Symfony/Component/Config/Loader/FileLoader.php +++ b/src/Symfony/Component/Config/Loader/FileLoader.php @@ -93,7 +93,7 @@ abstract class FileLoader extends Loader /** * @internal */ - protected function glob(string $pattern, bool $recursive, &$resource = null, bool $ignoreErrors = false, bool $forExclusion = false, array $excluded = array()) + protected function glob(string $pattern, bool $recursive, &$resource = null, bool $ignoreErrors = false, bool $forExclusion = false, array $excluded = []) { if (\strlen($pattern) === $i = strcspn($pattern, '*?{[')) { $prefix = $pattern; diff --git a/src/Symfony/Component/Config/Resource/GlobResource.php b/src/Symfony/Component/Config/Resource/GlobResource.php index bd110d72f5..195a8e5eec 100644 --- a/src/Symfony/Component/Config/Resource/GlobResource.php +++ b/src/Symfony/Component/Config/Resource/GlobResource.php @@ -37,7 +37,7 @@ class GlobResource implements \IteratorAggregate, SelfCheckingResourceInterface, * * @throws \InvalidArgumentException */ - public function __construct(?string $prefix, string $pattern, bool $recursive, bool $forExclusion = false, array $excludedPrefixes = array()) + public function __construct(?string $prefix, string $pattern, bool $recursive, bool $forExclusion = false, array $excludedPrefixes = []) { $this->prefix = realpath($prefix) ?: (file_exists($prefix) ? $prefix : false); $this->pattern = $pattern; @@ -83,12 +83,12 @@ class GlobResource implements \IteratorAggregate, SelfCheckingResourceInterface, $this->hash = $this->computeHash(); } - return serialize(array($this->prefix, $this->pattern, $this->recursive, $this->hash, $this->forExclusion, $this->excludedPrefixes)); + return serialize([$this->prefix, $this->pattern, $this->recursive, $this->hash, $this->forExclusion, $this->excludedPrefixes]); } public function unserialize($serialized) { - list($this->prefix, $this->pattern, $this->recursive, $this->hash, $this->forExclusion, $this->excludedPrefixes) = unserialize($serialized) + array(4 => false, array()); + list($this->prefix, $this->pattern, $this->recursive, $this->hash, $this->forExclusion, $this->excludedPrefixes) = unserialize($serialized) + [4 => false, []]; } public function getIterator() diff --git a/src/Symfony/Component/Config/Resource/ReflectionClassResource.php b/src/Symfony/Component/Config/Resource/ReflectionClassResource.php index 21b1972feb..04a9aafd44 100644 --- a/src/Symfony/Component/Config/Resource/ReflectionClassResource.php +++ b/src/Symfony/Component/Config/Resource/ReflectionClassResource.php @@ -160,7 +160,7 @@ class ReflectionClassResource implements SelfCheckingResourceInterface, \Seriali if (interface_exists(LegacyServiceSubscriberInterface::class, false) && $class->isSubclassOf(LegacyServiceSubscriberInterface::class)) { yield LegacyServiceSubscriberInterface::class; - yield print_r(array($class->name, 'getSubscribedServices')(), true); + yield print_r([$class->name, 'getSubscribedServices'](), true); } elseif (interface_exists(ServiceSubscriberInterface::class, false) && $class->isSubclassOf(ServiceSubscriberInterface::class)) { yield ServiceSubscriberInterface::class; yield print_r($class->name::getSubscribedServices(), true); diff --git a/src/Symfony/Component/Config/Tests/Definition/ArrayNodeTest.php b/src/Symfony/Component/Config/Tests/Definition/ArrayNodeTest.php index cc224346c0..771057d0b3 100644 --- a/src/Symfony/Component/Config/Tests/Definition/ArrayNodeTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/ArrayNodeTest.php @@ -47,7 +47,7 @@ class ArrayNodeTest extends TestCase $node->addChild(new ArrayNode('alpha1')); $node->addChild(new ArrayNode('alpha2')); $node->addChild(new ArrayNode('beta')); - $node->normalize(array('alpha3' => 'foo')); + $node->normalize(['alpha3' => 'foo']); } /** @@ -59,7 +59,7 @@ class ArrayNodeTest extends TestCase $node = new ArrayNode('root'); $node->addChild(new ArrayNode('alpha1')); $node->addChild(new ArrayNode('alpha2')); - $node->normalize(array('beta' => 'foo')); + $node->normalize(['beta' => 'foo']); } public function ignoreAndRemoveMatrixProvider() diff --git a/src/Symfony/Component/Config/Tests/Definition/Builder/ArrayNodeDefinitionTest.php b/src/Symfony/Component/Config/Tests/Definition/Builder/ArrayNodeDefinitionTest.php index 0d4cad96bd..0aa2a08ab4 100644 --- a/src/Symfony/Component/Config/Tests/Definition/Builder/ArrayNodeDefinitionTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/Builder/ArrayNodeDefinitionTest.php @@ -50,13 +50,13 @@ class ArrayNodeDefinitionTest extends TestCase public function providePrototypeNodeSpecificCalls() { - return array( - array('defaultValue', array(array())), - array('addDefaultChildrenIfNoneSet', array()), - array('requiresAtLeastOneElement', array()), - array('cannotBeEmpty', array()), - array('useAttributeAsKey', array('foo')), - ); + return [ + ['defaultValue', [[]]], + ['addDefaultChildrenIfNoneSet', []], + ['requiresAtLeastOneElement', []], + ['cannotBeEmpty', []], + ['useAttributeAsKey', ['foo']], + ]; } /** @@ -79,7 +79,7 @@ class ArrayNodeDefinitionTest extends TestCase { $node = new ArrayNodeDefinition('root'); $node - ->defaultValue(array()) + ->defaultValue([]) ->addDefaultChildrenIfNoneSet('foo') ->prototype('array') ; @@ -94,7 +94,7 @@ class ArrayNodeDefinitionTest extends TestCase ->prototype('array') ; $tree = $node->getNode(); - $this->assertEquals(array(array()), $tree->getDefaultValue()); + $this->assertEquals([[]], $tree->getDefaultValue()); } /** @@ -134,14 +134,14 @@ class ArrayNodeDefinitionTest extends TestCase public function providePrototypedArrayNodeDefaults() { - return array( - array(null, true, false, array(array())), - array(2, true, false, array(array(), array())), - array('2', false, true, array('2' => array())), - array('foo', false, true, array('foo' => array())), - array(array('foo'), false, true, array('foo' => array())), - array(array('foo', 'bar'), false, true, array('foo' => array(), 'bar' => array())), - ); + return [ + [null, true, false, [[]]], + [2, true, false, [[], []]], + ['2', false, true, ['2' => []]], + ['foo', false, true, ['foo' => []]], + [['foo'], false, true, ['foo' => []]], + [['foo', 'bar'], false, true, ['foo' => [], 'bar' => []]], + ]; } public function testNestedPrototypedArrayNodes() @@ -167,7 +167,7 @@ class ArrayNodeDefinitionTest extends TestCase ->scalarNode('foo')->defaultValue('bar')->end() ; - $this->assertEquals(array('enabled' => false, 'foo' => 'bar'), $node->getNode()->getDefaultValue()); + $this->assertEquals(['enabled' => false, 'foo' => 'bar'], $node->getNode()->getDefaultValue()); } /** @@ -196,9 +196,9 @@ class ArrayNodeDefinitionTest extends TestCase $node->canBeDisabled(); $this->assertTrue($this->getField($node, 'addDefaults')); - $this->assertEquals(array('enabled' => false), $this->getField($node, 'falseEquivalent')); - $this->assertEquals(array('enabled' => true), $this->getField($node, 'trueEquivalent')); - $this->assertEquals(array('enabled' => true), $this->getField($node, 'nullEquivalent')); + $this->assertEquals(['enabled' => false], $this->getField($node, 'falseEquivalent')); + $this->assertEquals(['enabled' => true], $this->getField($node, 'trueEquivalent')); + $this->assertEquals(['enabled' => true], $this->getField($node, 'nullEquivalent')); $nodeChildren = $this->getField($node, 'children'); $this->assertArrayHasKey('enabled', $nodeChildren); @@ -248,7 +248,7 @@ class ArrayNodeDefinitionTest extends TestCase ->end() ; - $this->assertSame(array(), $node->getNode()->normalize(array('value' => null))); + $this->assertSame([], $node->getNode()->normalize(['value' => null])); } public function testPrototypeVariable() @@ -295,14 +295,14 @@ class ArrayNodeDefinitionTest extends TestCase public function getEnableableNodeFixtures() { - return array( - array(array('enabled' => true, 'foo' => 'bar'), array(true), 'true enables an enableable node'), - array(array('enabled' => true, 'foo' => 'bar'), array(null), 'null enables an enableable node'), - array(array('enabled' => true, 'foo' => 'bar'), array(array('enabled' => true)), 'An enableable node can be enabled'), - array(array('enabled' => true, 'foo' => 'baz'), array(array('foo' => 'baz')), 'any configuration enables an enableable node'), - array(array('enabled' => false, 'foo' => 'baz'), array(array('foo' => 'baz', 'enabled' => false)), 'An enableable node can be disabled'), - array(array('enabled' => false, 'foo' => 'bar'), array(false), 'false disables an enableable node'), - ); + return [ + [['enabled' => true, 'foo' => 'bar'], [true], 'true enables an enableable node'], + [['enabled' => true, 'foo' => 'bar'], [null], 'null enables an enableable node'], + [['enabled' => true, 'foo' => 'bar'], [['enabled' => true]], 'An enableable node can be enabled'], + [['enabled' => true, 'foo' => 'baz'], [['foo' => 'baz']], 'any configuration enables an enableable node'], + [['enabled' => false, 'foo' => 'baz'], [['foo' => 'baz', 'enabled' => false]], 'An enableable node can be disabled'], + [['enabled' => false, 'foo' => 'bar'], [false], 'false disables an enableable node'], + ]; } public function testRequiresAtLeastOneElement() @@ -312,7 +312,7 @@ class ArrayNodeDefinitionTest extends TestCase ->requiresAtLeastOneElement() ->integerPrototype(); - $node->getNode()->finalize(array(1)); + $node->getNode()->finalize([1]); $this->addToAssertionCount(1); } @@ -328,7 +328,7 @@ class ArrayNodeDefinitionTest extends TestCase ->cannotBeEmpty() ->integerPrototype(); - $node->getNode()->finalize(array()); + $node->getNode()->finalize([]); } public function testSetDeprecated() @@ -354,7 +354,7 @@ class ArrayNodeDefinitionTest extends TestCase $node = new ArrayNodeDefinition('root'); $node->cannotBeEmpty(); - $node->getNode()->finalize(array()); + $node->getNode()->finalize([]); } protected function getField($object, $field) diff --git a/src/Symfony/Component/Config/Tests/Definition/Builder/TreeBuilderTest.php b/src/Symfony/Component/Config/Tests/Definition/Builder/TreeBuilderTest.php index 27c8ea231d..0dae83be41 100644 --- a/src/Symfony/Component/Config/Tests/Definition/Builder/TreeBuilderTest.php +++ b/src/Symfony/Component/Config/Tests/Definition/Builder/TreeBuilderTest.php @@ -115,7 +115,7 @@ class TreeBuilderTest extends TestCase $builder = new TreeBuilder('test'); $builder->getRootNode() - ->example(array('key' => 'value')) + ->example(['key' => 'value']) ->children() ->node('child', 'variable')->info('child info')->defaultValue('default')->example('example') ->end() diff --git a/src/Symfony/Component/Config/Tests/Resource/GlobResourceTest.php b/src/Symfony/Component/Config/Tests/Resource/GlobResourceTest.php index 0f8504a893..5e0b248002 100644 --- a/src/Symfony/Component/Config/Tests/Resource/GlobResourceTest.php +++ b/src/Symfony/Component/Config/Tests/Resource/GlobResourceTest.php @@ -62,7 +62,7 @@ class GlobResourceTest extends TestCase public function testIteratorSkipsFoldersForGivenExcludedPrefixes() { $dir = \dirname(__DIR__).\DIRECTORY_SEPARATOR.'Fixtures'; - $resource = new GlobResource($dir, '/*Exclude*', true, false, array($dir.\DIRECTORY_SEPARATOR.'Exclude' => true)); + $resource = new GlobResource($dir, '/*Exclude*', true, false, [$dir.\DIRECTORY_SEPARATOR.'Exclude' => true]); $paths = iterator_to_array($resource); @@ -76,7 +76,7 @@ class GlobResourceTest extends TestCase public function testIteratorSkipsSubfoldersForGivenExcludedPrefixes() { $dir = \dirname(__DIR__).\DIRECTORY_SEPARATOR.'Fixtures'; - $resource = new GlobResource($dir, '/*Exclude/*', true, false, array($dir.\DIRECTORY_SEPARATOR.'Exclude' => true)); + $resource = new GlobResource($dir, '/*Exclude/*', true, false, [$dir.\DIRECTORY_SEPARATOR.'Exclude' => true]); $paths = iterator_to_array($resource); @@ -90,7 +90,7 @@ class GlobResourceTest extends TestCase public function testIteratorSkipsFoldersWithForwardSlashForGivenExcludedPrefixes() { $dir = \dirname(__DIR__).\DIRECTORY_SEPARATOR.'Fixtures'; - $resource = new GlobResource($dir, '/*Exclude*', true, false, array($dir.'/Exclude' => true)); + $resource = new GlobResource($dir, '/*Exclude*', true, false, [$dir.'/Exclude' => true]); $paths = iterator_to_array($resource); diff --git a/src/Symfony/Component/Console/Helper/ProcessHelper.php b/src/Symfony/Component/Console/Helper/ProcessHelper.php index f03774d35d..e3a7c77b35 100644 --- a/src/Symfony/Component/Console/Helper/ProcessHelper.php +++ b/src/Symfony/Component/Console/Helper/ProcessHelper.php @@ -46,17 +46,17 @@ class ProcessHelper extends Helper $formatter = $this->getHelperSet()->get('debug_formatter'); if ($cmd instanceof Process) { - $cmd = array($cmd); + $cmd = [$cmd]; } if (!\is_array($cmd)) { @trigger_error(sprintf('Passing a command as a string to "%s()" is deprecated since Symfony 4.2, pass it the command as an array of arguments instead.', __METHOD__), E_USER_DEPRECATED); - $cmd = array(\method_exists(Process::class, 'fromShellCommandline') ? Process::fromShellCommandline($cmd) : new Process($cmd)); + $cmd = [\method_exists(Process::class, 'fromShellCommandline') ? Process::fromShellCommandline($cmd) : new Process($cmd)]; } if (\is_string($cmd[0] ?? null)) { $process = new Process($cmd); - $cmd = array(); + $cmd = []; } elseif (($cmd[0] ?? null) instanceof Process) { $process = $cmd[0]; unset($cmd[0]); diff --git a/src/Symfony/Component/Console/Helper/Table.php b/src/Symfony/Component/Console/Helper/Table.php index 14974529c4..99aa83d4c8 100644 --- a/src/Symfony/Component/Console/Helper/Table.php +++ b/src/Symfony/Component/Console/Helper/Table.php @@ -41,17 +41,17 @@ class Table /** * Table headers. */ - private $headers = array(); + private $headers = []; /** * Table rows. */ - private $rows = array(); + private $rows = []; /** * Column widths cache. */ - private $effectiveColumnWidths = array(); + private $effectiveColumnWidths = []; /** * Number of columns cache. @@ -73,15 +73,15 @@ class Table /** * @var array */ - private $columnStyles = array(); + private $columnStyles = []; /** * User set column widths. * * @var array */ - private $columnWidths = array(); - private $columnMaxWidths = array(); + private $columnWidths = []; + private $columnMaxWidths = []; private static $styles; @@ -212,7 +212,7 @@ class Table */ public function setColumnWidths(array $widths) { - $this->columnWidths = array(); + $this->columnWidths = []; foreach ($widths as $index => $width) { $this->setColumnWidth($index, $width); } @@ -243,7 +243,7 @@ class Table { $headers = array_values($headers); if (!empty($headers) && !\is_array($headers[0])) { - $headers = array($headers); + $headers = [$headers]; } $this->headers = $headers; @@ -253,7 +253,7 @@ class Table public function setRows(array $rows) { - $this->rows = array(); + $this->rows = []; return $this->addRows($rows); } @@ -339,7 +339,7 @@ class Table */ public function render() { - $rows = array_merge($this->headers, array($divider = new TableSeparator()), $this->rows); + $rows = array_merge($this->headers, [$divider = new TableSeparator()], $this->rows); $this->calculateNumberOfColumns($rows); $rows = $this->buildTableRows($rows); @@ -400,13 +400,13 @@ class Table $crossings = $this->style->getCrossingChars(); if (self::SEPARATOR_MID === $type) { - list($horizontal, $leftChar, $midChar, $rightChar) = array($borders[2], $crossings[8], $crossings[0], $crossings[4]); + list($horizontal, $leftChar, $midChar, $rightChar) = [$borders[2], $crossings[8], $crossings[0], $crossings[4]]; } elseif (self::SEPARATOR_TOP === $type) { - list($horizontal, $leftChar, $midChar, $rightChar) = array($borders[0], $crossings[1], $crossings[2], $crossings[3]); + list($horizontal, $leftChar, $midChar, $rightChar) = [$borders[0], $crossings[1], $crossings[2], $crossings[3]]; } elseif (self::SEPARATOR_TOP_BOTTOM === $type) { - list($horizontal, $leftChar, $midChar, $rightChar) = array($borders[0], $crossings[9], $crossings[10], $crossings[11]); + list($horizontal, $leftChar, $midChar, $rightChar) = [$borders[0], $crossings[9], $crossings[10], $crossings[11]]; } else { - list($horizontal, $leftChar, $midChar, $rightChar) = array($borders[0], $crossings[7], $crossings[6], $crossings[5]); + list($horizontal, $leftChar, $midChar, $rightChar) = [$borders[0], $crossings[7], $crossings[6], $crossings[5]]; } $markup = $leftChar; @@ -500,7 +500,7 @@ class Table */ private function calculateNumberOfColumns($rows) { - $columns = array(0); + $columns = [0]; foreach ($rows as $row) { if ($row instanceof TableSeparator) { continue; @@ -516,7 +516,7 @@ class Table { /** @var WrappableOutputFormatterInterface $formatter */ $formatter = $this->output->getFormatter(); - $unmergedRows = array(); + $unmergedRows = []; for ($rowKey = 0; $rowKey < \count($rows); ++$rowKey) { $rows = $this->fillNextRows($rows, $rowKey); @@ -531,7 +531,7 @@ class Table $lines = explode("\n", str_replace("\n", "\n", $cell)); foreach ($lines as $lineKey => $line) { if ($cell instanceof TableCell) { - $line = new TableCell($line, array('colspan' => $cell->getColspan())); + $line = new TableCell($line, ['colspan' => $cell->getColspan()]); } if (0 === $lineKey) { $rows[$rowKey][$column] = $line; @@ -557,7 +557,7 @@ class Table private function calculateRowCount(): int { - $numberOfRows = \count(iterator_to_array($this->buildTableRows(array_merge($this->headers, array(new TableSeparator()), $this->rows)))); + $numberOfRows = \count(iterator_to_array($this->buildTableRows(array_merge($this->headers, [new TableSeparator()], $this->rows)))); if ($this->headers) { ++$numberOfRows; // Add row for header separator @@ -575,27 +575,27 @@ class Table */ private function fillNextRows(array $rows, int $line): array { - $unmergedRows = array(); + $unmergedRows = []; foreach ($rows[$line] as $column => $cell) { if (null !== $cell && !$cell instanceof TableCell && !is_scalar($cell) && !(\is_object($cell) && method_exists($cell, '__toString'))) { throw new InvalidArgumentException(sprintf('A cell must be a TableCell, a scalar or an object implementing __toString, %s given.', \gettype($cell))); } if ($cell instanceof TableCell && $cell->getRowspan() > 1) { $nbLines = $cell->getRowspan() - 1; - $lines = array($cell); + $lines = [$cell]; if (strstr($cell, "\n")) { $lines = explode("\n", str_replace("\n", "\n", $cell)); $nbLines = \count($lines) > $nbLines ? substr_count($cell, "\n") : $nbLines; - $rows[$line][$column] = new TableCell($lines[0], array('colspan' => $cell->getColspan())); + $rows[$line][$column] = new TableCell($lines[0], ['colspan' => $cell->getColspan()]); unset($lines[0]); } // create a two dimensional array (rowspan x colspan) - $unmergedRows = array_replace_recursive(array_fill($line + 1, $nbLines, array()), $unmergedRows); + $unmergedRows = array_replace_recursive(array_fill($line + 1, $nbLines, []), $unmergedRows); foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) { $value = isset($lines[$unmergedRowKey - $line]) ? $lines[$unmergedRowKey - $line] : ''; - $unmergedRows[$unmergedRowKey][$column] = new TableCell($value, array('colspan' => $cell->getColspan())); + $unmergedRows[$unmergedRowKey][$column] = new TableCell($value, ['colspan' => $cell->getColspan()]); if ($nbLines === $unmergedRowKey - $line) { break; } @@ -608,7 +608,7 @@ class Table if (isset($rows[$unmergedRowKey]) && \is_array($rows[$unmergedRowKey]) && ($this->getNumberOfColumns($rows[$unmergedRowKey]) + $this->getNumberOfColumns($unmergedRows[$unmergedRowKey]) <= $this->numberOfColumns)) { foreach ($unmergedRow as $cellKey => $cell) { // insert cell into row at cellKey position - array_splice($rows[$unmergedRowKey], $cellKey, 0, array($cell)); + array_splice($rows[$unmergedRowKey], $cellKey, 0, [$cell]); } } else { $row = $this->copyRow($rows, $unmergedRowKey - 1); @@ -617,7 +617,7 @@ class Table $row[$column] = $unmergedRow[$column]; } } - array_splice($rows, $unmergedRowKey, 0, array($row)); + array_splice($rows, $unmergedRowKey, 0, [$row]); } } @@ -629,7 +629,7 @@ class Table */ private function fillCells($row) { - $newRow = array(); + $newRow = []; foreach ($row as $column => $cell) { $newRow[] = $cell; if ($cell instanceof TableCell && $cell->getColspan() > 1) { @@ -649,7 +649,7 @@ class Table foreach ($row as $cellKey => $cellValue) { $row[$cellKey] = ''; if ($cellValue instanceof TableCell) { - $row[$cellKey] = new TableCell('', array('colspan' => $cellValue->getColspan())); + $row[$cellKey] = new TableCell('', ['colspan' => $cellValue->getColspan()]); } } @@ -691,7 +691,7 @@ class Table private function calculateColumnsWidth(iterable $rows) { for ($column = 0; $column < $this->numberOfColumns; ++$column) { - $lengths = array(); + $lengths = []; foreach ($rows as $row) { if ($row instanceof TableSeparator) { continue; @@ -742,7 +742,7 @@ class Table */ private function cleanup() { - $this->effectiveColumnWidths = array(); + $this->effectiveColumnWidths = []; $this->numberOfColumns = null; } @@ -783,14 +783,14 @@ class Table ->setCrossingChars('┼', '╔', '╤', '╗', '╢', '╝', '╧', '╚', '╟', '╠', '╪', '╣') ; - return array( + return [ 'default' => new TableStyle(), 'borderless' => $borderless, 'compact' => $compact, 'symfony-style-guide' => $styleGuide, 'box' => $box, 'box-double' => $boxDouble, - ); + ]; } private function resolveStyle($name) diff --git a/src/Symfony/Component/Console/Tester/TesterTrait.php b/src/Symfony/Component/Console/Tester/TesterTrait.php index b66972cae5..e5df56d835 100644 --- a/src/Symfony/Component/Console/Tester/TesterTrait.php +++ b/src/Symfony/Component/Console/Tester/TesterTrait.php @@ -23,7 +23,7 @@ trait TesterTrait { /** @var StreamOutput */ private $output; - private $inputs = array(); + private $inputs = []; private $captureStreamsIndependently = false; /** diff --git a/src/Symfony/Component/Console/Tests/ApplicationTest.php b/src/Symfony/Component/Console/Tests/ApplicationTest.php index b7b54f858e..2aaf9d7dae 100644 --- a/src/Symfony/Component/Console/Tests/ApplicationTest.php +++ b/src/Symfony/Component/Console/Tests/ApplicationTest.php @@ -84,7 +84,7 @@ class ApplicationTest extends TestCase $application = new Application('foo', 'bar'); $this->assertEquals('foo', $application->getName(), '__construct() takes the application name as its first argument'); $this->assertEquals('bar', $application->getVersion(), '__construct() takes the application version as its second argument'); - $this->assertEquals(array('help', 'list'), array_keys($application->all()), '__construct() registered the help and list commands by default'); + $this->assertEquals(['help', 'list'], array_keys($application->all()), '__construct() registered the help and list commands by default'); } public function testSetGetName() @@ -134,9 +134,9 @@ class ApplicationTest extends TestCase $commands = $application->all('foo'); $this->assertCount(1, $commands, '->all() takes a namespace as its first argument'); - $application->setCommandLoader(new FactoryCommandLoader(array( + $application->setCommandLoader(new FactoryCommandLoader([ 'foo:bar1' => function () { return new \Foo1Command(); }, - ))); + ])); $commands = $application->all('foo'); $this->assertCount(2, $commands, '->all() takes a namespace as its first argument'); $this->assertInstanceOf(\FooCommand::class, $commands['foo:bar'], '->all() returns the registered commands'); @@ -158,9 +158,9 @@ class ApplicationTest extends TestCase $this->assertEquals($foo, $commands['foo:bar'], '->add() registers a command'); $application = new Application(); - $application->addCommands(array($foo = new \FooCommand(), $foo1 = new \Foo1Command())); + $application->addCommands([$foo = new \FooCommand(), $foo1 = new \Foo1Command()]); $commands = $application->all(); - $this->assertEquals(array($foo, $foo1), array($commands['foo:bar'], $commands['foo:bar1']), '->addCommands() registers an array of commands'); + $this->assertEquals([$foo, $foo1], [$commands['foo:bar'], $commands['foo:bar1']], '->addCommands() registers an array of commands'); } /** @@ -206,9 +206,9 @@ class ApplicationTest extends TestCase $this->assertEquals($foo, $application->get('foo:bar'), '->get() returns a command by name'); $this->assertEquals($foo, $application->get('afoobar'), '->get() returns a command by alias'); - $application->setCommandLoader(new FactoryCommandLoader(array( + $application->setCommandLoader(new FactoryCommandLoader([ 'foo:bar1' => function () { return new \Foo1Command(); }, - ))); + ])); $this->assertTrue($application->has('afoobar'), '->has() returns true if an instance is registered for an alias even with command loader'); $this->assertEquals($foo, $application->get('foo:bar'), '->get() returns an instance by name even with command loader'); @@ -226,7 +226,7 @@ class ApplicationTest extends TestCase $application->setCatchExceptions(false); $tester = new ApplicationTester($application); - $tester->run(array('-h' => true, '-q' => true), array('decorated' => false)); + $tester->run(['-h' => true, '-q' => true], ['decorated' => false]); $this->assertEmpty($tester->getDisplay(true)); } @@ -246,7 +246,7 @@ class ApplicationTest extends TestCase $application = new Application(); $application->add(new \FooCommand()); $application->add(new \Foo1Command()); - $this->assertEquals(array('foo'), $application->getNamespaces(), '->getNamespaces() returns an array of unique used namespaces'); + $this->assertEquals(['foo'], $application->getNamespaces(), '->getNamespaces() returns an array of unique used namespaces'); } public function testFindNamespace() @@ -368,9 +368,9 @@ class ApplicationTest extends TestCase public function testFindWithCommandLoader() { $application = new Application(); - $application->setCommandLoader(new FactoryCommandLoader(array( + $application->setCommandLoader(new FactoryCommandLoader([ 'foo:bar' => $f = function () { return new \FooCommand(); }, - ))); + ])); $this->assertInstanceOf('FooCommand', $application->find('foo:bar'), '->find() returns a command if its name exists'); $this->assertInstanceOf('Symfony\Component\Console\Command\HelpCommand', $application->find('h'), '->find() returns a command if its name exists'); @@ -401,23 +401,23 @@ class ApplicationTest extends TestCase public function provideAmbiguousAbbreviations() { - return array( - array('f', 'Command "f" is not defined.'), - array( + return [ + ['f', 'Command "f" is not defined.'], + [ 'a', "Command \"a\" is ambiguous.\nDid you mean one of these?\n". " afoobar The foo:bar command\n". " afoobar1 The foo:bar1 command\n". ' afoobar2 The foo1:bar command', - ), - array( + ], + [ 'foo:b', "Command \"foo:b\" is ambiguous.\nDid you mean one of these?\n". " foo:bar The foo:bar command\n". " foo:bar1 The foo:bar1 command\n". ' foo1:bar The foo1:bar command', - ), - ); + ], + ]; } public function testFindCommandEqualNamespace() @@ -465,7 +465,7 @@ class ApplicationTest extends TestCase $application->add(new \Foo1Command()); $application->setAutoExit(false); $tester = new ApplicationTester($application); - $tester->run(array('command' => 'foos:bar1'), array('decorated' => false)); + $tester->run(['command' => 'foos:bar1'], ['decorated' => false]); $this->assertSame(' There are no commands defined in the "foos" namespace. @@ -483,8 +483,8 @@ class ApplicationTest extends TestCase $application->add(new \FooWithoutAliasCommand()); $application->setAutoExit(false); $tester = new ApplicationTester($application); - $tester->setInputs(array('y')); - $tester->run(array('command' => 'foos'), array('decorated' => false)); + $tester->setInputs(['y']); + $tester->run(['command' => 'foos'], ['decorated' => false]); $display = trim($tester->getDisplay(true)); $this->assertContains('Command "foos" is not defined', $display); $this->assertContains('Do you want to run "foo" instead? (yes/no) [no]:', $display); @@ -497,8 +497,8 @@ class ApplicationTest extends TestCase $application->add(new \FooWithoutAliasCommand()); $application->setAutoExit(false); $tester = new ApplicationTester($application); - $tester->setInputs(array('n')); - $exitCode = $tester->run(array('command' => 'foos'), array('decorated' => false)); + $tester->setInputs(['n']); + $exitCode = $tester->run(['command' => 'foos'], ['decorated' => false]); $this->assertSame(1, $exitCode); $display = trim($tester->getDisplay(true)); $this->assertContains('Command "foos" is not defined', $display); @@ -507,10 +507,10 @@ class ApplicationTest extends TestCase public function provideInvalidCommandNamesSingle() { - return array( - array('foo3:barr'), - array('fooo3:bar'), - ); + return [ + ['foo3:barr'], + ['fooo3:bar'], + ]; } public function testFindAlternativeExceptionMessageMultiple() @@ -568,7 +568,7 @@ class ApplicationTest extends TestCase $this->fail('->find() throws a CommandNotFoundException if command does not exist'); } catch (\Exception $e) { $this->assertInstanceOf('Symfony\Component\Console\Exception\CommandNotFoundException', $e, '->find() throws a CommandNotFoundException if command does not exist'); - $this->assertSame(array(), $e->getAlternatives()); + $this->assertSame([], $e->getAlternatives()); $this->assertEquals(sprintf('Command "%s" is not defined.', $commandName), $e->getMessage(), '->find() throws a CommandNotFoundException if command does not exist, without alternatives'); } @@ -579,7 +579,7 @@ class ApplicationTest extends TestCase $this->fail('->find() throws a CommandNotFoundException if command does not exist'); } catch (\Exception $e) { $this->assertInstanceOf('Symfony\Component\Console\Exception\CommandNotFoundException', $e, '->find() throws a CommandNotFoundException if command does not exist'); - $this->assertSame(array('afoobar1', 'foo:bar1'), $e->getAlternatives()); + $this->assertSame(['afoobar1', 'foo:bar1'], $e->getAlternatives()); $this->assertRegExp(sprintf('/Command "%s" is not defined./', $commandName), $e->getMessage(), '->find() throws a CommandNotFoundException if command does not exist, with alternatives'); $this->assertRegExp('/afoobar1/', $e->getMessage(), '->find() throws a CommandNotFoundException if command does not exist, with alternative : "afoobar1"'); $this->assertRegExp('/foo:bar1/', $e->getMessage(), '->find() throws a CommandNotFoundException if command does not exist, with alternative : "foo:bar1"'); @@ -590,7 +590,7 @@ class ApplicationTest extends TestCase public function testFindAlternativeCommandsWithAnAlias() { $fooCommand = new \FooCommand(); - $fooCommand->setAliases(array('foo2')); + $fooCommand->setAliases(['foo2']); $application = new Application(); $application->add($fooCommand); @@ -614,7 +614,7 @@ class ApplicationTest extends TestCase $this->fail('->find() throws a CommandNotFoundException if namespace does not exist'); } catch (\Exception $e) { $this->assertInstanceOf('Symfony\Component\Console\Exception\CommandNotFoundException', $e, '->find() throws a CommandNotFoundException if namespace does not exist'); - $this->assertSame(array(), $e->getAlternatives()); + $this->assertSame([], $e->getAlternatives()); $this->assertEquals('There are no commands defined in the "Unknown-namespace" namespace.', $e->getMessage(), '->find() throws a CommandNotFoundException if namespace does not exist, without alternatives'); } @@ -644,7 +644,7 @@ class ApplicationTest extends TestCase $application->add(new \Foo2Command()); $application->add(new \Foo3Command()); - $expectedAlternatives = array( + $expectedAlternatives = [ 'afoobar', 'afoobar1', 'afoobar2', @@ -652,7 +652,7 @@ class ApplicationTest extends TestCase 'foo3:bar', 'foo:bar', 'foo:bar1', - ); + ]; try { $application->find('foo'); @@ -667,10 +667,10 @@ class ApplicationTest extends TestCase public function testFindNamespaceDoesNotFailOnDeepSimilarNamespaces() { - $application = $this->getMockBuilder('Symfony\Component\Console\Application')->setMethods(array('getNamespaces'))->getMock(); + $application = $this->getMockBuilder('Symfony\Component\Console\Application')->setMethods(['getNamespaces'])->getMock(); $application->expects($this->once()) ->method('getNamespaces') - ->will($this->returnValue(array('foo:sublong', 'bar:sub'))); + ->will($this->returnValue(['foo:sublong', 'bar:sub'])); $this->assertEquals('foo:sublong', $application->findNamespace('f:sub')); } @@ -697,16 +697,16 @@ class ApplicationTest extends TestCase $application->setCatchExceptions(true); $this->assertTrue($application->areExceptionsCaught()); - $tester->run(array('command' => 'foo'), array('decorated' => false)); + $tester->run(['command' => 'foo'], ['decorated' => false]); $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception1.txt', $tester->getDisplay(true), '->setCatchExceptions() sets the catch exception flag'); - $tester->run(array('command' => 'foo'), array('decorated' => false, 'capture_stderr_separately' => true)); + $tester->run(['command' => 'foo'], ['decorated' => false, 'capture_stderr_separately' => true]); $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception1.txt', $tester->getErrorOutput(true), '->setCatchExceptions() sets the catch exception flag'); $this->assertSame('', $tester->getDisplay(true)); $application->setCatchExceptions(false); try { - $tester->run(array('command' => 'foo'), array('decorated' => false)); + $tester->run(['command' => 'foo'], ['decorated' => false]); $this->fail('->setCatchExceptions() sets the catch exception flag'); } catch (\Exception $e) { $this->assertInstanceOf('\Exception', $e, '->setCatchExceptions() sets the catch exception flag'); @@ -730,29 +730,29 @@ class ApplicationTest extends TestCase putenv('COLUMNS=120'); $tester = new ApplicationTester($application); - $tester->run(array('command' => 'foo'), array('decorated' => false, 'capture_stderr_separately' => true)); + $tester->run(['command' => 'foo'], ['decorated' => false, 'capture_stderr_separately' => true]); $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception1.txt', $tester->getErrorOutput(true), '->renderException() renders a pretty exception'); - $tester->run(array('command' => 'foo'), array('decorated' => false, 'verbosity' => Output::VERBOSITY_VERBOSE, 'capture_stderr_separately' => true)); + $tester->run(['command' => 'foo'], ['decorated' => false, 'verbosity' => Output::VERBOSITY_VERBOSE, 'capture_stderr_separately' => true]); $this->assertContains('Exception trace', $tester->getErrorOutput(), '->renderException() renders a pretty exception with a stack trace when verbosity is verbose'); - $tester->run(array('command' => 'list', '--foo' => true), array('decorated' => false, 'capture_stderr_separately' => true)); + $tester->run(['command' => 'list', '--foo' => true], ['decorated' => false, 'capture_stderr_separately' => true]); $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception2.txt', $tester->getErrorOutput(true), '->renderException() renders the command synopsis when an exception occurs in the context of a command'); $application->add(new \Foo3Command()); $tester = new ApplicationTester($application); - $tester->run(array('command' => 'foo3:bar'), array('decorated' => false, 'capture_stderr_separately' => true)); + $tester->run(['command' => 'foo3:bar'], ['decorated' => false, 'capture_stderr_separately' => true]); $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception3.txt', $tester->getErrorOutput(true), '->renderException() renders a pretty exceptions with previous exceptions'); - $tester->run(array('command' => 'foo3:bar'), array('decorated' => false, 'verbosity' => Output::VERBOSITY_VERBOSE)); + $tester->run(['command' => 'foo3:bar'], ['decorated' => false, 'verbosity' => Output::VERBOSITY_VERBOSE]); $this->assertRegExp('/\[Exception\]\s*First exception/', $tester->getDisplay(), '->renderException() renders a pretty exception without code exception when code exception is default and verbosity is verbose'); $this->assertRegExp('/\[Exception\]\s*Second exception/', $tester->getDisplay(), '->renderException() renders a pretty exception without code exception when code exception is 0 and verbosity is verbose'); $this->assertRegExp('/\[Exception \(404\)\]\s*Third exception/', $tester->getDisplay(), '->renderException() renders a pretty exception with code exception when code exception is 404 and verbosity is verbose'); - $tester->run(array('command' => 'foo3:bar'), array('decorated' => true)); + $tester->run(['command' => 'foo3:bar'], ['decorated' => true]); $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception3decorated.txt', $tester->getDisplay(true), '->renderException() renders a pretty exceptions with previous exceptions'); - $tester->run(array('command' => 'foo3:bar'), array('decorated' => true, 'capture_stderr_separately' => true)); + $tester->run(['command' => 'foo3:bar'], ['decorated' => true, 'capture_stderr_separately' => true]); $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception3decorated.txt', $tester->getErrorOutput(true), '->renderException() renders a pretty exceptions with previous exceptions'); $application = new Application(); @@ -760,7 +760,7 @@ class ApplicationTest extends TestCase putenv('COLUMNS=32'); $tester = new ApplicationTester($application); - $tester->run(array('command' => 'foo'), array('decorated' => false, 'capture_stderr_separately' => true)); + $tester->run(['command' => 'foo'], ['decorated' => false, 'capture_stderr_separately' => true]); $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception4.txt', $tester->getErrorOutput(true), '->renderException() wraps messages when they are bigger than the terminal'); putenv('COLUMNS=120'); } @@ -775,10 +775,10 @@ class ApplicationTest extends TestCase }); $tester = new ApplicationTester($application); - $tester->run(array('command' => 'foo'), array('decorated' => false, 'capture_stderr_separately' => true)); + $tester->run(['command' => 'foo'], ['decorated' => false, 'capture_stderr_separately' => true]); $this->assertStringMatchesFormatFile(self::$fixturesPath.'/application_renderexception_doublewidth1.txt', $tester->getErrorOutput(true), '->renderException() renders a pretty exceptions with previous exceptions'); - $tester->run(array('command' => 'foo'), array('decorated' => true, 'capture_stderr_separately' => true)); + $tester->run(['command' => 'foo'], ['decorated' => true, 'capture_stderr_separately' => true]); $this->assertStringMatchesFormatFile(self::$fixturesPath.'/application_renderexception_doublewidth1decorated.txt', $tester->getErrorOutput(true), '->renderException() renders a pretty exceptions with previous exceptions'); $application = new Application(); @@ -788,7 +788,7 @@ class ApplicationTest extends TestCase throw new \Exception('コマンドの実行中にエラーが発生しました。'); }); $tester = new ApplicationTester($application); - $tester->run(array('command' => 'foo'), array('decorated' => false, 'capture_stderr_separately' => true)); + $tester->run(['command' => 'foo'], ['decorated' => false, 'capture_stderr_separately' => true]); $this->assertStringMatchesFormatFile(self::$fixturesPath.'/application_renderexception_doublewidth2.txt', $tester->getErrorOutput(true), '->renderException() wraps messages when they are bigger than the terminal'); putenv('COLUMNS=120'); } @@ -803,14 +803,14 @@ class ApplicationTest extends TestCase }); $tester = new ApplicationTester($application); - $tester->run(array('command' => 'foo'), array('decorated' => false)); + $tester->run(['command' => 'foo'], ['decorated' => false]); $this->assertStringMatchesFormatFile(self::$fixturesPath.'/application_renderexception_escapeslines.txt', $tester->getDisplay(true), '->renderException() escapes lines containing formatting'); putenv('COLUMNS=120'); } public function testRenderExceptionLineBreaks() { - $application = $this->getMockBuilder('Symfony\Component\Console\Application')->setMethods(array('getTerminalWidth'))->getMock(); + $application = $this->getMockBuilder('Symfony\Component\Console\Application')->setMethods(['getTerminalWidth'])->getMock(); $application->setAutoExit(false); $application->expects($this->any()) ->method('getTerminalWidth') @@ -820,7 +820,7 @@ class ApplicationTest extends TestCase }); $tester = new ApplicationTester($application); - $tester->run(array('command' => 'foo'), array('decorated' => false)); + $tester->run(['command' => 'foo'], ['decorated' => false]); $this->assertStringMatchesFormatFile(self::$fixturesPath.'/application_renderexception_linebreaks.txt', $tester->getDisplay(true), '->renderException() keep multiple line breaks'); } @@ -834,7 +834,7 @@ class ApplicationTest extends TestCase }); $tester = new ApplicationTester($application); - $tester->run(array('command' => 'foo'), array('decorated' => false)); + $tester->run(['command' => 'foo'], ['decorated' => false]); $this->assertContains('[InvalidArgumentException@anonymous]', $tester->getDisplay(true)); $application = new Application(); @@ -845,7 +845,7 @@ class ApplicationTest extends TestCase }); $tester = new ApplicationTester($application); - $tester->run(array('command' => 'foo'), array('decorated' => false)); + $tester->run(['command' => 'foo'], ['decorated' => false]); $this->assertContains('Dummy type "@anonymous" is invalid.', $tester->getDisplay(true)); } @@ -859,7 +859,7 @@ class ApplicationTest extends TestCase }); $tester = new ApplicationTester($application); - $tester->run(array('command' => 'foo'), array('decorated' => false)); + $tester->run(['command' => 'foo'], ['decorated' => false]); $this->assertContains('[InvalidArgumentException@anonymous]', $tester->getDisplay(true)); $application = new Application(); @@ -870,7 +870,7 @@ class ApplicationTest extends TestCase }); $tester = new ApplicationTester($application); - $tester->run(array('command' => 'foo'), array('decorated' => false)); + $tester->run(['command' => 'foo'], ['decorated' => false]); $this->assertContains('Dummy type "@anonymous" is invalid.', $tester->getDisplay(true)); } @@ -880,7 +880,7 @@ class ApplicationTest extends TestCase $application->setAutoExit(false); $application->setCatchExceptions(false); $application->add($command = new \Foo1Command()); - $_SERVER['argv'] = array('cli.php', 'foo:bar1'); + $_SERVER['argv'] = ['cli.php', 'foo:bar1']; ob_start(); $application->run(); @@ -896,63 +896,63 @@ class ApplicationTest extends TestCase $this->ensureStaticCommandHelp($application); $tester = new ApplicationTester($application); - $tester->run(array(), array('decorated' => false)); + $tester->run([], ['decorated' => false]); $this->assertStringEqualsFile(self::$fixturesPath.'/application_run1.txt', $tester->getDisplay(true), '->run() runs the list command if no argument is passed'); - $tester->run(array('--help' => true), array('decorated' => false)); + $tester->run(['--help' => true], ['decorated' => false]); $this->assertStringEqualsFile(self::$fixturesPath.'/application_run2.txt', $tester->getDisplay(true), '->run() runs the help command if --help is passed'); - $tester->run(array('-h' => true), array('decorated' => false)); + $tester->run(['-h' => true], ['decorated' => false]); $this->assertStringEqualsFile(self::$fixturesPath.'/application_run2.txt', $tester->getDisplay(true), '->run() runs the help command if -h is passed'); - $tester->run(array('command' => 'list', '--help' => true), array('decorated' => false)); + $tester->run(['command' => 'list', '--help' => true], ['decorated' => false]); $this->assertStringEqualsFile(self::$fixturesPath.'/application_run3.txt', $tester->getDisplay(true), '->run() displays the help if --help is passed'); - $tester->run(array('command' => 'list', '-h' => true), array('decorated' => false)); + $tester->run(['command' => 'list', '-h' => true], ['decorated' => false]); $this->assertStringEqualsFile(self::$fixturesPath.'/application_run3.txt', $tester->getDisplay(true), '->run() displays the help if -h is passed'); - $tester->run(array('--ansi' => true)); + $tester->run(['--ansi' => true]); $this->assertTrue($tester->getOutput()->isDecorated(), '->run() forces color output if --ansi is passed'); - $tester->run(array('--no-ansi' => true)); + $tester->run(['--no-ansi' => true]); $this->assertFalse($tester->getOutput()->isDecorated(), '->run() forces color output to be disabled if --no-ansi is passed'); - $tester->run(array('--version' => true), array('decorated' => false)); + $tester->run(['--version' => true], ['decorated' => false]); $this->assertStringEqualsFile(self::$fixturesPath.'/application_run4.txt', $tester->getDisplay(true), '->run() displays the program version if --version is passed'); - $tester->run(array('-V' => true), array('decorated' => false)); + $tester->run(['-V' => true], ['decorated' => false]); $this->assertStringEqualsFile(self::$fixturesPath.'/application_run4.txt', $tester->getDisplay(true), '->run() displays the program version if -v is passed'); - $tester->run(array('command' => 'list', '--quiet' => true)); + $tester->run(['command' => 'list', '--quiet' => true]); $this->assertSame('', $tester->getDisplay(), '->run() removes all output if --quiet is passed'); $this->assertFalse($tester->getInput()->isInteractive(), '->run() sets off the interactive mode if --quiet is passed'); - $tester->run(array('command' => 'list', '-q' => true)); + $tester->run(['command' => 'list', '-q' => true]); $this->assertSame('', $tester->getDisplay(), '->run() removes all output if -q is passed'); $this->assertFalse($tester->getInput()->isInteractive(), '->run() sets off the interactive mode if -q is passed'); - $tester->run(array('command' => 'list', '--verbose' => true)); + $tester->run(['command' => 'list', '--verbose' => true]); $this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if --verbose is passed'); - $tester->run(array('command' => 'list', '--verbose' => 1)); + $tester->run(['command' => 'list', '--verbose' => 1]); $this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if --verbose=1 is passed'); - $tester->run(array('command' => 'list', '--verbose' => 2)); + $tester->run(['command' => 'list', '--verbose' => 2]); $this->assertSame(Output::VERBOSITY_VERY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to very verbose if --verbose=2 is passed'); - $tester->run(array('command' => 'list', '--verbose' => 3)); + $tester->run(['command' => 'list', '--verbose' => 3]); $this->assertSame(Output::VERBOSITY_DEBUG, $tester->getOutput()->getVerbosity(), '->run() sets the output to debug if --verbose=3 is passed'); - $tester->run(array('command' => 'list', '--verbose' => 4)); + $tester->run(['command' => 'list', '--verbose' => 4]); $this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if unknown --verbose level is passed'); - $tester->run(array('command' => 'list', '-v' => true)); + $tester->run(['command' => 'list', '-v' => true]); $this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if -v is passed'); - $tester->run(array('command' => 'list', '-vv' => true)); + $tester->run(['command' => 'list', '-vv' => true]); $this->assertSame(Output::VERBOSITY_VERY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if -v is passed'); - $tester->run(array('command' => 'list', '-vvv' => true)); + $tester->run(['command' => 'list', '-vvv' => true]); $this->assertSame(Output::VERBOSITY_DEBUG, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if -v is passed'); $application = new Application(); @@ -961,10 +961,10 @@ class ApplicationTest extends TestCase $application->add(new \FooCommand()); $tester = new ApplicationTester($application); - $tester->run(array('command' => 'foo:bar', '--no-interaction' => true), array('decorated' => false)); + $tester->run(['command' => 'foo:bar', '--no-interaction' => true], ['decorated' => false]); $this->assertSame('called'.PHP_EOL, $tester->getDisplay(), '->run() does not call interact() if --no-interaction is passed'); - $tester->run(array('command' => 'foo:bar', '-n' => true), array('decorated' => false)); + $tester->run(['command' => 'foo:bar', '-n' => true], ['decorated' => false]); $this->assertSame('called'.PHP_EOL, $tester->getDisplay(), '->run() does not call interact() if -n is passed'); } @@ -984,12 +984,12 @@ class ApplicationTest extends TestCase $output = new StreamOutput(fopen('php://memory', 'w', false)); - $input = new ArgvInput(array('cli.php', '-v', 'foo:bar')); + $input = new ArgvInput(['cli.php', '-v', 'foo:bar']); $application->run($input, $output); $this->addToAssertionCount(1); - $input = new ArgvInput(array('cli.php', '--verbose', 'foo:bar')); + $input = new ArgvInput(['cli.php', '--verbose', 'foo:bar']); $application->run($input, $output); $this->addToAssertionCount(1); @@ -999,13 +999,13 @@ class ApplicationTest extends TestCase { $exception = new \Exception('', 4); - $application = $this->getMockBuilder('Symfony\Component\Console\Application')->setMethods(array('doRun'))->getMock(); + $application = $this->getMockBuilder('Symfony\Component\Console\Application')->setMethods(['doRun'])->getMock(); $application->setAutoExit(false); $application->expects($this->once()) ->method('doRun') ->willThrowException($exception); - $exitCode = $application->run(new ArrayInput(array()), new NullOutput()); + $exitCode = $application->run(new ArrayInput([]), new NullOutput()); $this->assertSame(4, $exitCode, '->run() returns integer exit code extracted from raised exception'); } @@ -1029,7 +1029,7 @@ class ApplicationTest extends TestCase }); $tester = new ApplicationTester($application); - $tester->run(array('command' => 'test')); + $tester->run(['command' => 'test']); $this->assertTrue($passedRightValue, '-> exit code 4 was passed in the console.terminate event'); } @@ -1038,13 +1038,13 @@ class ApplicationTest extends TestCase { $exception = new \Exception('', 0); - $application = $this->getMockBuilder('Symfony\Component\Console\Application')->setMethods(array('doRun'))->getMock(); + $application = $this->getMockBuilder('Symfony\Component\Console\Application')->setMethods(['doRun'])->getMock(); $application->setAutoExit(false); $application->expects($this->once()) ->method('doRun') ->willThrowException($exception); - $exitCode = $application->run(new ArrayInput(array()), new NullOutput()); + $exitCode = $application->run(new ArrayInput([]), new NullOutput()); $this->assertSame(1, $exitCode, '->run() returns exit code 1 when exception code is 0'); } @@ -1068,7 +1068,7 @@ class ApplicationTest extends TestCase }); $tester = new ApplicationTester($application); - $tester->run(array('command' => 'test')); + $tester->run(['command' => 'test']); $this->assertTrue($passedRightValue, '-> exit code 1 was passed in the console.terminate event'); } @@ -1089,12 +1089,12 @@ class ApplicationTest extends TestCase $application ->register('foo') - ->setAliases(array('f')) - ->setDefinition(array(new InputOption('survey', 'e', InputOption::VALUE_REQUIRED, 'My option with a shortcut.'))) + ->setAliases(['f']) + ->setDefinition([new InputOption('survey', 'e', InputOption::VALUE_REQUIRED, 'My option with a shortcut.')]) ->setCode(function (InputInterface $input, OutputInterface $output) {}) ; - $input = new ArrayInput(array('command' => 'foo')); + $input = new ArrayInput(['command' => 'foo']); $output = new NullOutput(); $application->run($input, $output); @@ -1111,22 +1111,22 @@ class ApplicationTest extends TestCase $application->setCatchExceptions(false); $application ->register('foo') - ->setDefinition(array($def)) + ->setDefinition([$def]) ->setCode(function (InputInterface $input, OutputInterface $output) {}) ; - $input = new ArrayInput(array('command' => 'foo')); + $input = new ArrayInput(['command' => 'foo']); $output = new NullOutput(); $application->run($input, $output); } public function getAddingAlreadySetDefinitionElementData() { - return array( - array(new InputArgument('command', InputArgument::REQUIRED)), - array(new InputOption('quiet', '', InputOption::VALUE_NONE)), - array(new InputOption('query', 'q', InputOption::VALUE_NONE)), - ); + return [ + [new InputArgument('command', InputArgument::REQUIRED)], + [new InputOption('quiet', '', InputOption::VALUE_NONE)], + [new InputOption('query', 'q', InputOption::VALUE_NONE)], + ]; } public function testGetDefaultHelperSetReturnsDefaultValues() @@ -1146,7 +1146,7 @@ class ApplicationTest extends TestCase $application->setAutoExit(false); $application->setCatchExceptions(false); - $application->setHelperSet(new HelperSet(array(new FormatterHelper()))); + $application->setHelperSet(new HelperSet([new FormatterHelper()])); $helperSet = $application->getHelperSet(); @@ -1163,7 +1163,7 @@ class ApplicationTest extends TestCase $application->setAutoExit(false); $application->setCatchExceptions(false); - $application->setHelperSet(new HelperSet(array(new FormatterHelper()))); + $application->setHelperSet(new HelperSet([new FormatterHelper()])); $helperSet = $application->getHelperSet(); @@ -1221,7 +1221,7 @@ class ApplicationTest extends TestCase $application->setAutoExit(false); $application->setCatchExceptions(false); - $application->setDefinition(new InputDefinition(array(new InputOption('--custom', '-c', InputOption::VALUE_NONE, 'Set the custom input definition.')))); + $application->setDefinition(new InputDefinition([new InputOption('--custom', '-c', InputOption::VALUE_NONE, 'Set the custom input definition.')])); $inputDefinition = $application->getDefinition(); @@ -1250,7 +1250,7 @@ class ApplicationTest extends TestCase }); $tester = new ApplicationTester($application); - $tester->run(array('command' => 'foo')); + $tester->run(['command' => 'foo']); $this->assertEquals('before.foo.after.'.PHP_EOL, $tester->getDisplay()); } @@ -1270,7 +1270,7 @@ class ApplicationTest extends TestCase }); $tester = new ApplicationTester($application); - $tester->run(array('command' => 'foo')); + $tester->run(['command' => 'foo']); } public function testRunDispatchesAllEventsWithException() @@ -1286,7 +1286,7 @@ class ApplicationTest extends TestCase }); $tester = new ApplicationTester($application); - $tester->run(array('command' => 'foo')); + $tester->run(['command' => 'foo']); $this->assertContains('before.foo.error.after.', $tester->getDisplay()); } @@ -1306,7 +1306,7 @@ class ApplicationTest extends TestCase }); $tester = new ApplicationTester($application); - $tester->run(array('command' => 'foo')); + $tester->run(['command' => 'foo']); $this->assertContains('before.error.after.', $tester->getDisplay()); } @@ -1325,7 +1325,7 @@ class ApplicationTest extends TestCase $tester = new ApplicationTester($application); try { - $tester->run(array('command' => 'dym')); + $tester->run(['command' => 'dym']); $this->fail('Error expected.'); } catch (\Error $e) { $this->assertSame('dymerr', $e->getMessage()); @@ -1354,7 +1354,7 @@ class ApplicationTest extends TestCase }); $tester = new ApplicationTester($application); - $tester->run(array('command' => 'foo')); + $tester->run(['command' => 'foo']); $this->assertContains('before.error.silenced.after.', $tester->getDisplay()); $this->assertEquals(ConsoleCommandEvent::RETURN_CODE_DISABLED, $tester->getStatusCode()); } @@ -1373,7 +1373,7 @@ class ApplicationTest extends TestCase $application->setAutoExit(false); $tester = new ApplicationTester($application); - $tester->run(array('command' => 'unknown')); + $tester->run(['command' => 'unknown']); $this->assertContains('silenced command not found', $tester->getDisplay()); $this->assertEquals(1, $tester->getStatusCode()); } @@ -1392,7 +1392,7 @@ class ApplicationTest extends TestCase $tester = new ApplicationTester($application); try { - $tester->run(array('command' => 'dym')); + $tester->run(['command' => 'dym']); $this->fail('->run() should rethrow PHP errors if not handled via ConsoleErrorEvent.'); } catch (\Error $e) { $this->assertSame($e->getMessage(), 'Class \'UnknownClass\' not found'); @@ -1417,7 +1417,7 @@ class ApplicationTest extends TestCase }); $tester = new ApplicationTester($application); - $tester->run(array('command' => 'dym')); + $tester->run(['command' => 'dym']); $this->assertContains('before.dym.error.after.', $tester->getDisplay(), 'The PHP Error did not dispached events'); } @@ -1434,7 +1434,7 @@ class ApplicationTest extends TestCase }); $tester = new ApplicationTester($application); - $tester->run(array('command' => 'dym')); + $tester->run(['command' => 'dym']); $this->assertContains('before.dym.error.after.', $tester->getDisplay(), 'The PHP Error did not dispached events'); } @@ -1451,7 +1451,7 @@ class ApplicationTest extends TestCase }); $tester = new ApplicationTester($application); - $tester->run(array('command' => 'dus')); + $tester->run(['command' => 'dus']); $this->assertSame(1, $tester->getStatusCode(), 'Status code should be 1'); } @@ -1466,7 +1466,7 @@ class ApplicationTest extends TestCase }); $tester = new ApplicationTester($application); - $exitCode = $tester->run(array('command' => 'foo')); + $exitCode = $tester->run(['command' => 'foo']); $this->assertContains('before.after.', $tester->getDisplay()); $this->assertEquals(ConsoleCommandEvent::RETURN_CODE_DISABLED, $exitCode); } @@ -1493,7 +1493,7 @@ class ApplicationTest extends TestCase }); $tester = new ApplicationTester($application); - $tester->run(array('command' => 'foo', '--no-interaction' => true)); + $tester->run(['command' => 'foo', '--no-interaction' => true]); $this->assertTrue($noInteractionValue); $this->assertFalse($quietValue); @@ -1523,7 +1523,7 @@ class ApplicationTest extends TestCase }); $tester = new ApplicationTester($application); - $tester->run(array('command' => 'foo', '--extra' => 'some test value')); + $tester->run(['command' => 'foo', '--extra' => 'some test value']); $this->assertEquals('some test value', $extraValue); } @@ -1538,14 +1538,14 @@ class ApplicationTest extends TestCase $application->setDefaultCommand($command->getName()); $tester = new ApplicationTester($application); - $tester->run(array(), array('interactive' => false)); + $tester->run([], ['interactive' => false]); $this->assertEquals('called'.PHP_EOL, $tester->getDisplay(), 'Application runs the default set command if different from \'list\' command'); $application = new CustomDefaultCommandApplication(); $application->setAutoExit(false); $tester = new ApplicationTester($application); - $tester->run(array(), array('interactive' => false)); + $tester->run([], ['interactive' => false]); $this->assertEquals('called'.PHP_EOL, $tester->getDisplay(), 'Application runs the default set command if different from \'list\' command'); } @@ -1560,7 +1560,7 @@ class ApplicationTest extends TestCase $application->setDefaultCommand($command->getName()); $tester = new ApplicationTester($application); - $tester->run(array('--fooopt' => 'opt'), array('interactive' => false)); + $tester->run(['--fooopt' => 'opt'], ['interactive' => false]); $this->assertEquals('called'.PHP_EOL.'opt'.PHP_EOL, $tester->getDisplay(), 'Application runs the default set command if different from \'list\' command'); } @@ -1576,10 +1576,10 @@ class ApplicationTest extends TestCase $tester = new ApplicationTester($application); - $tester->run(array()); + $tester->run([]); $this->assertContains('called', $tester->getDisplay()); - $tester->run(array('--help' => true)); + $tester->run(['--help' => true]); $this->assertContains('The foo:bar command', $tester->getDisplay()); } @@ -1592,9 +1592,9 @@ class ApplicationTest extends TestCase $application->setAutoExit(false); $tester = new ApplicationTester($application); - $tester->run(array('command' => 'help')); + $tester->run(['command' => 'help']); - $this->assertFalse($tester->getInput()->hasParameterOption(array('--no-interaction', '-n'))); + $this->assertFalse($tester->getInput()->hasParameterOption(['--no-interaction', '-n'])); $inputStream = $tester->getInput()->getStream(); $this->assertEquals($tester->getInput()->isInteractive(), @posix_isatty($inputStream)); @@ -1606,9 +1606,9 @@ class ApplicationTest extends TestCase $container->addCompilerPass(new AddConsoleCommandPass()); $container ->register('lazy-command', LazyCommand::class) - ->addTag('console.command', array('command' => 'lazy:command')) - ->addTag('console.command', array('command' => 'lazy:alias')) - ->addTag('console.command', array('command' => 'lazy:alias2')); + ->addTag('console.command', ['command' => 'lazy:command']) + ->addTag('console.command', ['command' => 'lazy:alias']) + ->addTag('console.command', ['command' => 'lazy:alias2']); $container->compile(); $application = new Application(); @@ -1617,17 +1617,17 @@ class ApplicationTest extends TestCase $tester = new ApplicationTester($application); - $tester->run(array('command' => 'lazy:command')); + $tester->run(['command' => 'lazy:command']); $this->assertSame("lazy-command called\n", $tester->getDisplay(true)); - $tester->run(array('command' => 'lazy:alias')); + $tester->run(['command' => 'lazy:alias']); $this->assertSame("lazy-command called\n", $tester->getDisplay(true)); - $tester->run(array('command' => 'lazy:alias2')); + $tester->run(['command' => 'lazy:alias2']); $this->assertSame("lazy-command called\n", $tester->getDisplay(true)); $command = $application->get('lazy:command'); - $this->assertSame(array('lazy:alias', 'lazy:alias2'), $command->getAliases()); + $this->assertSame(['lazy:alias', 'lazy:alias2'], $command->getAliases()); } /** @@ -1636,21 +1636,21 @@ class ApplicationTest extends TestCase public function testGetDisabledLazyCommand() { $application = new Application(); - $application->setCommandLoader(new FactoryCommandLoader(array('disabled' => function () { return new DisabledCommand(); }))); + $application->setCommandLoader(new FactoryCommandLoader(['disabled' => function () { return new DisabledCommand(); }])); $application->get('disabled'); } public function testHasReturnsFalseForDisabledLazyCommand() { $application = new Application(); - $application->setCommandLoader(new FactoryCommandLoader(array('disabled' => function () { return new DisabledCommand(); }))); + $application->setCommandLoader(new FactoryCommandLoader(['disabled' => function () { return new DisabledCommand(); }])); $this->assertFalse($application->has('disabled')); } public function testAllExcludesDisabledLazyCommand() { $application = new Application(); - $application->setCommandLoader(new FactoryCommandLoader(array('disabled' => function () { return new DisabledCommand(); }))); + $application->setCommandLoader(new FactoryCommandLoader(['disabled' => function () { return new DisabledCommand(); }])); $this->assertArrayNotHasKey('disabled', $application->all()); } @@ -1693,7 +1693,7 @@ class ApplicationTest extends TestCase $tester = new ApplicationTester($application); try { - $tester->run(array('command' => 'dym')); + $tester->run(['command' => 'dym']); $this->fail('->run() should rethrow PHP errors if not handled via ConsoleErrorEvent.'); } catch (\Error $e) { $this->assertSame($e->getMessage(), 'Class \'UnknownClass\' not found'); @@ -1725,7 +1725,7 @@ class ApplicationTest extends TestCase }); $tester = new ApplicationTester($application); - $tester->run(array('command' => 'foo')); + $tester->run(['command' => 'foo']); } protected function tearDown() @@ -1745,7 +1745,7 @@ class CustomApplication extends Application */ protected function getDefaultInputDefinition() { - return new InputDefinition(array(new InputOption('--custom', '-c', InputOption::VALUE_NONE, 'Set the custom input definition.'))); + return new InputDefinition([new InputOption('--custom', '-c', InputOption::VALUE_NONE, 'Set the custom input definition.')]); } /** @@ -1755,7 +1755,7 @@ class CustomApplication extends Application */ protected function getDefaultHelperSet() { - return new HelperSet(array(new FormatterHelper())); + return new HelperSet([new FormatterHelper()]); } } diff --git a/src/Symfony/Component/Console/Tests/Helper/ProcessHelperTest.php b/src/Symfony/Component/Console/Tests/Helper/ProcessHelperTest.php index 829bc43307..5387a9e3c2 100644 --- a/src/Symfony/Component/Console/Tests/Helper/ProcessHelperTest.php +++ b/src/Symfony/Component/Console/Tests/Helper/ProcessHelperTest.php @@ -30,7 +30,7 @@ class ProcessHelperTest extends TestCase } $helper = new ProcessHelper(); - $helper->setHelperSet(new HelperSet(array(new DebugFormatterHelper()))); + $helper->setHelperSet(new HelperSet([new DebugFormatterHelper()])); $output = $this->getOutputStream($verbosity); $helper->run($output, $cmd, $error); $this->assertEquals($expected, $this->getOutput($output)); @@ -39,13 +39,13 @@ class ProcessHelperTest extends TestCase public function testPassedCallbackIsExecuted() { $helper = new ProcessHelper(); - $helper->setHelperSet(new HelperSet(array(new DebugFormatterHelper()))); + $helper->setHelperSet(new HelperSet([new DebugFormatterHelper()])); $output = $this->getOutputStream(StreamOutput::VERBOSITY_NORMAL); $executed = false; $callback = function () use (&$executed) { $executed = true; }; - $helper->run($output, array('php', '-r', 'echo 42;'), null, $callback); + $helper->run($output, ['php', '-r', 'echo 42;'], null, $callback); $this->assertTrue($executed); } @@ -96,27 +96,27 @@ EOT; EOT; $errorMessage = 'An error occurred'; - $args = new Process(array('php', '-r', 'echo 42;')); + $args = new Process(['php', '-r', 'echo 42;']); $args = $args->getCommandLine(); $successOutputProcessDebug = str_replace("'php' '-r' 'echo 42;'", $args, $successOutputProcessDebug); - $fromShellCommandline = \method_exists(Process::class, 'fromShellCommandline') ? array(Process::class, 'fromShellCommandline') : function ($cmd) { return new Process($cmd); }; + $fromShellCommandline = \method_exists(Process::class, 'fromShellCommandline') ? [Process::class, 'fromShellCommandline'] : function ($cmd) { return new Process($cmd); }; - return array( - array('', 'php -r "echo 42;"', StreamOutput::VERBOSITY_VERBOSE, null), - array($successOutputVerbose, 'php -r "echo 42;"', StreamOutput::VERBOSITY_VERY_VERBOSE, null), - array($successOutputDebug, 'php -r "echo 42;"', StreamOutput::VERBOSITY_DEBUG, null), - array($successOutputDebugWithTags, 'php -r "echo \'42\';"', StreamOutput::VERBOSITY_DEBUG, null), - array('', 'php -r "syntax error"', StreamOutput::VERBOSITY_VERBOSE, null), - array($syntaxErrorOutputVerbose, 'php -r "fwrite(STDERR, \'error message\');usleep(50000);fwrite(STDOUT, \'out message\');exit(252);"', StreamOutput::VERBOSITY_VERY_VERBOSE, null), - array($syntaxErrorOutputDebug, 'php -r "fwrite(STDERR, \'error message\');usleep(500000);fwrite(STDOUT, \'out message\');exit(252);"', StreamOutput::VERBOSITY_DEBUG, null), - array($errorMessage.PHP_EOL, 'php -r "fwrite(STDERR, \'error message\');usleep(50000);fwrite(STDOUT, \'out message\');exit(252);"', StreamOutput::VERBOSITY_VERBOSE, $errorMessage), - array($syntaxErrorOutputVerbose.$errorMessage.PHP_EOL, 'php -r "fwrite(STDERR, \'error message\');usleep(50000);fwrite(STDOUT, \'out message\');exit(252);"', StreamOutput::VERBOSITY_VERY_VERBOSE, $errorMessage), - array($syntaxErrorOutputDebug.$errorMessage.PHP_EOL, 'php -r "fwrite(STDERR, \'error message\');usleep(500000);fwrite(STDOUT, \'out message\');exit(252);"', StreamOutput::VERBOSITY_DEBUG, $errorMessage), - array($successOutputProcessDebug, array('php', '-r', 'echo 42;'), StreamOutput::VERBOSITY_DEBUG, null), - array($successOutputDebug, $fromShellCommandline('php -r "echo 42;"'), StreamOutput::VERBOSITY_DEBUG, null), - array($successOutputProcessDebug, array(new Process(array('php', '-r', 'echo 42;'))), StreamOutput::VERBOSITY_DEBUG, null), - array($successOutputPhp, array($fromShellCommandline('php -r '.$PHP), 'PHP' => 'echo 42;'), StreamOutput::VERBOSITY_DEBUG, null), - ); + return [ + ['', 'php -r "echo 42;"', StreamOutput::VERBOSITY_VERBOSE, null], + [$successOutputVerbose, 'php -r "echo 42;"', StreamOutput::VERBOSITY_VERY_VERBOSE, null], + [$successOutputDebug, 'php -r "echo 42;"', StreamOutput::VERBOSITY_DEBUG, null], + [$successOutputDebugWithTags, 'php -r "echo \'42\';"', StreamOutput::VERBOSITY_DEBUG, null], + ['', 'php -r "syntax error"', StreamOutput::VERBOSITY_VERBOSE, null], + [$syntaxErrorOutputVerbose, 'php -r "fwrite(STDERR, \'error message\');usleep(50000);fwrite(STDOUT, \'out message\');exit(252);"', StreamOutput::VERBOSITY_VERY_VERBOSE, null], + [$syntaxErrorOutputDebug, 'php -r "fwrite(STDERR, \'error message\');usleep(500000);fwrite(STDOUT, \'out message\');exit(252);"', StreamOutput::VERBOSITY_DEBUG, null], + [$errorMessage.PHP_EOL, 'php -r "fwrite(STDERR, \'error message\');usleep(50000);fwrite(STDOUT, \'out message\');exit(252);"', StreamOutput::VERBOSITY_VERBOSE, $errorMessage], + [$syntaxErrorOutputVerbose.$errorMessage.PHP_EOL, 'php -r "fwrite(STDERR, \'error message\');usleep(50000);fwrite(STDOUT, \'out message\');exit(252);"', StreamOutput::VERBOSITY_VERY_VERBOSE, $errorMessage], + [$syntaxErrorOutputDebug.$errorMessage.PHP_EOL, 'php -r "fwrite(STDERR, \'error message\');usleep(500000);fwrite(STDOUT, \'out message\');exit(252);"', StreamOutput::VERBOSITY_DEBUG, $errorMessage], + [$successOutputProcessDebug, ['php', '-r', 'echo 42;'], StreamOutput::VERBOSITY_DEBUG, null], + [$successOutputDebug, $fromShellCommandline('php -r "echo 42;"'), StreamOutput::VERBOSITY_DEBUG, null], + [$successOutputProcessDebug, [new Process(['php', '-r', 'echo 42;'])], StreamOutput::VERBOSITY_DEBUG, null], + [$successOutputPhp, [$fromShellCommandline('php -r '.$PHP), 'PHP' => 'echo 42;'], StreamOutput::VERBOSITY_DEBUG, null], + ]; } private function getOutputStream($verbosity) diff --git a/src/Symfony/Component/Console/Tests/Helper/TableTest.php b/src/Symfony/Component/Console/Tests/Helper/TableTest.php index a74fe5ea6f..43b90fd073 100644 --- a/src/Symfony/Component/Console/Tests/Helper/TableTest.php +++ b/src/Symfony/Component/Console/Tests/Helper/TableTest.php @@ -982,13 +982,13 @@ TABLE; (new Table($output = $this->getOutputStream())) ->setHeaderTitle($headerTitle) ->setFooterTitle($footerTitle) - ->setHeaders(array('ISBN', 'Title', 'Author')) - ->setRows(array( - array('99921-58-10-7', 'Divine Comedy', 'Dante Alighieri'), - array('9971-5-0210-0', 'A Tale of Two Cities', 'Charles Dickens'), - array('960-425-059-0', 'The Lord of the Rings', 'J. R. R. Tolkien'), - array('80-902734-1-6', 'And Then There Were None', 'Agatha Christie'), - )) + ->setHeaders(['ISBN', 'Title', 'Author']) + ->setRows([ + ['99921-58-10-7', 'Divine Comedy', 'Dante Alighieri'], + ['9971-5-0210-0', 'A Tale of Two Cities', 'Charles Dickens'], + ['960-425-059-0', 'The Lord of the Rings', 'J. R. R. Tolkien'], + ['80-902734-1-6', 'And Then There Were None', 'Agatha Christie'], + ]) ->setStyle($style) ->render() ; @@ -998,8 +998,8 @@ TABLE; public function renderSetTitle() { - return array( - array( + return [ + [ 'Books', 'Page 1/2', 'default', @@ -1014,8 +1014,8 @@ TABLE; +---------------+--------- Page 1/2 -------+------------------+ TABLE - ), - array( + ], + [ 'Books', 'Page 1/2', 'box', @@ -1030,8 +1030,8 @@ TABLE └───────────────┴───────── Page 1/2 ───────┴──────────────────┘ TABLE - ), - array( + ], + [ 'Boooooooooooooooooooooooooooooooooooooooooooooooooooooooks', 'Page 1/999999999999999999999999999999999999999999999999999', 'default', @@ -1046,17 +1046,17 @@ TABLE +- Page 1/99999999999999999999999999999999999999999999999... -+ TABLE - ), - ); + ], + ]; } public function testColumnMaxWidths() { $table = new Table($output = $this->getOutputStream()); $table - ->setRows(array( - array('Divine Comedy', 'A Tale of Two Cities', 'The Lord of the Rings', 'And Then There Were None'), - )) + ->setRows([ + ['Divine Comedy', 'A Tale of Two Cities', 'The Lord of the Rings', 'And Then There Were None'], + ]) ->setColumnMaxWidth(1, 5) ->setColumnMaxWidth(2, 10) ->setColumnMaxWidth(3, 15); diff --git a/src/Symfony/Component/Console/Tests/Tester/ApplicationTesterTest.php b/src/Symfony/Component/Console/Tests/Tester/ApplicationTesterTest.php index 53fbaf855f..7522731535 100644 --- a/src/Symfony/Component/Console/Tests/Tester/ApplicationTesterTest.php +++ b/src/Symfony/Component/Console/Tests/Tester/ApplicationTesterTest.php @@ -104,8 +104,8 @@ class ApplicationTesterTest extends TestCase $tester = new ApplicationTester($application); $tester->run( - array('command' => 'foo', 'foo' => 'bar'), - array('capture_stderr_separately' => true) + ['command' => 'foo', 'foo' => 'bar'], + ['capture_stderr_separately' => true] ); $this->assertSame('foo', $tester->getErrorOutput()); diff --git a/src/Symfony/Component/Console/Tests/Tester/CommandTesterTest.php b/src/Symfony/Component/Console/Tests/Tester/CommandTesterTest.php index 4a0e8afbc8..6d9b7417d6 100644 --- a/src/Symfony/Component/Console/Tests/Tester/CommandTesterTest.php +++ b/src/Symfony/Component/Console/Tests/Tester/CommandTesterTest.php @@ -198,8 +198,8 @@ class CommandTesterTest extends TestCase $tester = new CommandTester($command); $tester->execute( - array('foo' => 'bar'), - array('capture_stderr_separately' => true) + ['foo' => 'bar'], + ['capture_stderr_separately' => true] ); $this->assertSame('foo', $tester->getErrorOutput()); diff --git a/src/Symfony/Component/Debug/DebugClassLoader.php b/src/Symfony/Component/Debug/DebugClassLoader.php index 8b5e542076..027c9a4775 100644 --- a/src/Symfony/Component/Debug/DebugClassLoader.php +++ b/src/Symfony/Component/Debug/DebugClassLoader.php @@ -29,16 +29,16 @@ class DebugClassLoader { private $classLoader; private $isFinder; - private $loaded = array(); + private $loaded = []; private static $caseCheck; - private static $checkedClasses = array(); - private static $final = array(); - private static $finalMethods = array(); - private static $deprecated = array(); - private static $internal = array(); - private static $internalMethods = array(); - private static $annotatedParameters = array(); - private static $darwinCache = array('/' => array('/', array())); + private static $checkedClasses = []; + private static $final = []; + private static $finalMethods = []; + private static $deprecated = []; + private static $internal = []; + private static $internalMethods = []; + private static $annotatedParameters = []; + private static $darwinCache = ['/' => ['/', []]]; public function __construct(callable $classLoader) { @@ -98,7 +98,7 @@ class DebugClassLoader foreach ($functions as $function) { if (!\is_array($function) || !$function[0] instanceof self) { - $function = array(new static($function), 'loadClass'); + $function = [new static($function), 'loadClass']; } spl_autoload_register($function); @@ -219,7 +219,7 @@ class DebugClassLoader public function checkAnnotations(\ReflectionClass $refl, $class) { - $deprecations = array(); + $deprecations = []; // Don't trigger deprecations for classes in the same vendor if (2 > $len = 1 + (\strpos($class, '\\') ?: \strpos($class, '_'))) { @@ -231,7 +231,7 @@ class DebugClassLoader // Detect annotations on the class if (false !== $doc = $refl->getDocComment()) { - foreach (array('final', 'deprecated', 'internal') as $annotation) { + foreach (['final', 'deprecated', 'internal'] as $annotation) { if (false !== \strpos($doc, $annotation) && preg_match('#\n \* @'.$annotation.'(?:( .+?)\.?)?\r?\n \*(?: @|/$)#s', $doc, $notice)) { self::${$annotation}[$class] = isset($notice[1]) ? preg_replace('#\s*\r?\n \* +#', ' ', $notice[1]) : ''; } @@ -273,11 +273,11 @@ class DebugClassLoader } // Inherit @final, @internal and @param annotations for methods - self::$finalMethods[$class] = array(); - self::$internalMethods[$class] = array(); - self::$annotatedParameters[$class] = array(); + self::$finalMethods[$class] = []; + self::$internalMethods[$class] = []; + self::$annotatedParameters[$class] = []; foreach ($parentAndOwnInterfaces as $use) { - foreach (array('finalMethods', 'internalMethods', 'annotatedParameters') as $property) { + foreach (['finalMethods', 'internalMethods', 'annotatedParameters'] as $property) { if (isset(self::${$property}[$use])) { self::${$property}[$class] = self::${$property}[$class] ? self::${$property}[$use] + self::${$property}[$class] : self::${$property}[$use]; } @@ -305,7 +305,7 @@ class DebugClassLoader $doc = $method->getDocComment(); if (isset(self::$annotatedParameters[$class][$method->name])) { - $definedParameters = array(); + $definedParameters = []; foreach ($method->getParameters() as $parameter) { $definedParameters[$parameter->name] = true; } @@ -323,10 +323,10 @@ class DebugClassLoader $finalOrInternal = false; - foreach (array('final', 'internal') as $annotation) { + foreach (['final', 'internal'] as $annotation) { if (false !== \strpos($doc, $annotation) && preg_match('#\n\s+\* @'.$annotation.'(?:( .+?)\.?)?\r?\n\s+\*(?: @|/$)#s', $doc, $notice)) { $message = isset($notice[1]) ? preg_replace('#\s*\r?\n \* +#', ' ', $notice[1]) : ''; - self::${$annotation.'Methods'}[$class][$method->name] = array($class, $message); + self::${$annotation.'Methods'}[$class][$method->name] = [$class, $message]; $finalOrInternal = true; } } @@ -338,7 +338,7 @@ class DebugClassLoader continue; } if (!isset(self::$annotatedParameters[$class][$method->name])) { - $definedParameters = array(); + $definedParameters = []; foreach ($method->getParameters() as $parameter) { $definedParameters[$parameter->name] = true; } @@ -384,7 +384,7 @@ class DebugClassLoader if (0 === substr_compare($real, $tail, -$tailLen, $tailLen, true) && 0 !== substr_compare($real, $tail, -$tailLen, $tailLen, false) ) { - return array(substr($tail, -$tailLen + 1), substr($real, -$tailLen + 1), substr($real, 0, -$tailLen + 1)); + return [substr($tail, -$tailLen + 1), substr($real, -$tailLen + 1), substr($real, 0, -$tailLen + 1)]; } } @@ -414,7 +414,7 @@ class DebugClassLoader $k = $kDir; $i = \strlen($dir) - 1; while (!isset(self::$darwinCache[$k])) { - self::$darwinCache[$k] = array($dir, array()); + self::$darwinCache[$k] = [$dir, []]; self::$darwinCache[$dir] = &self::$darwinCache[$k]; while ('/' !== $dir[--$i]) { diff --git a/src/Symfony/Component/Debug/ErrorHandler.php b/src/Symfony/Component/Debug/ErrorHandler.php index 2eb058ebe1..efbfa5bcaa 100644 --- a/src/Symfony/Component/Debug/ErrorHandler.php +++ b/src/Symfony/Component/Debug/ErrorHandler.php @@ -48,7 +48,7 @@ use Symfony\Component\Debug\FatalErrorHandler\UndefinedMethodFatalErrorHandler; */ class ErrorHandler { - private $levels = array( + private $levels = [ E_DEPRECATED => 'Deprecated', E_USER_DEPRECATED => 'User Deprecated', E_NOTICE => 'Notice', @@ -64,25 +64,25 @@ class ErrorHandler E_PARSE => 'Parse Error', E_ERROR => 'Error', E_CORE_ERROR => 'Core Error', - ); + ]; - private $loggers = array( - E_DEPRECATED => array(null, LogLevel::INFO), - E_USER_DEPRECATED => array(null, LogLevel::INFO), - E_NOTICE => array(null, LogLevel::WARNING), - E_USER_NOTICE => array(null, LogLevel::WARNING), - E_STRICT => array(null, LogLevel::WARNING), - E_WARNING => array(null, LogLevel::WARNING), - E_USER_WARNING => array(null, LogLevel::WARNING), - E_COMPILE_WARNING => array(null, LogLevel::WARNING), - E_CORE_WARNING => array(null, LogLevel::WARNING), - E_USER_ERROR => array(null, LogLevel::CRITICAL), - E_RECOVERABLE_ERROR => array(null, LogLevel::CRITICAL), - E_COMPILE_ERROR => array(null, LogLevel::CRITICAL), - E_PARSE => array(null, LogLevel::CRITICAL), - E_ERROR => array(null, LogLevel::CRITICAL), - E_CORE_ERROR => array(null, LogLevel::CRITICAL), - ); + private $loggers = [ + E_DEPRECATED => [null, LogLevel::INFO], + E_USER_DEPRECATED => [null, LogLevel::INFO], + E_NOTICE => [null, LogLevel::WARNING], + E_USER_NOTICE => [null, LogLevel::WARNING], + E_STRICT => [null, LogLevel::WARNING], + E_WARNING => [null, LogLevel::WARNING], + E_USER_WARNING => [null, LogLevel::WARNING], + E_COMPILE_WARNING => [null, LogLevel::WARNING], + E_CORE_WARNING => [null, LogLevel::WARNING], + E_USER_ERROR => [null, LogLevel::CRITICAL], + E_RECOVERABLE_ERROR => [null, LogLevel::CRITICAL], + E_COMPILE_ERROR => [null, LogLevel::CRITICAL], + E_PARSE => [null, LogLevel::CRITICAL], + E_ERROR => [null, LogLevel::CRITICAL], + E_CORE_ERROR => [null, LogLevel::CRITICAL], + ]; private $thrownErrors = 0x1FFF; // E_ALL - E_DEPRECATED - E_USER_DEPRECATED private $scopedErrors = 0x1FFF; // E_ALL - E_DEPRECATED - E_USER_DEPRECATED @@ -98,7 +98,7 @@ class ErrorHandler private static $reservedMemory; private static $toStringException = null; - private static $silencedErrorCache = array(); + private static $silencedErrorCache = []; private static $silencedErrorCount = 0; private static $exitCode = 0; @@ -121,10 +121,10 @@ class ErrorHandler $handler = new static(); } - if (null === $prev = set_error_handler(array($handler, 'handleError'))) { + if (null === $prev = set_error_handler([$handler, 'handleError'])) { restore_error_handler(); // Specifying the error types earlier would expose us to https://bugs.php.net/63206 - set_error_handler(array($handler, 'handleError'), $handler->thrownErrors | $handler->loggedErrors); + set_error_handler([$handler, 'handleError'], $handler->thrownErrors | $handler->loggedErrors); $handler->isRoot = true; } @@ -138,12 +138,12 @@ class ErrorHandler } else { $handlerIsRegistered = true; } - if (\is_array($prev = set_exception_handler(array($handler, 'handleException'))) && $prev[0] instanceof self) { + if (\is_array($prev = set_exception_handler([$handler, 'handleException'])) && $prev[0] instanceof self) { restore_exception_handler(); if (!$handlerIsRegistered) { $handler = $prev[0]; } elseif ($handler !== $prev[0] && $replace) { - set_exception_handler(array($handler, 'handleException')); + set_exception_handler([$handler, 'handleException']); $p = $prev[0]->setExceptionHandler(null); $handler->setExceptionHandler($p); $prev[0]->setExceptionHandler($p); @@ -176,12 +176,12 @@ class ErrorHandler */ public function setDefaultLogger(LoggerInterface $logger, $levels = E_ALL, $replace = false) { - $loggers = array(); + $loggers = []; if (\is_array($levels)) { foreach ($levels as $type => $logLevel) { if (empty($this->loggers[$type][0]) || $replace || $this->loggers[$type][0] === $this->bootstrappingLogger) { - $loggers[$type] = array($logger, $logLevel); + $loggers[$type] = [$logger, $logLevel]; } } } else { @@ -212,14 +212,14 @@ class ErrorHandler { $prevLogged = $this->loggedErrors; $prev = $this->loggers; - $flush = array(); + $flush = []; foreach ($loggers as $type => $log) { if (!isset($prev[$type])) { throw new \InvalidArgumentException('Unknown error type: '.$type); } if (!\is_array($log)) { - $log = array($log); + $log = [$log]; } elseif (!array_key_exists(0, $log)) { throw new \InvalidArgumentException('No logger provided'); } @@ -356,9 +356,9 @@ class ErrorHandler if ($handler === $this) { restore_error_handler(); if ($this->isRoot) { - set_error_handler(array($this, 'handleError'), $this->thrownErrors | $this->loggedErrors); + set_error_handler([$this, 'handleError'], $this->thrownErrors | $this->loggedErrors); } else { - set_error_handler(array($this, 'handleError')); + set_error_handler([$this, 'handleError']); } } } @@ -395,9 +395,9 @@ class ErrorHandler $scope = $this->scopedErrors & $type; if (4 < $numArgs = \func_num_args()) { - $context = $scope ? (func_get_arg(4) ?: array()) : array(); + $context = $scope ? (func_get_arg(4) ?: []) : []; } else { - $context = array(); + $context = []; } if (isset($context['GLOBALS']) && $scope) { @@ -417,19 +417,19 @@ class ErrorHandler self::$toStringException = null; } elseif (!$throw && !($type & $level)) { if (!isset(self::$silencedErrorCache[$id = $file.':'.$line])) { - $lightTrace = $this->tracedErrors & $type ? $this->cleanTrace(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 5), $type, $file, $line, false) : array(); - $errorAsException = new SilencedErrorContext($type, $file, $line, isset($lightTrace[1]) ? array($lightTrace[0]) : $lightTrace); + $lightTrace = $this->tracedErrors & $type ? $this->cleanTrace(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 5), $type, $file, $line, false) : []; + $errorAsException = new SilencedErrorContext($type, $file, $line, isset($lightTrace[1]) ? [$lightTrace[0]] : $lightTrace); } elseif (isset(self::$silencedErrorCache[$id][$message])) { $lightTrace = null; $errorAsException = self::$silencedErrorCache[$id][$message]; ++$errorAsException->count; } else { - $lightTrace = array(); + $lightTrace = []; $errorAsException = null; } if (100 < ++self::$silencedErrorCount) { - self::$silencedErrorCache = $lightTrace = array(); + self::$silencedErrorCache = $lightTrace = []; self::$silencedErrorCount = 1; } if ($errorAsException) { @@ -446,8 +446,8 @@ class ErrorHandler $lightTrace = $this->cleanTrace($backtrace, $type, $file, $line, $throw); $this->traceReflector->setValue($errorAsException, $lightTrace); } else { - $this->traceReflector->setValue($errorAsException, array()); - $backtrace = array(); + $this->traceReflector->setValue($errorAsException, []); + $backtrace = []; } } @@ -493,7 +493,7 @@ class ErrorHandler try { $this->isRecursive = true; $level = ($type & $level) ? $this->loggers[$type][1] : LogLevel::DEBUG; - $this->loggers[$type][0]->log($level, $logMessage, $errorAsException ? array('exception' => $errorAsException) : array()); + $this->loggers[$type][0]->log($level, $logMessage, $errorAsException ? ['exception' => $errorAsException] : []); } finally { $this->isRecursive = false; } @@ -527,12 +527,12 @@ class ErrorHandler } if ($exception instanceof FatalErrorException) { if ($exception instanceof FatalThrowableError) { - $error = array( + $error = [ 'type' => $type, 'message' => $message, 'file' => $exception->getFile(), 'line' => $exception->getLine(), - ); + ]; } else { $message = 'Fatal '.$message; } @@ -544,7 +544,7 @@ class ErrorHandler } if ($this->loggedErrors & $type) { try { - $this->loggers[$type][0]->log($this->loggers[$type][1], $message, array('exception' => $exception)); + $this->loggers[$type][0]->log($this->loggers[$type][1], $message, ['exception' => $exception]); } catch (\Throwable $handlerException) { } } @@ -586,7 +586,7 @@ class ErrorHandler } $handler = self::$reservedMemory = null; - $handlers = array(); + $handlers = []; $previousHandler = null; $sameHandlerLimit = 10; @@ -617,7 +617,7 @@ class ErrorHandler $handler[0]->setExceptionHandler($h); } $handler = $handler[0]; - $handlers = array(); + $handlers = []; if ($exit = null === $error) { $error = error_get_last(); @@ -661,11 +661,11 @@ class ErrorHandler */ protected function getFatalErrorHandlers() { - return array( + return [ new UndefinedFunctionFatalErrorHandler(), new UndefinedMethodFatalErrorHandler(), new ClassNotFoundFatalErrorHandler(), - ); + ]; } /** diff --git a/src/Symfony/Component/DependencyInjection/Compiler/AbstractRecursivePass.php b/src/Symfony/Component/DependencyInjection/Compiler/AbstractRecursivePass.php index d6bfc0c648..89857f78a8 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/AbstractRecursivePass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/AbstractRecursivePass.php @@ -86,7 +86,7 @@ abstract class AbstractRecursivePass implements CompilerPassInterface } elseif ($value instanceof ArgumentInterface) { $value->setValues($this->processValue($value->getValues())); } elseif ($value instanceof Expression && $this->processExpressions) { - $this->getExpressionLanguage()->compile((string) $value, array('this' => 'container')); + $this->getExpressionLanguage()->compile((string) $value, ['this' => 'container']); } elseif ($value instanceof Definition) { $value->setArguments($this->processValue($value->getArguments())); $value->setProperties($this->processValue($value->getProperties())); diff --git a/src/Symfony/Component/DependencyInjection/Compiler/AnalyzeServiceReferencesPass.php b/src/Symfony/Component/DependencyInjection/Compiler/AnalyzeServiceReferencesPass.php index adaded42fa..2dafb53789 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/AnalyzeServiceReferencesPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/AnalyzeServiceReferencesPass.php @@ -78,7 +78,7 @@ class AnalyzeServiceReferencesPass extends AbstractRecursivePass implements Repe try { parent::process($container); } finally { - $this->aliases = $this->definitions = array(); + $this->aliases = $this->definitions = []; } } diff --git a/src/Symfony/Component/DependencyInjection/Compiler/CheckExceptionOnInvalidReferenceBehaviorPass.php b/src/Symfony/Component/DependencyInjection/Compiler/CheckExceptionOnInvalidReferenceBehaviorPass.php index e987b1ad31..eef71587cd 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/CheckExceptionOnInvalidReferenceBehaviorPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/CheckExceptionOnInvalidReferenceBehaviorPass.php @@ -23,14 +23,14 @@ use Symfony\Component\DependencyInjection\Reference; */ class CheckExceptionOnInvalidReferenceBehaviorPass extends AbstractRecursivePass { - private $serviceLocatorContextIds = array(); + private $serviceLocatorContextIds = []; /** * {@inheritdoc} */ public function process(ContainerBuilder $container) { - $this->serviceLocatorContextIds = array(); + $this->serviceLocatorContextIds = []; foreach ($container->findTaggedServiceIds('container.service_locator_context') as $id => $tags) { $this->serviceLocatorContextIds[$id] = $tags[0]['id']; $container->getDefinition($id)->clearTag('container.service_locator_context'); @@ -39,7 +39,7 @@ class CheckExceptionOnInvalidReferenceBehaviorPass extends AbstractRecursivePass try { return parent::process($container); } finally { - $this->serviceLocatorContextIds = array(); + $this->serviceLocatorContextIds = []; } } diff --git a/src/Symfony/Component/DependencyInjection/Compiler/InlineServiceDefinitionsPass.php b/src/Symfony/Component/DependencyInjection/Compiler/InlineServiceDefinitionsPass.php index 8681c56f69..b326a30c50 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/InlineServiceDefinitionsPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/InlineServiceDefinitionsPass.php @@ -26,10 +26,10 @@ class InlineServiceDefinitionsPass extends AbstractRecursivePass implements Repe { private $analyzingPass; private $repeatedPass; - private $cloningIds = array(); - private $connectedIds = array(); - private $notInlinedIds = array(); - private $inlinedIds = array(); + private $cloningIds = []; + private $connectedIds = []; + private $notInlinedIds = []; + private $inlinedIds = []; private $graph; public function __construct(AnalyzeServiceReferencesPass $analyzingPass = null) @@ -68,7 +68,7 @@ class InlineServiceDefinitionsPass extends AbstractRecursivePass implements Repe } $this->graph = $analyzedContainer->getCompiler()->getServiceReferenceGraph(); $notInlinedIds = $this->notInlinedIds; - $this->connectedIds = $this->notInlinedIds = $this->inlinedIds = array(); + $this->connectedIds = $this->notInlinedIds = $this->inlinedIds = []; foreach ($analyzedContainer->getDefinitions() as $id => $definition) { if (!$this->graph->hasNode($id)) { @@ -96,7 +96,7 @@ class InlineServiceDefinitionsPass extends AbstractRecursivePass implements Repe } } finally { $this->container = null; - $this->connectedIds = $this->notInlinedIds = $this->inlinedIds = array(); + $this->connectedIds = $this->notInlinedIds = $this->inlinedIds = []; $this->graph = null; } } @@ -193,7 +193,7 @@ class InlineServiceDefinitionsPass extends AbstractRecursivePass implements Repe } $this->connectedIds[$id] = true; - $srcIds = array(); + $srcIds = []; $srcCount = 0; $isReferencedByConstructor = false; foreach ($this->graph->getNode($id)->getInEdges() as $edge) { diff --git a/src/Symfony/Component/DependencyInjection/Compiler/PassConfig.php b/src/Symfony/Component/DependencyInjection/Compiler/PassConfig.php index e5fb5b212f..e39cd4981a 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/PassConfig.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/PassConfig.php @@ -29,9 +29,9 @@ class PassConfig const TYPE_REMOVE = 'removing'; private $mergePass; - private $afterRemovingPasses = array(); - private $beforeOptimizationPasses = array(); - private $beforeRemovingPasses = array(); + private $afterRemovingPasses = []; + private $beforeOptimizationPasses = []; + private $beforeRemovingPasses = []; private $optimizationPasses; private $removingPasses; @@ -39,16 +39,16 @@ class PassConfig { $this->mergePass = new MergeExtensionConfigurationPass(); - $this->beforeOptimizationPasses = array( - 100 => array( + $this->beforeOptimizationPasses = [ + 100 => [ new ResolveClassPass(), new ResolveInstanceofConditionalsPass(), new RegisterEnvVarProcessorsPass(), - ), - -1000 => array(new ExtensionCompilerPass()), - ); + ], + -1000 => [new ExtensionCompilerPass()], + ]; - $this->optimizationPasses = array(array( + $this->optimizationPasses = [[ new ValidateEnvPlaceholdersPass(), new ResolveChildDefinitionsPass(), new ServiceLocatorTagPass(), @@ -69,15 +69,15 @@ class PassConfig new CheckCircularReferencesPass(), new CheckReferenceValidityPass(), new CheckArgumentsValidityPass(false), - )); + ]]; - $this->beforeRemovingPasses = array( - -100 => array( + $this->beforeRemovingPasses = [ + -100 => [ new ResolvePrivatesPass(), - ), - ); + ], + ]; - $this->removingPasses = array(array( + $this->removingPasses = [[ new RemovePrivateAliasesPass(), new ReplaceAliasByActualDefinitionPass(), new RemoveAbstractDefinitionsPass(), @@ -87,7 +87,7 @@ class PassConfig new DefinitionErrorExceptionPass(), new CheckExceptionOnInvalidReferenceBehaviorPass(), new ResolveHotPathPass(), - )); + ]]; } /** @@ -98,7 +98,7 @@ class PassConfig public function getPasses() { return array_merge( - array($this->mergePass), + [$this->mergePass], $this->getBeforeOptimizationPasses(), $this->getOptimizationPasses(), $this->getBeforeRemovingPasses(), @@ -126,7 +126,7 @@ class PassConfig $passes = &$this->$property; if (!isset($passes[$priority])) { - $passes[$priority] = array(); + $passes[$priority] = []; } $passes[$priority][] = $pass; } @@ -203,7 +203,7 @@ class PassConfig */ public function setAfterRemovingPasses(array $passes) { - $this->afterRemovingPasses = array($passes); + $this->afterRemovingPasses = [$passes]; } /** @@ -213,7 +213,7 @@ class PassConfig */ public function setBeforeOptimizationPasses(array $passes) { - $this->beforeOptimizationPasses = array($passes); + $this->beforeOptimizationPasses = [$passes]; } /** @@ -223,7 +223,7 @@ class PassConfig */ public function setBeforeRemovingPasses(array $passes) { - $this->beforeRemovingPasses = array($passes); + $this->beforeRemovingPasses = [$passes]; } /** @@ -233,7 +233,7 @@ class PassConfig */ public function setOptimizationPasses(array $passes) { - $this->optimizationPasses = array($passes); + $this->optimizationPasses = [$passes]; } /** @@ -243,7 +243,7 @@ class PassConfig */ public function setRemovingPasses(array $passes) { - $this->removingPasses = array($passes); + $this->removingPasses = [$passes]; } /** @@ -256,7 +256,7 @@ class PassConfig private function sortPasses(array $passes) { if (0 === \count($passes)) { - return array(); + return []; } krsort($passes); diff --git a/src/Symfony/Component/DependencyInjection/Compiler/RegisterEnvVarProcessorsPass.php b/src/Symfony/Component/DependencyInjection/Compiler/RegisterEnvVarProcessorsPass.php index 297f806286..852e7ca44a 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/RegisterEnvVarProcessorsPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/RegisterEnvVarProcessorsPass.php @@ -25,13 +25,13 @@ use Symfony\Component\DependencyInjection\Reference; */ class RegisterEnvVarProcessorsPass implements CompilerPassInterface { - private static $allowedTypes = array('array', 'bool', 'float', 'int', 'string'); + private static $allowedTypes = ['array', 'bool', 'float', 'int', 'string']; public function process(ContainerBuilder $container) { $bag = $container->getParameterBag(); - $types = array(); - $processors = array(); + $types = []; + $processors = []; foreach ($container->findTaggedServiceIds('container.env_var_processor') as $id => $tags) { if (!$r = $container->getReflectionClass($class = $container->getDefinition($id)->getClass())) { throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id)); diff --git a/src/Symfony/Component/DependencyInjection/Compiler/RemoveUnusedDefinitionsPass.php b/src/Symfony/Component/DependencyInjection/Compiler/RemoveUnusedDefinitionsPass.php index dddc13e667..6d1bbbffe9 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/RemoveUnusedDefinitionsPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/RemoveUnusedDefinitionsPass.php @@ -22,7 +22,7 @@ use Symfony\Component\DependencyInjection\Reference; */ class RemoveUnusedDefinitionsPass extends AbstractRecursivePass implements RepeatablePassInterface { - private $connectedIds = array(); + private $connectedIds = []; /** * {@inheritdoc} @@ -40,7 +40,7 @@ class RemoveUnusedDefinitionsPass extends AbstractRecursivePass implements Repea try { $this->enableExpressionProcessing(); $this->container = $container; - $connectedIds = array(); + $connectedIds = []; $aliases = $container->getAliases(); foreach ($aliases as $id => $alias) { @@ -58,7 +58,7 @@ class RemoveUnusedDefinitionsPass extends AbstractRecursivePass implements Repea while ($this->connectedIds) { $ids = $this->connectedIds; - $this->connectedIds = array(); + $this->connectedIds = []; foreach ($ids as $id) { if (!isset($connectedIds[$id]) && $container->hasDefinition($id)) { $connectedIds[$id] = true; @@ -76,7 +76,7 @@ class RemoveUnusedDefinitionsPass extends AbstractRecursivePass implements Repea } } finally { $this->container = null; - $this->connectedIds = array(); + $this->connectedIds = []; } } diff --git a/src/Symfony/Component/DependencyInjection/Compiler/ReplaceAliasByActualDefinitionPass.php b/src/Symfony/Component/DependencyInjection/Compiler/ReplaceAliasByActualDefinitionPass.php index 885e9d21ab..9981096361 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/ReplaceAliasByActualDefinitionPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/ReplaceAliasByActualDefinitionPass.php @@ -56,7 +56,7 @@ class ReplaceAliasByActualDefinitionPass extends AbstractRecursivePass $definition = $container->getDefinition($targetId); } catch (ServiceNotFoundException $e) { if ('' !== $e->getId() && '@' === $e->getId()[0]) { - throw new ServiceNotFoundException($e->getId(), $e->getSourceId(), null, array(substr($e->getId(), 1))); + throw new ServiceNotFoundException($e->getId(), $e->getSourceId(), null, [substr($e->getId(), 1)]); } throw $e; diff --git a/src/Symfony/Component/DependencyInjection/Compiler/ResolveInstanceofConditionalsPass.php b/src/Symfony/Component/DependencyInjection/Compiler/ResolveInstanceofConditionalsPass.php index cc9b0dd01a..02021c8bc5 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/ResolveInstanceofConditionalsPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/ResolveInstanceofConditionalsPass.php @@ -47,7 +47,7 @@ class ResolveInstanceofConditionalsPass implements CompilerPassInterface private function processDefinition(ContainerBuilder $container, $id, Definition $definition) { $instanceofConditionals = $definition->getInstanceofConditionals(); - $autoconfiguredInstanceof = $definition->isAutoconfigured() ? $container->getAutoconfiguredInstanceof() : array(); + $autoconfiguredInstanceof = $definition->isAutoconfigured() ? $container->getAutoconfiguredInstanceof() : []; if (!$instanceofConditionals && !$autoconfiguredInstanceof) { return $definition; } @@ -58,11 +58,11 @@ class ResolveInstanceofConditionalsPass implements CompilerPassInterface $conditionals = $this->mergeConditionals($autoconfiguredInstanceof, $instanceofConditionals, $container); - $definition->setInstanceofConditionals(array()); + $definition->setInstanceofConditionals([]); $parent = $shared = null; - $instanceofTags = array(); - $instanceofCalls = array(); - $instanceofBindings = array(); + $instanceofTags = []; + $instanceofCalls = []; + $instanceofBindings = []; foreach ($conditionals as $interface => $instanceofDefs) { if ($interface !== $class && (!$container->getReflectionClass($class, false))) { @@ -86,9 +86,9 @@ class ResolveInstanceofConditionalsPass implements CompilerPassInterface $instanceofCalls[] = $methodCall; } - $instanceofDef->setTags(array()); - $instanceofDef->setMethodCalls(array()); - $instanceofDef->setBindings(array()); + $instanceofDef->setTags([]); + $instanceofDef->setMethodCalls([]); + $instanceofDef->setBindings([]); if (isset($instanceofDef->getChanges()['shared'])) { $shared = $instanceofDef->isShared(); @@ -101,7 +101,7 @@ class ResolveInstanceofConditionalsPass implements CompilerPassInterface $abstract = $container->setDefinition('.abstract.instanceof.'.$id, $definition); // cast Definition to ChildDefinition - $definition->setBindings(array()); + $definition->setBindings([]); $definition = serialize($definition); $definition = substr_replace($definition, '53', 2, 2); $definition = substr_replace($definition, 'Child', 44, 0); @@ -130,11 +130,11 @@ class ResolveInstanceofConditionalsPass implements CompilerPassInterface // reset fields with "merge" behavior $abstract - ->setBindings(array()) - ->setArguments(array()) - ->setMethodCalls(array()) + ->setBindings([]) + ->setArguments([]) + ->setMethodCalls([]) ->setDecoratedService(null) - ->setTags(array()) + ->setTags([]) ->setAbstract(true); } @@ -144,7 +144,7 @@ class ResolveInstanceofConditionalsPass implements CompilerPassInterface private function mergeConditionals(array $autoconfiguredInstanceof, array $instanceofConditionals, ContainerBuilder $container) { // make each value an array of ChildDefinition - $conditionals = array_map(function ($childDef) { return array($childDef); }, $autoconfiguredInstanceof); + $conditionals = array_map(function ($childDef) { return [$childDef]; }, $autoconfiguredInstanceof); foreach ($instanceofConditionals as $interface => $instanceofDef) { // make sure the interface/class exists (but don't validate automaticInstanceofConditionals) @@ -153,7 +153,7 @@ class ResolveInstanceofConditionalsPass implements CompilerPassInterface } if (!isset($autoconfiguredInstanceof[$interface])) { - $conditionals[$interface] = array(); + $conditionals[$interface] = []; } $conditionals[$interface][] = $instanceofDef; diff --git a/src/Symfony/Component/DependencyInjection/Compiler/ServiceLocatorTagPass.php b/src/Symfony/Component/DependencyInjection/Compiler/ServiceLocatorTagPass.php index acf8403225..e335307482 100644 --- a/src/Symfony/Component/DependencyInjection/Compiler/ServiceLocatorTagPass.php +++ b/src/Symfony/Component/DependencyInjection/Compiler/ServiceLocatorTagPass.php @@ -112,8 +112,8 @@ final class ServiceLocatorTagPass extends AbstractRecursivePass // to derivate customized instances from the prototype one. $container->register($id .= '.'.$callerId, ServiceLocator::class) ->setPublic(false) - ->setFactory(array(new Reference($locatorId), 'withContext')) - ->addTag('container.service_locator_context', array('id' => $callerId)) + ->setFactory([new Reference($locatorId), 'withContext']) + ->addTag('container.service_locator_context', ['id' => $callerId]) ->addArgument($callerId) ->addArgument(new Reference('service_container')); } diff --git a/src/Symfony/Component/DependencyInjection/Container.php b/src/Symfony/Component/DependencyInjection/Container.php index 603c560fbb..938c0a8e3c 100644 --- a/src/Symfony/Component/DependencyInjection/Container.php +++ b/src/Symfony/Component/DependencyInjection/Container.php @@ -42,17 +42,17 @@ use Symfony\Contracts\Service\ResetInterface; class Container implements ResettableContainerInterface { protected $parameterBag; - protected $services = array(); - protected $privates = array(); - protected $fileMap = array(); - protected $methodMap = array(); - protected $factories = array(); - protected $aliases = array(); - protected $loading = array(); - protected $resolving = array(); - protected $syntheticIds = array(); + protected $services = []; + protected $privates = []; + protected $fileMap = []; + protected $methodMap = []; + protected $factories = []; + protected $aliases = []; + protected $loading = []; + protected $resolving = []; + protected $syntheticIds = []; - private $envCache = array(); + private $envCache = []; private $compiled = false; private $getEnv; @@ -222,7 +222,7 @@ class Container implements ResettableContainerInterface { return $this->services[$id] ?? $this->services[$id = $this->aliases[$id] ?? $id] - ?? ('service_container' === $id ? $this : ($this->factories[$id] ?? array($this, 'make'))($id, $invalidBehavior)); + ?? ('service_container' === $id ? $this : ($this->factories[$id] ?? [$this, 'make'])($id, $invalidBehavior)); } /** @@ -233,7 +233,7 @@ class Container implements ResettableContainerInterface private function make(string $id, int $invalidBehavior) { if (isset($this->loading[$id])) { - throw new ServiceCircularReferenceException($id, array_merge(array_keys($this->loading), array($id))); + throw new ServiceCircularReferenceException($id, array_merge(array_keys($this->loading), [$id])); } $this->loading[$id] = true; @@ -257,13 +257,13 @@ class Container implements ResettableContainerInterface throw new ServiceNotFoundException($id); } if (isset($this->syntheticIds[$id])) { - throw new ServiceNotFoundException($id, null, null, array(), sprintf('The "%s" service is synthetic, it needs to be set at boot time before it can be used.', $id)); + throw new ServiceNotFoundException($id, null, null, [], sprintf('The "%s" service is synthetic, it needs to be set at boot time before it can be used.', $id)); } if (isset($this->getRemovedIds()[$id])) { - throw new ServiceNotFoundException($id, null, null, array(), sprintf('The "%s" service or alias has been removed or inlined when the container was compiled. You should either make it public, or stop using the container directly and use dependency injection instead.', $id)); + throw new ServiceNotFoundException($id, null, null, [], sprintf('The "%s" service or alias has been removed or inlined when the container was compiled. You should either make it public, or stop using the container directly and use dependency injection instead.', $id)); } - $alternatives = array(); + $alternatives = []; foreach ($this->getServiceIds() as $knownId) { if ('' === $knownId || '.' === $knownId[0]) { continue; @@ -304,7 +304,7 @@ class Container implements ResettableContainerInterface public function reset() { $services = $this->services + $this->privates; - $this->services = $this->factories = $this->privates = array(); + $this->services = $this->factories = $this->privates = []; foreach ($services as $service) { try { @@ -324,7 +324,7 @@ class Container implements ResettableContainerInterface */ public function getServiceIds() { - return array_unique(array_merge(array('service_container'), array_keys($this->fileMap), array_keys($this->methodMap), array_keys($this->services))); + return array_unique(array_merge(['service_container'], array_keys($this->fileMap), array_keys($this->methodMap), array_keys($this->services))); } /** @@ -334,7 +334,7 @@ class Container implements ResettableContainerInterface */ public function getRemovedIds() { - return array(); + return []; } /** @@ -346,7 +346,7 @@ class Container implements ResettableContainerInterface */ public static function camelize($id) { - return strtr(ucwords(strtr($id, array('_' => ' ', '.' => '_ ', '\\' => '_ '))), array(' ' => '')); + return strtr(ucwords(strtr($id, ['_' => ' ', '.' => '_ ', '\\' => '_ '])), [' ' => '']); } /** @@ -358,7 +358,7 @@ class Container implements ResettableContainerInterface */ public static function underscore($id) { - return strtolower(preg_replace(array('/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'), array('\\1_\\2', '\\1_\\2'), str_replace('_', '.', $id))); + return strtolower(preg_replace(['/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'], ['\\1_\\2', '\\1_\\2'], str_replace('_', '.', $id))); } /** @@ -389,7 +389,7 @@ class Container implements ResettableContainerInterface return $this->envCache[$name]; } if (!$this->has($id = 'container.env_var_processors_locator')) { - $this->set($id, new ServiceLocator(array())); + $this->set($id, new ServiceLocator([])); } if (!$this->getEnv) { $this->getEnv = new \ReflectionMethod($this, __FUNCTION__); diff --git a/src/Symfony/Component/DependencyInjection/ContainerBuilder.php b/src/Symfony/Component/DependencyInjection/ContainerBuilder.php index 4c611bc6d8..8630052822 100644 --- a/src/Symfony/Component/DependencyInjection/ContainerBuilder.php +++ b/src/Symfony/Component/DependencyInjection/ContainerBuilder.php @@ -54,29 +54,29 @@ class ContainerBuilder extends Container implements TaggedContainerInterface /** * @var ExtensionInterface[] */ - private $extensions = array(); + private $extensions = []; /** * @var ExtensionInterface[] */ - private $extensionsByNs = array(); + private $extensionsByNs = []; /** * @var Definition[] */ - private $definitions = array(); + private $definitions = []; /** * @var Alias[] */ - private $aliasDefinitions = array(); + private $aliasDefinitions = []; /** * @var ResourceInterface[] */ - private $resources = array(); + private $resources = []; - private $extensionConfigs = array(); + private $extensionConfigs = []; /** * @var Compiler @@ -98,33 +98,33 @@ class ContainerBuilder extends Container implements TaggedContainerInterface /** * @var ExpressionFunctionProviderInterface[] */ - private $expressionLanguageProviders = array(); + private $expressionLanguageProviders = []; /** * @var string[] with tag names used by findTaggedServiceIds */ - private $usedTags = array(); + private $usedTags = []; /** * @var string[][] a map of env var names to their placeholders */ - private $envPlaceholders = array(); + private $envPlaceholders = []; /** * @var int[] a map of env vars to their resolution counter */ - private $envCounters = array(); + private $envCounters = []; /** * @var string[] the list of vendor directories */ private $vendors; - private $autoconfiguredInstanceof = array(); + private $autoconfiguredInstanceof = []; - private $removedIds = array(); + private $removedIds = []; - private static $internalTypes = array( + private static $internalTypes = [ 'int' => true, 'float' => true, 'string' => true, @@ -136,7 +136,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface 'callable' => true, 'iterable' => true, 'mixed' => true, - ); + ]; public function __construct(ParameterBagInterface $parameterBag = null) { @@ -431,7 +431,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface } if (\func_num_args() < 2) { - $values = array(); + $values = []; } $namespace = $this->getExtension($extension)->getAlias(); @@ -563,7 +563,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface } if (null === $inlineServices) { $isConstructorArgument = true; - $inlineServices = array(); + $inlineServices = []; } try { if (ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE === $invalidBehavior) { @@ -647,7 +647,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface foreach ($this->extensions as $name => $extension) { if (!isset($this->extensionConfigs[$name])) { - $this->extensionConfigs[$name] = array(); + $this->extensionConfigs[$name] = []; } $this->extensionConfigs[$name] = array_merge($this->extensionConfigs[$name], $container->getExtensionConfig($name)); @@ -657,7 +657,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface $envPlaceholders = $container->getParameterBag()->getEnvPlaceholders(); $this->getParameterBag()->mergeEnvPlaceholders($container->getParameterBag()); } else { - $envPlaceholders = array(); + $envPlaceholders = []; } foreach ($container->envCounters as $env => $count) { @@ -690,7 +690,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface public function getExtensionConfig($name) { if (!isset($this->extensionConfigs[$name])) { - $this->extensionConfigs[$name] = array(); + $this->extensionConfigs[$name] = []; } return $this->extensionConfigs[$name]; @@ -705,7 +705,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface public function prependExtensionConfig($name, array $config) { if (!isset($this->extensionConfigs[$name])) { - $this->extensionConfigs[$name] = array(); + $this->extensionConfigs[$name] = []; } array_unshift($this->extensionConfigs[$name], $config); @@ -753,7 +753,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface } } - $this->extensionConfigs = array(); + $this->extensionConfigs = []; if ($bag instanceof EnvPlaceholderParameterBag) { if ($resolveEnvPlaceholders) { @@ -807,7 +807,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface */ public function setAliases(array $aliases) { - $this->aliasDefinitions = array(); + $this->aliasDefinitions = []; $this->addAliases($aliases); } @@ -947,7 +947,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface */ public function setDefinitions(array $definitions) { - $this->definitions = array(); + $this->definitions = []; $this->addDefinitions($definitions); } @@ -1031,7 +1031,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface { $id = (string) $id; - $seen = array(); + $seen = []; while (isset($this->aliasDefinitions[$id])) { $id = (string) $this->aliasDefinitions[$id]; @@ -1103,7 +1103,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface if (null !== $factory = $definition->getFactory()) { if (\is_array($factory)) { - $factory = array($this->doResolveServices($parameterBag->resolveValue($factory[0]), $inlineServices, $isConstructorArgument), $factory[1]); + $factory = [$this->doResolveServices($parameterBag->resolveValue($factory[0]), $inlineServices, $isConstructorArgument), $factory[1]]; } elseif (!\is_string($factory)) { throw new RuntimeException(sprintf('Cannot create service "%s" because of invalid factory', $id)); } @@ -1181,7 +1181,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface return $this->doResolveServices($value); } - private function doResolveServices($value, array &$inlineServices = array(), $isConstructorArgument = false) + private function doResolveServices($value, array &$inlineServices = [], $isConstructorArgument = false) { if (\is_array($value)) { foreach ($value as $k => $v) { @@ -1228,13 +1228,13 @@ class ContainerBuilder extends Container implements TaggedContainerInterface return $count; }); } elseif ($value instanceof ServiceLocatorArgument) { - $refs = array(); + $refs = []; foreach ($value->getValues() as $k => $v) { if ($v) { - $refs[$k] = array($v); + $refs[$k] = [$v]; } } - $value = new ServiceLocator(\Closure::fromCallable(array($this, 'resolveServices')), $refs); + $value = new ServiceLocator(\Closure::fromCallable([$this, 'resolveServices']), $refs); } elseif ($value instanceof Reference) { $value = $this->doGet((string) $value, $value->getInvalidBehavior(), $inlineServices, $isConstructorArgument); } elseif ($value instanceof Definition) { @@ -1242,7 +1242,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface } elseif ($value instanceof Parameter) { $value = $this->getParameter((string) $value); } elseif ($value instanceof Expression) { - $value = $this->getExpressionLanguage()->evaluate($value, array('container' => $this)); + $value = $this->getExpressionLanguage()->evaluate($value, ['container' => $this]); } return $value; @@ -1270,7 +1270,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface public function findTaggedServiceIds($name, $throwOnAbstract = false) { $this->usedTags[] = $name; - $tags = array(); + $tags = []; foreach ($this->getDefinitions() as $id => $definition) { if ($definition->hasTag($name)) { if ($throwOnAbstract && $definition->isAbstract()) { @@ -1290,7 +1290,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface */ public function findTags() { - $tags = array(); + $tags = []; foreach ($this->getDefinitions() as $id => $definition) { $tags = array_merge(array_keys($definition->getTags()), $tags); } @@ -1389,7 +1389,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface } if (\is_array($value)) { - $result = array(); + $result = []; foreach ($value as $k => $v) { $result[\is_string($k) ? $this->resolveEnvPlaceholders($k, $format, $usedEnvs) : $k] = $this->resolveEnvPlaceholders($v, $format, $usedEnvs); } @@ -1471,7 +1471,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface */ public static function getServiceConditionals($value) { - $services = array(); + $services = []; if (\is_array($value)) { foreach ($value as $v) { @@ -1495,7 +1495,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface */ public static function getInitializedConditionals($value) { - $services = array(); + $services = []; if (\is_array($value)) { foreach ($value as $v) { @@ -1519,7 +1519,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface { $hash = substr(base64_encode(hash('sha256', serialize($value), true)), 0, 7); - return str_replace(array('/', '+'), array('.', '_'), $hash); + return str_replace(['/', '+'], ['.', '_'], $hash); } /** diff --git a/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php b/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php index 71accf4f8c..0a2162d372 100644 --- a/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php +++ b/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php @@ -62,7 +62,7 @@ class PhpDumper extends Dumper private $variableCount; private $inlinedDefinitions; private $serviceCalls; - private $reservedVariables = array('instance', 'class', 'this'); + private $reservedVariables = ['instance', 'class', 'this']; private $expressionLanguage; private $targetDirRegex; private $targetDirMaxMatches; @@ -73,14 +73,14 @@ class PhpDumper extends Dumper private $asFiles; private $hotPathTag; private $inlineRequires; - private $inlinedRequires = array(); - private $circularReferences = array(); - private $singleUsePrivateIds = array(); + private $inlinedRequires = []; + private $circularReferences = []; + private $singleUsePrivateIds = []; private $addThrow = false; private $addGetService = false; - private $locatedIds = array(); + private $locatedIds = []; private $serviceLocatorTag; - private $exportedVariables = array(); + private $exportedVariables = []; /** * @var ProxyDumper @@ -121,13 +121,13 @@ class PhpDumper extends Dumper * * @throws EnvParameterException When an env var exists but has not been dumped */ - public function dump(array $options = array()) + public function dump(array $options = []) { - $this->locatedIds = array(); + $this->locatedIds = []; $this->targetDirRegex = null; - $this->inlinedRequires = array(); - $this->exportedVariables = array(); - $options = array_merge(array( + $this->inlinedRequires = []; + $this->exportedVariables = []; + $options = array_merge([ 'class' => 'ProjectServiceContainer', 'base_class' => 'Container', 'namespace' => '', @@ -137,7 +137,7 @@ class PhpDumper extends Dumper 'inline_class_loader_parameter' => 'container.dumper.inline_class_loader', 'service_locator_tag' => 'container.service_locator', 'build_time' => time(), - ), $options); + ], $options); $this->addThrow = $this->addGetService = false; $this->namespace = $options['namespace']; @@ -171,9 +171,9 @@ class PhpDumper extends Dumper } (new AnalyzeServiceReferencesPass(false, !$this->getProxyDumper() instanceof NullDumper))->process($this->container); - $checkedNodes = array(); - $this->circularReferences = array(); - $this->singleUsePrivateIds = array(); + $checkedNodes = []; + $this->circularReferences = []; + $this->singleUsePrivateIds = []; foreach ($this->container->getCompiler()->getServiceReferenceGraph()->getNodes() as $id => $node) { if (!$node->getValue() instanceof Definition) { continue; @@ -186,7 +186,7 @@ class PhpDumper extends Dumper } } $this->container->getCompiler()->getServiceReferenceGraph()->clear(); - $checkedNodes = array(); + $checkedNodes = []; $this->docStar = $options['debug'] ? '*' : ''; @@ -240,7 +240,7 @@ use Symfony\Component\DependencyInjection\Exception\RuntimeException; // This file has been auto-generated by the Symfony Dependency Injection Component for internal use. EOF; - $files = array(); + $files = []; $ids = $this->container->getRemovedIds(); foreach ($this->container->getDefinitions() as $id => $definition) { @@ -265,7 +265,7 @@ EOF; } $files[$options['class'].'.php'] = $code.$this->endClass(); $hash = ucfirst(strtr(ContainerBuilder::hash($files), '._', 'xx')); - $code = array(); + $code = []; foreach ($files as $file => $c) { $code["Container{$hash}/{$file}"] = $c; @@ -308,12 +308,12 @@ EOF; } $this->targetDirRegex = null; - $this->inlinedRequires = array(); - $this->circularReferences = array(); - $this->locatedIds = array(); - $this->exportedVariables = array(); + $this->inlinedRequires = []; + $this->circularReferences = []; + $this->locatedIds = []; + $this->exportedVariables = []; - $unusedEnvs = array(); + $unusedEnvs = []; foreach ($this->container->getEnvCounters() as $env => $use) { if (!$use) { $unusedEnvs[] = $env; @@ -338,7 +338,7 @@ EOF; return $this->proxyDumper; } - private function analyzeCircularReferences($sourceId, array $edges, &$checkedNodes, &$currentPath = array()) + private function analyzeCircularReferences($sourceId, array $edges, &$checkedNodes, &$currentPath = []) { $checkedNodes[$sourceId] = true; $currentPath[$sourceId] = $sourceId; @@ -367,7 +367,7 @@ EOF; unset($currentPath[$sourceId]); } - private function connectCircularReferences($sourceId, &$currentPath, &$subPath = array()) + private function connectCircularReferences($sourceId, &$currentPath, &$subPath = []) { $subPath[$sourceId] = $sourceId; $currentPath[$sourceId] = $sourceId; @@ -423,7 +423,7 @@ EOF; private function generateProxyClasses() { - $alreadyGenerated = array(); + $alreadyGenerated = []; $definitions = $this->container->getDefinitions(); $strip = '' === $this->docStar && method_exists('Symfony\Component\HttpKernel\Kernel', 'stripComments'); $proxyDumper = $this->getProxyDumper(); @@ -454,7 +454,7 @@ EOF; $code = ''; if ($this->inlineRequires && !$this->isHotPath($definition)) { - $lineage = array(); + $lineage = []; foreach ($this->inlinedDefinitions as $def) { if (!$def->isDeprecated() && \is_string($class = \is_array($factory = $def->getFactory()) && \is_string($factory[0]) ? $factory[0] : $def->getClass())) { $this->collectLineage($class, $lineage); @@ -566,7 +566,7 @@ EOF; { $calls = ''; foreach ($definition->getMethodCalls() as $call) { - $arguments = array(); + $arguments = []; foreach ($call[1] as $value) { $arguments[] = $this->dumpValue($value); } @@ -619,11 +619,11 @@ EOF; private function addService(string $id, Definition $definition): array { $this->definitionVariables = new \SplObjectStorage(); - $this->referenceVariables = array(); + $this->referenceVariables = []; $this->variableCount = 0; $this->referenceVariables[$id] = new Variable('instance'); - $return = array(); + $return = []; if ($class = $definition->getClass()) { $class = $class instanceof Parameter ? '%'.$class.'%' : $this->container->resolveEnvPlaceholders($class); @@ -680,8 +680,8 @@ EOF; EOF; } - $this->serviceCalls = array(); - $this->inlinedDefinitions = $this->getDefinitionsFromArguments(array($definition), null, $this->serviceCalls); + $this->serviceCalls = []; + $this->inlinedDefinitions = $this->getDefinitionsFromArguments([$definition], null, $this->serviceCalls); $code .= $this->addServiceInclude($id, $definition); @@ -705,7 +705,7 @@ EOF; $this->definitionVariables = $this->inlinedDefinitions = null; $this->referenceVariables = $this->serviceCalls = null; - return array($file, $code); + return [$file, $code]; } private function addInlineVariables(string $id, Definition $definition, array $arguments, bool $forConstructor): string @@ -782,11 +782,11 @@ EOTXT return ''; } - $arguments = array($inlineDef->getArguments(), $inlineDef->getFactory()); + $arguments = [$inlineDef->getArguments(), $inlineDef->getFactory()]; $code = $this->addInlineVariables($id, $definition, $arguments, $forConstructor); - if ($arguments = array_filter(array($inlineDef->getProperties(), $inlineDef->getMethodCalls(), $inlineDef->getConfigurator()))) { + if ($arguments = array_filter([$inlineDef->getProperties(), $inlineDef->getMethodCalls(), $inlineDef->getConfigurator()])) { $isSimpleInstance = false; } elseif ($definition !== $inlineDef && 2 > $this->inlinedDefinitions[$inlineDef]) { return $code; @@ -855,9 +855,9 @@ EOTXT if (!$definition->isShared()) { $i = strpos($code, "\n\ninclude_once "); if (false !== $i && false !== $i = strpos($code, "\n\n", 2 + $i)) { - $code = array(substr($code, 0, 2 + $i), substr($code, 2 + $i)); + $code = [substr($code, 0, 2 + $i), substr($code, 2 + $i)]; } else { - $code = array("\n", $code); + $code = ["\n", $code]; } $code[1] = implode("\n", array_map(function ($line) { return $line ? ' '.$line : $line; }, explode("\n", $code[1]))); $factory = sprintf('$this->factories%s[\'%s\']', $definition->isPublic() ? '' : "['service_container']", $id); @@ -875,7 +875,7 @@ EOTXT $tail = $return ? ";\n" : ''; if (BaseServiceLocator::class === $definition->getClass() && $definition->hasTag($this->serviceLocatorTag)) { - $arguments = array(); + $arguments = []; foreach ($definition->getArgument(0) as $k => $argument) { $arguments[$k] = $argument->getValues()[0]; } @@ -883,7 +883,7 @@ EOTXT return $return.$this->dumpValue(new ServiceLocatorArgument($arguments)).$tail; } - $arguments = array(); + $arguments = []; foreach ($definition->getArguments() as $value) { $arguments[] = $this->dumpValue($value); } @@ -1157,11 +1157,11 @@ EOF; return ''; } - $lineage = array(); + $lineage = []; foreach ($this->container->findTaggedServiceIds($this->hotPathTag) as $id => $tags) { $definition = $this->container->getDefinition($id); - $inlinedDefinitions = $this->getDefinitionsFromArguments(array($definition)); + $inlinedDefinitions = $this->getDefinitionsFromArguments([$definition]); foreach ($inlinedDefinitions as $def) { if (\is_string($class = \is_array($factory = $def->getFactory()) && \is_string($factory[0]) ? $factory[0] : $def->getClass())) { @@ -1188,14 +1188,14 @@ EOF; return ''; } - $php = array(); - $dynamicPhp = array(); + $php = []; + $dynamicPhp = []; foreach ($this->container->getParameterBag()->all() as $key => $value) { if ($key !== $resolvedKey = $this->container->resolveEnvPlaceholders($key)) { throw new InvalidArgumentException(sprintf('Parameter name cannot use env parameters: %s.', $resolvedKey)); } - $export = $this->exportParameters(array($value)); + $export = $this->exportParameters([$value]); $export = explode('0 => ', substr(rtrim($export, " )\n"), 7, -1), 2); if (preg_match("/\\\$this->(?:getEnv\('(?:\w++:)*+\w++'\)|targetDirs\[\d++\])/", $export[1])) { @@ -1317,7 +1317,7 @@ EOF; */ private function exportParameters(array $parameters, string $path = '', int $indent = 12): string { - $php = array(); + $php = []; foreach ($parameters as $key => $value) { if (\is_array($value)) { $value = $this->exportParameters($value, $path.'/'.$key, $indent + 4); @@ -1375,7 +1375,7 @@ EOF; private function getServiceConditionals($value): string { - $conditions = array(); + $conditions = []; foreach (ContainerBuilder::getInitializedConditionals($value) as $service) { if (!$this->container->hasDefinition($service)) { return 'false'; @@ -1397,7 +1397,7 @@ EOF; return implode(' && ', $conditions); } - private function getDefinitionsFromArguments(array $arguments, \SplObjectStorage $definitions = null, array &$calls = array()): \SplObjectStorage + private function getDefinitionsFromArguments(array $arguments, \SplObjectStorage $definitions = null, array &$calls = []): \SplObjectStorage { if (null === $definitions) { $definitions = new \SplObjectStorage(); @@ -1410,7 +1410,7 @@ EOF; $id = (string) $argument; if (!isset($calls[$id])) { - $calls[$id] = array(0, $argument->getInvalidBehavior()); + $calls[$id] = [0, $argument->getInvalidBehavior()]; } else { $calls[$id][1] = min($calls[$id][1], $argument->getInvalidBehavior()); } @@ -1422,7 +1422,7 @@ EOF; $definitions[$argument] = 1 + $definitions[$argument]; } else { $definitions[$argument] = 1; - $arguments = array($argument->getArguments(), $argument->getFactory(), $argument->getProperties(), $argument->getMethodCalls(), $argument->getConfigurator()); + $arguments = [$argument->getArguments(), $argument->getFactory(), $argument->getProperties(), $argument->getMethodCalls(), $argument->getConfigurator()]; $this->getDefinitionsFromArguments($arguments, $definitions, $calls); } } @@ -1439,14 +1439,14 @@ EOF; if ($value && $interpolate && false !== $param = array_search($value, $this->container->getParameterBag()->all(), true)) { return $this->dumpValue("%$param%"); } - $code = array(); + $code = []; foreach ($value as $k => $v) { $code[] = sprintf('%s => %s', $this->dumpValue($k, $interpolate), $this->dumpValue($v, $interpolate)); } return sprintf('array(%s)', implode(', ', $code)); } elseif ($value instanceof ArgumentInterface) { - $scope = array($this->definitionVariables, $this->referenceVariables); + $scope = [$this->definitionVariables, $this->referenceVariables]; $this->definitionVariables = $this->referenceVariables = null; try { @@ -1465,14 +1465,14 @@ EOF; } if ($value instanceof IteratorArgument) { - $operands = array(0); - $code = array(); + $operands = [0]; + $code = []; $code[] = 'new RewindableGenerator(function () {'; if (!$values = $value->getValues()) { $code[] = ' return new \EmptyIterator();'; } else { - $countCode = array(); + $countCode = []; $countCode[] = 'function () {'; foreach ($values as $k => $v) { @@ -1548,7 +1548,7 @@ EOF; return $this->getServiceCall($id, $value); } elseif ($value instanceof Expression) { - return $this->getExpressionLanguage()->compile((string) $value, array('this' => 'container')); + return $this->getExpressionLanguage()->compile((string) $value, ['this' => 'container']); } elseif ($value instanceof Parameter) { return $this->dumpParameter($value); } elseif (true === $interpolate && \is_string($value)) { @@ -1670,8 +1670,8 @@ EOF; */ private function initializeMethodNamesMap(string $class) { - $this->serviceIdToMethodNameMap = array(); - $this->usedMethodNames = array(); + $this->serviceIdToMethodNameMap = []; + $this->usedMethodNames = []; if ($reflectionClass = $this->container->getReflectionClass($class)) { foreach ($reflectionClass->getMethods() as $method) { @@ -1776,7 +1776,7 @@ EOF; if ($node->getValue()->isPublic()) { return false; } - $ids = array(); + $ids = []; foreach ($node->getInEdges() as $edge) { if (!$value = $edge->getSourceNode()->getValue()) { continue; diff --git a/src/Symfony/Component/DependencyInjection/Loader/Configurator/Traits/LazyTrait.php b/src/Symfony/Component/DependencyInjection/Loader/Configurator/Traits/LazyTrait.php index d2c3431fbd..d387dfb4b0 100644 --- a/src/Symfony/Component/DependencyInjection/Loader/Configurator/Traits/LazyTrait.php +++ b/src/Symfony/Component/DependencyInjection/Loader/Configurator/Traits/LazyTrait.php @@ -24,7 +24,7 @@ trait LazyTrait { $this->definition->setLazy((bool) $lazy); if (\is_string($lazy)) { - $this->definition->addTag('proxy', array('interface' => $lazy)); + $this->definition->addTag('proxy', ['interface' => $lazy]); } return $this; diff --git a/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php b/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php index bc67d1ec22..c5292ecf68 100644 --- a/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php +++ b/src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php @@ -65,7 +65,7 @@ class XmlFileLoader extends FileLoader try { $this->parseDefinitions($xml, $path, $defaults); } finally { - $this->instanceof = array(); + $this->instanceof = []; } } @@ -136,11 +136,11 @@ class XmlFileLoader extends FileLoader } $this->setCurrentDir(\dirname($file)); - $this->instanceof = array(); + $this->instanceof = []; $this->isLoadingInstanceof = true; $instanceof = $xpath->query('//container:services/container:instanceof'); foreach ($instanceof as $service) { - $this->setDefinition((string) $service->getAttribute('id'), $this->parseDefinition($service, $file, array())); + $this->setDefinition((string) $service->getAttribute('id'), $this->parseDefinition($service, $file, [])); } $this->isLoadingInstanceof = false; @@ -152,7 +152,7 @@ class XmlFileLoader extends FileLoader if (\count($excludes) > 0) { throw new InvalidArgumentException('You cannot use both the attribute "exclude" and tags at the same time.'); } - $excludes = array($service->getAttribute('exclude')); + $excludes = [$service->getAttribute('exclude')]; } $this->registerClasses($definition, (string) $service->getAttribute('namespace'), (string) $service->getAttribute('resource'), $excludes); } else { @@ -173,12 +173,12 @@ class XmlFileLoader extends FileLoader $xpath->registerNamespace('container', self::NS); if (null === $defaultsNode = $xpath->query('//container:services/container:defaults')->item(0)) { - return array(); + return []; } - $defaults = array( + $defaults = [ 'tags' => $this->getChildren($defaultsNode, 'tag'), 'bind' => array_map(function ($v) { return new BoundArgument($v); }, $this->getArgumentsAsPhp($defaultsNode, 'bind', $file)), - ); + ]; foreach ($defaults['tags'] as $tag) { if ('' === $tag->getAttribute('name')) { @@ -262,10 +262,10 @@ class XmlFileLoader extends FileLoader $definition->setAutoconfigured($defaults['autoconfigure']); } - $definition->setChanges(array()); + $definition->setChanges([]); } - foreach (array('class', 'public', 'shared', 'synthetic', 'abstract') as $key) { + foreach (['class', 'public', 'shared', 'synthetic', 'abstract'] as $key) { if ($value = $service->getAttribute($key)) { $method = 'set'.$key; $definition->$method($value = XmlUtils::phpize($value)); @@ -275,7 +275,7 @@ class XmlFileLoader extends FileLoader if ($value = $service->getAttribute('lazy')) { $definition->setLazy((bool) $value = XmlUtils::phpize($value)); if (\is_string($value)) { - $definition->addTag('proxy', array('interface' => $value)); + $definition->addTag('proxy', ['interface' => $value]); } } @@ -313,7 +313,7 @@ class XmlFileLoader extends FileLoader $class = $factory->hasAttribute('class') ? $factory->getAttribute('class') : null; } - $definition->setFactory(array($class, $factory->getAttribute('method'))); + $definition->setFactory([$class, $factory->getAttribute('method')]); } } @@ -328,7 +328,7 @@ class XmlFileLoader extends FileLoader $class = $configurator->getAttribute('class'); } - $definition->setConfigurator(array($class, $configurator->getAttribute('method'))); + $definition->setConfigurator([$class, $configurator->getAttribute('method')]); } } @@ -343,7 +343,7 @@ class XmlFileLoader extends FileLoader } foreach ($tags as $tag) { - $parameters = array(); + $parameters = []; foreach ($tag->attributes as $name => $node) { if ('name' === $name) { continue; @@ -393,7 +393,7 @@ class XmlFileLoader extends FileLoader private function parseFileToDOM($file) { try { - $dom = XmlUtils::loadFile($file, array($this, 'validateSchema')); + $dom = XmlUtils::loadFile($file, [$this, 'validateSchema']); } catch (\InvalidArgumentException $e) { throw new InvalidArgumentException(sprintf('Unable to parse file "%s".', $file), $e->getCode(), $e); } @@ -412,7 +412,7 @@ class XmlFileLoader extends FileLoader */ private function processAnonymousServices(\DOMDocument $xml, $file, $defaults) { - $definitions = array(); + $definitions = []; $count = 0; $suffix = '~'.ContainerBuilder::hash($file); @@ -428,7 +428,7 @@ class XmlFileLoader extends FileLoader $node->setAttribute('id', $id); $node->setAttribute('service', $id); - $definitions[$id] = array($services[0], $file); + $definitions[$id] = [$services[0], $file]; $services[0]->setAttribute('id', $id); // anonymous services are always private @@ -448,7 +448,7 @@ class XmlFileLoader extends FileLoader // resolve definitions uksort($definitions, 'strnatcmp'); foreach (array_reverse($definitions) as $id => list($domElement, $file)) { - if (null !== $definition = $this->parseDefinition($domElement, $file, array())) { + if (null !== $definition = $this->parseDefinition($domElement, $file, [])) { $this->setDefinition($id, $definition); } } @@ -466,7 +466,7 @@ class XmlFileLoader extends FileLoader */ private function getArgumentsAsPhp(\DOMElement $node, $name, $file, $lowercase = true, $isChildDefinition = false) { - $arguments = array(); + $arguments = []; foreach ($this->getChildren($node, $name) as $arg) { if ($arg->hasAttribute('name')) { $arg->setAttribute('key', $arg->getAttribute('name')); @@ -565,7 +565,7 @@ class XmlFileLoader extends FileLoader */ private function getChildren(\DOMNode $node, $name) { - $children = array(); + $children = []; foreach ($node->childNodes as $child) { if ($child instanceof \DOMElement && $child->localName === $name && self::NS === $child->namespaceURI) { $children[] = $child; @@ -586,7 +586,7 @@ class XmlFileLoader extends FileLoader */ public function validateSchema(\DOMDocument $dom) { - $schemaLocations = array('http://symfony.com/schema/dic/services' => str_replace('\\', '/', __DIR__.'/schema/dic/services/services-1.0.xsd')); + $schemaLocations = ['http://symfony.com/schema/dic/services' => str_replace('\\', '/', __DIR__.'/schema/dic/services/services-1.0.xsd')]; if ($element = $dom->documentElement->getAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'schemaLocation')) { $items = preg_split('/\s+/', $element); @@ -607,7 +607,7 @@ class XmlFileLoader extends FileLoader } } - $tmpfiles = array(); + $tmpfiles = []; $imports = ''; foreach ($schemaLocations as $namespace => $location) { $parts = explode('/', $location); @@ -662,7 +662,7 @@ EOF private function validateAlias(\DOMElement $alias, $file) { foreach ($alias->attributes as $name => $node) { - if (!\in_array($name, array('alias', 'id', 'public'))) { + if (!\in_array($name, ['alias', 'id', 'public'])) { throw new InvalidArgumentException(sprintf('Invalid attribute "%s" defined for alias "%s" in "%s".', $name, $alias->getAttribute('id'), $file)); } } @@ -711,7 +711,7 @@ EOF $values = static::convertDomElementToArray($node); if (!\is_array($values)) { - $values = array(); + $values = []; } $this->container->loadFromExtension($node->namespaceURI, $values); diff --git a/src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php b/src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php index e286d27952..05fbe86363 100644 --- a/src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php +++ b/src/Symfony/Component/DependencyInjection/Loader/YamlFileLoader.php @@ -38,7 +38,7 @@ use Symfony\Component\Yaml\Yaml; */ class YamlFileLoader extends FileLoader { - private static $serviceKeywords = array( + private static $serviceKeywords = [ 'alias' => 'alias', 'parent' => 'parent', 'class' => 'class', @@ -61,9 +61,9 @@ class YamlFileLoader extends FileLoader 'autowire' => 'autowire', 'autoconfigure' => 'autoconfigure', 'bind' => 'bind', - ); + ]; - private static $prototypeKeywords = array( + private static $prototypeKeywords = [ 'resource' => 'resource', 'namespace' => 'namespace', 'exclude' => 'exclude', @@ -82,9 +82,9 @@ class YamlFileLoader extends FileLoader 'autowire' => 'autowire', 'autoconfigure' => 'autoconfigure', 'bind' => 'bind', - ); + ]; - private static $instanceofKeywords = array( + private static $instanceofKeywords = [ 'shared' => 'shared', 'lazy' => 'lazy', 'public' => 'public', @@ -94,15 +94,15 @@ class YamlFileLoader extends FileLoader 'tags' => 'tags', 'autowire' => 'autowire', 'bind' => 'bind', - ); + ]; - private static $defaultsKeywords = array( + private static $defaultsKeywords = [ 'public' => 'public', 'tags' => 'tags', 'autowire' => 'autowire', 'autoconfigure' => 'autoconfigure', 'bind' => 'bind', - ); + ]; private $yamlParser; @@ -149,7 +149,7 @@ class YamlFileLoader extends FileLoader try { $this->parseDefinitions($content, $path); } finally { - $this->instanceof = array(); + $this->instanceof = []; } } @@ -162,11 +162,11 @@ class YamlFileLoader extends FileLoader return false; } - if (null === $type && \in_array(pathinfo($resource, PATHINFO_EXTENSION), array('yaml', 'yml'), true)) { + if (null === $type && \in_array(pathinfo($resource, PATHINFO_EXTENSION), ['yaml', 'yml'], true)) { return true; } - return \in_array($type, array('yaml', 'yml'), true); + return \in_array($type, ['yaml', 'yml'], true); } private function parseImports(array $content, string $file) @@ -182,7 +182,7 @@ class YamlFileLoader extends FileLoader $defaultDirectory = \dirname($file); foreach ($content['imports'] as $import) { if (!\is_array($import)) { - $import = array('resource' => $import); + $import = ['resource' => $import]; } if (!isset($import['resource'])) { throw new InvalidArgumentException(sprintf('An import should provide a resource in %s. Check your YAML syntax.', $file)); @@ -210,7 +210,7 @@ class YamlFileLoader extends FileLoader if (!\is_array($instanceof)) { throw new InvalidArgumentException(sprintf('Service "_instanceof" key must be an array, "%s" given in "%s".', \gettype($instanceof), $file)); } - $this->instanceof = array(); + $this->instanceof = []; $this->isLoadingInstanceof = true; foreach ($instanceof as $id => $service) { if (!$service || !\is_array($service)) { @@ -219,7 +219,7 @@ class YamlFileLoader extends FileLoader if (\is_string($service) && 0 === strpos($service, '@')) { throw new InvalidArgumentException(sprintf('Type definition "%s" cannot be an alias within "_instanceof" in %s. Check your YAML syntax.', $id, $file)); } - $this->parseDefinition($id, $service, $file, array()); + $this->parseDefinition($id, $service, $file, []); } } @@ -236,7 +236,7 @@ class YamlFileLoader extends FileLoader private function parseDefaults(array &$content, string $file): array { if (!array_key_exists('_defaults', $content['services'])) { - return array(); + return []; } $defaults = $content['services']['_defaults']; unset($content['services']['_defaults']); @@ -258,7 +258,7 @@ class YamlFileLoader extends FileLoader foreach ($tags as $tag) { if (!\is_array($tag)) { - $tag = array('name' => $tag); + $tag = ['name' => $tag]; } if (!isset($tag['name'])) { @@ -327,11 +327,11 @@ class YamlFileLoader extends FileLoader } if (\is_array($service) && $this->isUsingShortSyntax($service)) { - $service = array('arguments' => $service); + $service = ['arguments' => $service]; } if (null === $service) { - $service = array(); + $service = []; } if (!\is_array($service)) { @@ -349,7 +349,7 @@ class YamlFileLoader extends FileLoader } foreach ($service as $key => $value) { - if (!\in_array($key, array('alias', 'public'))) { + if (!\in_array($key, ['alias', 'public'])) { throw new InvalidArgumentException(sprintf('The configuration key "%s" is unsupported for the service "%s" which is defined as an alias in "%s". Allowed configuration keys for service aliases are "alias" and "public".', $key, $id, $file)); } } @@ -396,7 +396,7 @@ class YamlFileLoader extends FileLoader $definition->setAutoconfigured($defaults['autoconfigure']); } - $definition->setChanges(array()); + $definition->setChanges([]); } if (isset($service['class'])) { @@ -414,7 +414,7 @@ class YamlFileLoader extends FileLoader if (isset($service['lazy'])) { $definition->setLazy((bool) $service['lazy']); if (\is_string($service['lazy'])) { - $definition->addTag('proxy', array('interface' => $service['lazy'])); + $definition->addTag('proxy', ['interface' => $service['lazy']]); } } @@ -458,10 +458,10 @@ class YamlFileLoader extends FileLoader foreach ($service['calls'] as $call) { if (isset($call['method'])) { $method = $call['method']; - $args = isset($call['arguments']) ? $this->resolveServices($call['arguments'], $file) : array(); + $args = isset($call['arguments']) ? $this->resolveServices($call['arguments'], $file) : []; } else { $method = $call[0]; - $args = isset($call[1]) ? $this->resolveServices($call[1], $file) : array(); + $args = isset($call[1]) ? $this->resolveServices($call[1], $file) : []; } if (!\is_array($args)) { @@ -471,7 +471,7 @@ class YamlFileLoader extends FileLoader } } - $tags = isset($service['tags']) ? $service['tags'] : array(); + $tags = isset($service['tags']) ? $service['tags'] : []; if (!\is_array($tags)) { throw new InvalidArgumentException(sprintf('Parameter "tags" must be an array for service "%s" in %s. Check your YAML syntax.', $id, $file)); } @@ -482,7 +482,7 @@ class YamlFileLoader extends FileLoader foreach ($tags as $tag) { if (!\is_array($tag)) { - $tag = array('name' => $tag); + $tag = ['name' => $tag]; } if (!isset($tag['name'])) { @@ -520,7 +520,7 @@ class YamlFileLoader extends FileLoader if (isset($defaults['bind']) || isset($service['bind'])) { // deep clone, to avoid multiple process of the same instance in the passes - $bindings = isset($defaults['bind']) ? unserialize(serialize($defaults['bind'])) : array(); + $bindings = isset($defaults['bind']) ? unserialize(serialize($defaults['bind'])) : []; if (isset($service['bind'])) { if (!\is_array($service['bind'])) { @@ -579,7 +579,7 @@ class YamlFileLoader extends FileLoader if (false !== strpos($callable, ':') && false === strpos($callable, '::')) { $parts = explode(':', $callable); - return array($this->resolveServices('@'.$parts[0], $file), $parts[1]); + return [$this->resolveServices('@'.$parts[0], $file), $parts[1]]; } return $callable; @@ -587,7 +587,7 @@ class YamlFileLoader extends FileLoader if (\is_array($callable)) { if (isset($callable[0]) && isset($callable[1])) { - return array($this->resolveServices($callable[0], $file), $callable[1]); + return [$this->resolveServices($callable[0], $file), $callable[1]]; } if ('factory' === $parameter && isset($callable[1]) && null === $callable[0]) { @@ -657,7 +657,7 @@ class YamlFileLoader extends FileLoader } foreach ($content as $namespace => $data) { - if (\in_array($namespace, array('imports', 'parameters', 'services'))) { + if (\in_array($namespace, ['imports', 'parameters', 'services'])) { continue; } @@ -720,10 +720,10 @@ class YamlFileLoader extends FileLoader $isLoadingInstanceof = $this->isLoadingInstanceof; $this->isLoadingInstanceof = false; $instanceof = $this->instanceof; - $this->instanceof = array(); + $this->instanceof = []; $id = sprintf('.%d_%s', ++$this->anonymousServicesCount, preg_replace('/^.*\\\\/', '', isset($argument['class']) ? $argument['class'] : '').$this->anonymousServicesSuffix); - $this->parseDefinition($id, $argument, $file, array()); + $this->parseDefinition($id, $argument, $file, []); if (!$this->container->hasDefinition($id)) { throw new InvalidArgumentException(sprintf('Creating an alias using the tag "!service" is not allowed in "%s".', $file)); @@ -779,12 +779,12 @@ class YamlFileLoader extends FileLoader private function loadFromExtensions(array $content) { foreach ($content as $namespace => $values) { - if (\in_array($namespace, array('imports', 'parameters', 'services'))) { + if (\in_array($namespace, ['imports', 'parameters', 'services'])) { continue; } if (!\is_array($values) && null !== $values) { - $values = array(); + $values = []; } $this->container->loadFromExtension($namespace, $values); diff --git a/src/Symfony/Component/DependencyInjection/ServiceLocator.php b/src/Symfony/Component/DependencyInjection/ServiceLocator.php index 9261c6546f..45a3524135 100644 --- a/src/Symfony/Component/DependencyInjection/ServiceLocator.php +++ b/src/Symfony/Component/DependencyInjection/ServiceLocator.php @@ -79,14 +79,14 @@ class ServiceLocator implements PsrContainerInterface if ($this->loading) { $msg = sprintf('The service "%s" has a dependency on a non-existent service "%s". This locator %s', end($this->loading), $id, $this->formatAlternatives()); - return new ServiceNotFoundException($id, end($this->loading) ?: null, null, array(), $msg); + return new ServiceNotFoundException($id, end($this->loading) ?: null, null, [], $msg); } $class = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT | DEBUG_BACKTRACE_IGNORE_ARGS, 4); $class = isset($class[3]['object']) ? \get_class($class[3]['object']) : null; $externalId = $this->externalId ?: $class; - $msg = array(); + $msg = []; $msg[] = sprintf('Service "%s" not found:', $id); if (!$this->container) { @@ -119,7 +119,7 @@ class ServiceLocator implements PsrContainerInterface $msg[] = 'Try using dependency injection instead.'; } - return new ServiceNotFoundException($id, end($this->loading) ?: null, null, array(), implode(' ', $msg)); + return new ServiceNotFoundException($id, end($this->loading) ?: null, null, [], implode(' ', $msg)); } private function createCircularReferenceException(string $id, array $path): ContainerExceptionInterface diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/AnalyzeServiceReferencesPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/AnalyzeServiceReferencesPassTest.php index 3cf23aa119..48c3df595c 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/AnalyzeServiceReferencesPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/AnalyzeServiceReferencesPassTest.php @@ -31,7 +31,7 @@ class AnalyzeServiceReferencesPassTest extends TestCase $b = $container ->register('b') - ->addMethodCall('setA', array($ref2 = new Reference('a'))) + ->addMethodCall('setA', [$ref2 = new Reference('a')]) ; $c = $container @@ -47,7 +47,7 @@ class AnalyzeServiceReferencesPassTest extends TestCase $e = $container ->register('e') - ->setConfigurator(array($ref6 = new Reference('b'), 'methodName')) + ->setConfigurator([$ref6 = new Reference('b'), 'methodName']) ; $graph = $this->process($container); @@ -93,7 +93,7 @@ class AnalyzeServiceReferencesPassTest extends TestCase $container ->register('c') ->addArgument($ref1 = new Reference('a')) - ->addArgument(new IteratorArgument(array($ref2 = new Reference('b')))) + ->addArgument(new IteratorArgument([$ref2 = new Reference('b')])) ; $graph = $this->process($container); @@ -118,7 +118,7 @@ class AnalyzeServiceReferencesPassTest extends TestCase $container ->register('b') - ->addArgument(new Definition(null, array($ref = new Reference('a')))) + ->addArgument(new Definition(null, [$ref = new Reference('a')])) ; $graph = $this->process($container); @@ -137,7 +137,7 @@ class AnalyzeServiceReferencesPassTest extends TestCase $container ->register('b') - ->addArgument(new IteratorArgument(array($ref = new Reference('a')))) + ->addArgument(new IteratorArgument([$ref = new Reference('a')])) ; $graph = $this->process($container); @@ -155,7 +155,7 @@ class AnalyzeServiceReferencesPassTest extends TestCase ; $factory = new Definition(); - $factory->setFactory(array(new Reference('a'), 'a')); + $factory->setFactory([new Reference('a'), 'a']); $container ->register('b') @@ -177,8 +177,8 @@ class AnalyzeServiceReferencesPassTest extends TestCase ; $container ->register('b') - ->addArgument(new Definition(null, array($ref1 = new Reference('a')))) - ->addArgument(new Definition(null, array($ref2 = new Reference('a')))) + ->addArgument(new Definition(null, [$ref1 = new Reference('a')])) + ->addArgument(new Definition(null, [$ref2 = new Reference('a')])) ; $graph = $this->process($container); @@ -192,11 +192,11 @@ class AnalyzeServiceReferencesPassTest extends TestCase $container ->register('foo', 'stdClass') - ->setFactory(array('stdClass', 'getInstance')); + ->setFactory(['stdClass', 'getInstance']); $container ->register('bar', 'stdClass') - ->setFactory(array(new Reference('foo'), 'getInstance')); + ->setFactory([new Reference('foo'), 'getInstance']); $graph = $this->process($container); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutowirePassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutowirePassTest.php index eacdefbdcf..558d6412a8 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutowirePassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/AutowirePassTest.php @@ -924,12 +924,12 @@ class AutowirePassTest extends TestCase $pass->process($container); - $expected = array( - array( + $expected = [ + [ 'setMultipleInstancesForOneArg', - array(new TypedReference(CollisionInterface::class.' $collision', CollisionInterface::class)), - ), - ); + [new TypedReference(CollisionInterface::class.' $collision', CollisionInterface::class)], + ], + ]; $this->assertEquals($expected, $container->getDefinition('setter_injection_collision')->getMethodCalls()); } } diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php index 3cef020f30..baedabf8d4 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php @@ -93,7 +93,7 @@ class CheckExceptionOnInvalidReferenceBehaviorPassTest extends TestCase { $container = new ContainerBuilder(); - ServiceLocatorTagPass::register($container, array('foo' => new Reference('baz')), 'bar'); + ServiceLocatorTagPass::register($container, ['foo' => new Reference('baz')], 'bar'); (new AnalyzeServiceReferencesPass())->process($container); (new InlineServiceDefinitionsPass())->process($container); @@ -108,7 +108,7 @@ class CheckExceptionOnInvalidReferenceBehaviorPassTest extends TestCase { $container = new ContainerBuilder(); - ServiceLocatorTagPass::register($container, array('foo' => new Reference('foo')), 'bar'); + ServiceLocatorTagPass::register($container, ['foo' => new Reference('foo')], 'bar'); (new AnalyzeServiceReferencesPass())->process($container); (new InlineServiceDefinitionsPass())->process($container); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CustomExpressionLanguageFunctionTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CustomExpressionLanguageFunctionTest.php index ead0a4207a..13e898a867 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/CustomExpressionLanguageFunctionTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/CustomExpressionLanguageFunctionTest.php @@ -16,14 +16,14 @@ class CustomExpressionLanguageFunctionTest extends TestCase $container = new ContainerBuilder(); $container->register('test', 'stdClass') ->setPublic(true) - ->setArguments(array(new Expression('custom_func("foobar")'))); + ->setArguments([new Expression('custom_func("foobar")')]); $container->addExpressionLanguageProvider(new class() implements ExpressionFunctionProviderInterface { public function getFunctions() { - return array( + return [ ExpressionFunction::fromPhp('strtolower', 'custom_func'), - ); + ]; } }); $container->compile(); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/InlineServiceDefinitionsPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/InlineServiceDefinitionsPassTest.php index 595beb7e97..61df0ebfa5 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/InlineServiceDefinitionsPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/InlineServiceDefinitionsPassTest.php @@ -32,7 +32,7 @@ class InlineServiceDefinitionsPassTest extends TestCase $container ->register('service') - ->setArguments(array(new Reference('inlinable.service'))) + ->setArguments([new Reference('inlinable.service')]) ; $this->process($container); @@ -54,7 +54,7 @@ class InlineServiceDefinitionsPassTest extends TestCase $container ->register('service') - ->setArguments(array($ref = new Reference('foo'))) + ->setArguments([$ref = new Reference('foo')]) ; $this->process($container); @@ -79,7 +79,7 @@ class InlineServiceDefinitionsPassTest extends TestCase $container ->register('service') - ->setArguments(array(new Reference('foo'), $ref = new Reference('moo'), new Reference('bar'))) + ->setArguments([new Reference('foo'), $ref = new Reference('moo'), new Reference('bar')]) ; $this->process($container); @@ -104,7 +104,7 @@ class InlineServiceDefinitionsPassTest extends TestCase $container ->register('bar') ->setPublic(false) - ->addMethodCall('setFoo', array(new Reference('foo'))) + ->addMethodCall('setFoo', [new Reference('foo')]) ; $this->process($container); @@ -127,7 +127,7 @@ class InlineServiceDefinitionsPassTest extends TestCase $container ->register('bar') ->setShared(false) - ->addMethodCall('setFoo', array(new Reference('foo'))) + ->addMethodCall('setFoo', [new Reference('foo')]) ; $this->process($container); @@ -174,7 +174,7 @@ class InlineServiceDefinitionsPassTest extends TestCase $b = $container ->register('b') ->addArgument(new Reference('a')) - ->addArgument(new Definition(null, array(new Reference('a')))) + ->addArgument(new Definition(null, [new Reference('a')])) ; $this->process($container); @@ -194,14 +194,14 @@ class InlineServiceDefinitionsPassTest extends TestCase $b = $container ->register('b') ->setPublic(false) - ->setFactory(array(new Reference('a'), 'a')) + ->setFactory([new Reference('a'), 'a']) ; $container ->register('foo') - ->setArguments(array( + ->setArguments([ $ref = new Reference('b'), - )); + ]); $this->process($container); @@ -218,15 +218,15 @@ class InlineServiceDefinitionsPassTest extends TestCase $container ->register('b') ->setPublic(false) - ->setFactory(array(new Reference('a'), 'a')) + ->setFactory([new Reference('a'), 'a']) ; $container ->register('foo') - ->setArguments(array( + ->setArguments([ $ref1 = new Reference('b'), $ref2 = new Reference('b'), - )) + ]) ; $this->process($container); @@ -244,19 +244,19 @@ class InlineServiceDefinitionsPassTest extends TestCase $container ->register('b') ->setPublic(false) - ->setFactory(array(new Reference('a'), 'a')) + ->setFactory([new Reference('a'), 'a']) ; $inlineFactory = new Definition(); $inlineFactory->setPublic(false); - $inlineFactory->setFactory(array(new Reference('b'), 'b')); + $inlineFactory->setFactory([new Reference('b'), 'b']); $container ->register('foo') - ->setArguments(array( + ->setArguments([ $ref = new Reference('b'), $inlineFactory, - )) + ]) ; $this->process($container); @@ -275,7 +275,7 @@ class InlineServiceDefinitionsPassTest extends TestCase $container ->register('service') - ->setArguments(array($ref = new Reference('foo'))) + ->setArguments([$ref = new Reference('foo')]) ; $this->process($container); @@ -290,7 +290,7 @@ class InlineServiceDefinitionsPassTest extends TestCase $container ->register('foo') ->setPublic(false) - ->addMethodCall('foo', array($ref = new Reference('foo'))) + ->addMethodCall('foo', [$ref = new Reference('foo')]) ; $this->process($container); @@ -308,11 +308,11 @@ class InlineServiceDefinitionsPassTest extends TestCase ; $container ->register('service-closure') - ->setArguments(array(new ServiceClosureArgument(new Reference('inline')))) + ->setArguments([new ServiceClosureArgument(new Reference('inline'))]) ; $container ->register('iterator') - ->setArguments(array(new IteratorArgument(array(new Reference('inline'))))) + ->setArguments([new IteratorArgument([new Reference('inline')])]) ; $this->process($container); diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/RegisterEnvVarProcessorsPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/RegisterEnvVarProcessorsPassTest.php index 4681092ca7..ff938ce01b 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/RegisterEnvVarProcessorsPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/RegisterEnvVarProcessorsPassTest.php @@ -28,20 +28,20 @@ class RegisterEnvVarProcessorsPassTest extends TestCase $this->assertTrue($container->has('container.env_var_processors_locator')); $this->assertInstanceOf(SimpleProcessor::class, $container->get('container.env_var_processors_locator')->get('foo')); - $expected = array( - 'foo' => array('string'), - 'base64' => array('string'), - 'bool' => array('bool'), - 'const' => array('bool', 'int', 'float', 'string', 'array'), - 'csv' => array('array'), - 'file' => array('string'), - 'float' => array('float'), - 'int' => array('int'), - 'json' => array('array'), - 'key' => array('bool', 'int', 'float', 'string', 'array'), - 'resolve' => array('string'), - 'string' => array('string'), - ); + $expected = [ + 'foo' => ['string'], + 'base64' => ['string'], + 'bool' => ['bool'], + 'const' => ['bool', 'int', 'float', 'string', 'array'], + 'csv' => ['array'], + 'file' => ['string'], + 'float' => ['float'], + 'int' => ['int'], + 'json' => ['array'], + 'key' => ['bool', 'int', 'float', 'string', 'array'], + 'resolve' => ['string'], + 'string' => ['string'], + ]; $this->assertSame($expected, $container->getParameterBag()->getProvidedTypes()); } @@ -77,7 +77,7 @@ class SimpleProcessor implements EnvVarProcessorInterface public static function getProvidedTypes() { - return array('foo' => 'string'); + return ['foo' => 'string']; } } @@ -85,6 +85,6 @@ class BadProcessor extends SimpleProcessor { public static function getProvidedTypes() { - return array('foo' => 'string|foo'); + return ['foo' => 'string|foo']; } } diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/RegisterServiceSubscribersPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/RegisterServiceSubscribersPassTest.php index d520c69cca..e501d1fca3 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/RegisterServiceSubscribersPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/RegisterServiceSubscribersPassTest.php @@ -61,7 +61,7 @@ class RegisterServiceSubscribersPassTest extends TestCase $container = new ContainerBuilder(); $container->register('foo', TestServiceSubscriber::class) - ->addTag('container.service_subscriber', array('bar' => '123')) + ->addTag('container.service_subscriber', ['bar' => '123']) ; (new RegisterServiceSubscribersPass())->process($container); @@ -86,12 +86,12 @@ class RegisterServiceSubscribersPassTest extends TestCase $this->assertFalse($locator->isPublic()); $this->assertSame(ServiceLocator::class, $locator->getClass()); - $expected = array( + $expected = [ TestServiceSubscriber::class => new ServiceClosureArgument(new TypedReference(TestServiceSubscriber::class, TestServiceSubscriber::class)), CustomDefinition::class => new ServiceClosureArgument(new TypedReference(CustomDefinition::class, CustomDefinition::class, ContainerInterface::IGNORE_ON_INVALID_REFERENCE)), 'bar' => new ServiceClosureArgument(new TypedReference(CustomDefinition::class, CustomDefinition::class, ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, 'bar')), 'baz' => new ServiceClosureArgument(new TypedReference(CustomDefinition::class, CustomDefinition::class, ContainerInterface::IGNORE_ON_INVALID_REFERENCE, 'baz')), - ); + ]; $this->assertEquals($expected, $container->getDefinition((string) $locator->getFactory()[0])->getArgument(0)); } @@ -103,8 +103,8 @@ class RegisterServiceSubscribersPassTest extends TestCase $container->register('foo', TestServiceSubscriber::class) ->setAutowired(true) ->addArgument(new Reference(PsrContainerInterface::class)) - ->addTag('container.service_subscriber', array('key' => 'bar', 'id' => 'bar')) - ->addTag('container.service_subscriber', array('key' => 'bar', 'id' => 'baz')) // should be ignored: the first wins + ->addTag('container.service_subscriber', ['key' => 'bar', 'id' => 'bar']) + ->addTag('container.service_subscriber', ['key' => 'bar', 'id' => 'baz']) // should be ignored: the first wins ; (new RegisterServiceSubscribersPass())->process($container); @@ -116,12 +116,12 @@ class RegisterServiceSubscribersPassTest extends TestCase $this->assertFalse($locator->isPublic()); $this->assertSame(ServiceLocator::class, $locator->getClass()); - $expected = array( + $expected = [ TestServiceSubscriber::class => new ServiceClosureArgument(new TypedReference(TestServiceSubscriber::class, TestServiceSubscriber::class)), CustomDefinition::class => new ServiceClosureArgument(new TypedReference(CustomDefinition::class, CustomDefinition::class, ContainerInterface::IGNORE_ON_INVALID_REFERENCE)), 'bar' => new ServiceClosureArgument(new TypedReference('bar', CustomDefinition::class, ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, 'bar')), 'baz' => new ServiceClosureArgument(new TypedReference(CustomDefinition::class, CustomDefinition::class, ContainerInterface::IGNORE_ON_INVALID_REFERENCE, 'baz')), - ); + ]; $this->assertEquals($expected, $container->getDefinition((string) $locator->getFactory()[0])->getArgument(0)); } @@ -136,10 +136,10 @@ class RegisterServiceSubscribersPassTest extends TestCase $container->register('foo_service', TestServiceSubscriber::class) ->setAutowired(true) ->addArgument(new Reference(PsrContainerInterface::class)) - ->addTag('container.service_subscriber', array( + ->addTag('container.service_subscriber', [ 'key' => 'test', 'id' => TestServiceSubscriber::class, - )) + ]) ; $container->register(TestServiceSubscriber::class, TestServiceSubscriber::class); $container->compile(); @@ -150,7 +150,7 @@ class RegisterServiceSubscribersPassTest extends TestCase $container = new ContainerBuilder(); $container->register('foo', TestServiceSubscriberChild::class) - ->addMethodCall('setContainer', array(new Reference(PsrContainerInterface::class))) + ->addMethodCall('setContainer', [new Reference(PsrContainerInterface::class)]) ->addTag('container.service_subscriber') ; @@ -160,12 +160,12 @@ class RegisterServiceSubscribersPassTest extends TestCase $foo = $container->getDefinition('foo'); $locator = $container->getDefinition((string) $foo->getMethodCalls()[0][1][0]); - $expected = array( + $expected = [ TestServiceSubscriberChild::class.'::invalidDefinition' => new ServiceClosureArgument(new TypedReference('Symfony\Component\DependencyInjection\Tests\Fixtures\InvalidDefinition', 'Symfony\Component\DependencyInjection\Tests\Fixtures\InvalidDefinition', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)), TestServiceSubscriberChild::class.'::testDefinition2' => new ServiceClosureArgument(new TypedReference(TestDefinition2::class, TestDefinition2::class, ContainerInterface::IGNORE_ON_INVALID_REFERENCE)), TestServiceSubscriberChild::class.'::testDefinition3' => new ServiceClosureArgument(new TypedReference(TestDefinition3::class, TestDefinition3::class, ContainerInterface::IGNORE_ON_INVALID_REFERENCE)), TestServiceSubscriberParent::class.'::testDefinition1' => new ServiceClosureArgument(new TypedReference(TestDefinition1::class, TestDefinition1::class, ContainerInterface::IGNORE_ON_INVALID_REFERENCE)), - ); + ]; $this->assertEquals($expected, $container->getDefinition((string) $locator->getFactory()[0])->getArgument(0)); } @@ -182,7 +182,7 @@ class RegisterServiceSubscribersPassTest extends TestCase } }; $container->register('foo', \get_class($subscriber)) - ->addMethodCall('setContainer', array(new Reference(PsrContainerInterface::class))) + ->addMethodCall('setContainer', [new Reference(PsrContainerInterface::class)]) ->addTag('container.service_subscriber'); (new RegisterServiceSubscribersPass())->process($container); @@ -191,9 +191,9 @@ class RegisterServiceSubscribersPassTest extends TestCase $foo = $container->getDefinition('foo'); $locator = $container->getDefinition((string) $foo->getMethodCalls()[0][1][0]); - $expected = array( + $expected = [ \get_class($subscriber).'::getFoo' => new ServiceClosureArgument(new TypedReference('stdClass', 'stdClass', ContainerInterface::IGNORE_ON_INVALID_REFERENCE, 'foo')), - ); + ]; $this->assertEquals($expected, $container->getDefinition((string) $locator->getFactory()[0])->getArgument(0)); } @@ -204,11 +204,11 @@ class RegisterServiceSubscribersPassTest extends TestCase $subscriber = new class() implements ServiceSubscriberInterface { public static function getSubscribedServices() { - return array( + return [ 'some.service' => 'stdClass', 'some_service' => 'stdClass', 'another_service' => 'stdClass', - ); + ]; } }; $container->register('some.service', 'stdClass'); @@ -216,7 +216,7 @@ class RegisterServiceSubscribersPassTest extends TestCase $container->setAlias('stdClass $some_service', 'some.service'); $container->setAlias('stdClass $anotherService', 'some.service'); $container->register('foo', \get_class($subscriber)) - ->addMethodCall('setContainer', array(new Reference(PsrContainerInterface::class))) + ->addMethodCall('setContainer', [new Reference(PsrContainerInterface::class)]) ->addTag('container.service_subscriber'); (new RegisterServiceSubscribersPass())->process($container); @@ -225,20 +225,20 @@ class RegisterServiceSubscribersPassTest extends TestCase $foo = $container->getDefinition('foo'); $locator = $container->getDefinition((string) $foo->getMethodCalls()[0][1][0]); - $expected = array( + $expected = [ 'some.service' => new ServiceClosureArgument(new TypedReference('stdClass', 'stdClass', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, 'some.service')), 'some_service' => new ServiceClosureArgument(new TypedReference('stdClass', 'stdClass', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, 'some_service')), 'another_service' => new ServiceClosureArgument(new TypedReference('stdClass', 'stdClass', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, 'anotherService')), - ); + ]; $this->assertEquals($expected, $container->getDefinition((string) $locator->getFactory()[0])->getArgument(0)); (new AutowirePass())->process($container); - $expected = array( + $expected = [ 'some.service' => new ServiceClosureArgument(new TypedReference('some.service', 'stdClass')), 'some_service' => new ServiceClosureArgument(new TypedReference('stdClass $some_service', 'stdClass')), 'another_service' => new ServiceClosureArgument(new TypedReference('stdClass $anotherService', 'stdClass')), - ); + ]; $this->assertEquals($expected, $container->getDefinition((string) $locator->getFactory()[0])->getArgument(0)); } } diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/RemoveUnusedDefinitionsPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/RemoveUnusedDefinitionsPassTest.php index 48b3139589..8b92a33e23 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/RemoveUnusedDefinitionsPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/RemoveUnusedDefinitionsPassTest.php @@ -33,7 +33,7 @@ class RemoveUnusedDefinitionsPassTest extends TestCase ; $container ->register('moo') - ->setArguments(array(new Reference('bar'))) + ->setArguments([new Reference('bar')]) ; $this->process($container); @@ -52,7 +52,7 @@ class RemoveUnusedDefinitionsPassTest extends TestCase ; $container ->register('bar') - ->setArguments(array(new Reference('foo'))) + ->setArguments([new Reference('foo')]) ->setPublic(false) ; @@ -71,7 +71,7 @@ class RemoveUnusedDefinitionsPassTest extends TestCase ; $container ->register('bar') - ->setArguments(array(new Definition(null, array(new Reference('foo'))))) + ->setArguments([new Definition(null, [new Reference('foo')])]) ; $this->process($container); @@ -86,12 +86,12 @@ class RemoveUnusedDefinitionsPassTest extends TestCase $container ->register('foo', 'stdClass') - ->setFactory(array('stdClass', 'getInstance')) + ->setFactory(['stdClass', 'getInstance']) ->setPublic(false); $container ->register('bar', 'stdClass') - ->setFactory(array(new Reference('foo'), 'getInstance')) + ->setFactory([new Reference('foo'), 'getInstance']) ->setPublic(false); $container @@ -111,7 +111,7 @@ class RemoveUnusedDefinitionsPassTest extends TestCase $container->setParameter('env(FOOBAR)', 'test'); $container ->register('foo') - ->setArguments(array('%env(FOOBAR)%')) + ->setArguments(['%env(FOOBAR)%']) ->setPublic(false) ; diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveBindingsPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveBindingsPassTest.php index 8d29a2b43c..43dcb4f8f1 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveBindingsPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveBindingsPassTest.php @@ -116,10 +116,10 @@ class ResolveBindingsPassTest extends TestCase { $container = new ContainerBuilder(); - $bindings = array( + $bindings = [ '$c' => new BoundArgument(new Reference('bar')), CaseSensitiveClass::class.'$c' => new BoundArgument(new Reference('foo')), - ); + ]; $definition = $container->register(NamedArgumentsDummy::class, NamedArgumentsDummy::class); $definition->addMethodCall('setSensitiveClass'); @@ -129,10 +129,10 @@ class ResolveBindingsPassTest extends TestCase $pass = new ResolveBindingsPass(); $pass->process($container); - $expected = array( - array('setSensitiveClass', array(new Reference('foo'))), - array('setAnotherC', array(new Reference('bar'))), - ); + $expected = [ + ['setSensitiveClass', [new Reference('foo')]], + ['setAnotherC', [new Reference('bar')]], + ]; $this->assertEquals($expected, $definition->getMethodCalls()); } } diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveInstanceofConditionalsPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveInstanceofConditionalsPassTest.php index d6f2d6b789..88cc88b9dc 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveInstanceofConditionalsPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveInstanceofConditionalsPassTest.php @@ -276,21 +276,21 @@ class ResolveInstanceofConditionalsPassTest extends TestCase $container = new ContainerBuilder(); $container->registerForAutoconfiguration(self::class) - ->setBindings(array( + ->setBindings([ '$foo' => new BoundArgument(234, false), parent::class => new BoundArgument(new Reference('foo'), false), - )); + ]); $container->register('foo', self::class) ->setAutoconfigured(true) - ->setBindings(array('$foo' => new BoundArgument(123, false))); + ->setBindings(['$foo' => new BoundArgument(123, false)]); (new ResolveInstanceofConditionalsPass())->process($container); - $expected = array( + $expected = [ '$foo' => new BoundArgument(123, false), parent::class => new BoundArgument(new Reference('foo'), false), - ); + ]; $this->assertEquals($expected, $container->findDefinition('foo')->getBindings()); } diff --git a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ServiceLocatorTagPassTest.php b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ServiceLocatorTagPassTest.php index 5157e84acf..d7e5586e0a 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Compiler/ServiceLocatorTagPassTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Compiler/ServiceLocatorTagPassTest.php @@ -48,9 +48,9 @@ class ServiceLocatorTagPassTest extends TestCase $container = new ContainerBuilder(); $container->register('foo', ServiceLocator::class) - ->setArguments(array(array( + ->setArguments([[ 'dummy', - ))) + ]]) ->addTag('container.service_locator') ; @@ -65,11 +65,11 @@ class ServiceLocatorTagPassTest extends TestCase $container->register('baz', CustomDefinition::class); $container->register('foo', ServiceLocator::class) - ->setArguments(array(array( + ->setArguments([[ new Reference('bar'), new Reference('baz'), 'some.service' => new Reference('bar'), - ))) + ]]) ->addTag('container.service_locator') ; @@ -91,10 +91,10 @@ class ServiceLocatorTagPassTest extends TestCase $container->register('baz', TestDefinition2::class); $container->register('foo', ServiceLocator::class) - ->setArguments(array(array( + ->setArguments([[ new Reference('bar'), 'bar' => new Reference('baz'), - ))) + ]]) ->addTag('container.service_locator') ; @@ -114,10 +114,10 @@ class ServiceLocatorTagPassTest extends TestCase $container->register('baz', TestDefinition2::class); $container->register('foo', ServiceLocator::class) - ->setArguments(array(array( + ->setArguments([[ 'bar' => new Reference('baz'), new Reference('bar'), - ))) + ]]) ->addTag('container.service_locator') ; diff --git a/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php b/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php index 200f84bee6..b4acc949c2 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php @@ -1086,7 +1086,7 @@ class PhpDumperTest extends TestCase $container = include self::$fixturesPath.'/containers/container_service_locator_argument.php'; $container->compile(); $dumper = new PhpDumper($container); - $dump = $dumper->dump(array('class' => 'Symfony_DI_PhpDumper_Service_Locator_Argument')); + $dump = $dumper->dump(['class' => 'Symfony_DI_PhpDumper_Service_Locator_Argument']); $this->assertStringEqualsFile(self::$fixturesPath.'/php/services_service_locator_argument.php', str_replace(str_replace('\\', '\\\\', self::$fixturesPath.\DIRECTORY_SEPARATOR.'includes'.\DIRECTORY_SEPARATOR), '%path%', $dump)); eval('?>'.$dump); diff --git a/src/Symfony/Component/DependencyInjection/Tests/EnvVarProcessorTest.php b/src/Symfony/Component/DependencyInjection/Tests/EnvVarProcessorTest.php index 04f8a7f163..8a70509482 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/EnvVarProcessorTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/EnvVarProcessorTest.php @@ -346,12 +346,12 @@ class EnvVarProcessorTest extends TestCase public function noArrayValues() { - return array( - array(null), - array('string'), - array(1), - array(true), - ); + return [ + [null], + ['string'], + [1], + [true], + ]; } /** @@ -372,11 +372,11 @@ class EnvVarProcessorTest extends TestCase public function invalidArrayValues() { - return array( - array(array()), - array(array('index2' => 'value')), - array(array('index', 'index2')), - ); + return [ + [[]], + [['index2' => 'value']], + [['index', 'index2']], + ]; } /** @@ -395,17 +395,17 @@ class EnvVarProcessorTest extends TestCase public function arrayValues() { - return array( - array(array('index' => 'password')), - array(array('index' => 'true')), - array(array('index' => false)), - array(array('index' => '1')), - array(array('index' => 1)), - array(array('index' => '1.1')), - array(array('index' => 1.1)), - array(array('index' => array())), - array(array('index' => array('val1', 'val2'))), - ); + return [ + [['index' => 'password']], + [['index' => 'true']], + [['index' => false]], + [['index' => '1']], + [['index' => 1]], + [['index' => '1.1']], + [['index' => 1.1]], + [['index' => []]], + [['index' => ['val1', 'val2']]], + ]; } public function testGetEnvKeyChained() @@ -415,9 +415,9 @@ class EnvVarProcessorTest extends TestCase $this->assertSame('password', $processor->getEnv('key', 'index:file:foo', function ($name) { $this->assertSame('file:foo', $name); - return array( + return [ 'index' => 'password', - ); + ]; })); } } diff --git a/src/Symfony/Component/DependencyInjection/Tests/Loader/FileLoaderTest.php b/src/Symfony/Component/DependencyInjection/Tests/Loader/FileLoaderTest.php index 87971eadd8..b94ee1953f 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Loader/FileLoaderTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Loader/FileLoaderTest.php @@ -46,21 +46,21 @@ class FileLoaderTest extends TestCase $container = new ContainerBuilder(); $loader = new TestFileLoader($container, new FileLocator(self::$fixturesPath)); - $resolver = new LoaderResolver(array( + $resolver = new LoaderResolver([ new IniFileLoader($container, new FileLocator(self::$fixturesPath.'/ini')), new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')), new PhpFileLoader($container, new FileLocator(self::$fixturesPath.'/php')), new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')), - )); + ]); $loader->setResolver($resolver); $loader->import('{F}ixtures/{xml,yaml}/services2.{yml,xml}'); $actual = $container->getParameterBag()->all(); - $expected = array( + $expected = [ 'a string', 'foo' => 'bar', - 'values' => array( + 'values' => [ 0, 'integer' => 4, 100 => null, @@ -72,14 +72,14 @@ class FileLoaderTest extends TestCase 'float' => 1.3, 1000.3, 'a string', - array('foo', 'bar'), - ), - 'mixedcase' => array('MixedCaseKey' => 'value'), + ['foo', 'bar'], + ], + 'mixedcase' => ['MixedCaseKey' => 'value'], 'constant' => PHP_EOL, 'bar' => '%foo%', 'escape' => '@escapeme', 'foo_bar' => new Reference('foo_bar'), - ); + ]; $this->assertEquals(array_keys($expected), array_keys($actual), '->load() imports and merges imported files'); } @@ -93,15 +93,15 @@ class FileLoaderTest extends TestCase $loader->registerClasses(new Definition(), 'Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\Sub\\', 'Prototype/%sub_dir%/*'); $this->assertEquals( - array('service_container', Bar::class), + ['service_container', Bar::class], array_keys($container->getDefinitions()) ); $this->assertEquals( - array( + [ PsrContainerInterface::class, ContainerInterface::class, BarInterface::class, - ), + ], array_keys($container->getAliases()) ); } @@ -126,11 +126,11 @@ class FileLoaderTest extends TestCase $this->assertFalse($container->has(DeeperBaz::class)); $this->assertEquals( - array( + [ PsrContainerInterface::class, ContainerInterface::class, BarInterface::class, - ), + ], array_keys($container->getAliases()) ); } @@ -143,10 +143,10 @@ class FileLoaderTest extends TestCase $loader->registerClasses( new Definition(), 'Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\\', - 'Prototype/*', array( + 'Prototype/*', [ 'Prototype/%sub_dir%', 'Prototype/OtherDir/AnotherSub/DeeperBaz.php', - ) + ] ); $this->assertTrue($container->has(Foo::class)); $this->assertTrue($container->has(Baz::class)); @@ -168,11 +168,11 @@ class FileLoaderTest extends TestCase $this->assertTrue($container->has(Foo::class)); $this->assertEquals( - array( + [ PsrContainerInterface::class, ContainerInterface::class, FooInterface::class, - ), + ], array_keys($container->getAliases()) ); @@ -197,7 +197,7 @@ class FileLoaderTest extends TestCase $this->assertTrue($container->has(MissingParent::class)); $this->assertSame( - array('While discovering services from namespace "Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\BadClasses\", an error was thrown when processing the class "Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\BadClasses\MissingParent": "Class Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\BadClasses\MissingClass not found".'), + ['While discovering services from namespace "Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\BadClasses\", an error was thrown when processing the class "Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\BadClasses\MissingParent": "Class Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\BadClasses\MissingClass not found".'], $container->getDefinition(MissingParent::class)->getErrors() ); } diff --git a/src/Symfony/Component/DependencyInjection/Tests/Loader/PhpFileLoaderTest.php b/src/Symfony/Component/DependencyInjection/Tests/Loader/PhpFileLoaderTest.php index 5a54688089..48791706a7 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Loader/PhpFileLoaderTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Loader/PhpFileLoaderTest.php @@ -67,16 +67,16 @@ class PhpFileLoaderTest extends TestCase public function provideConfig() { - yield array('basic'); - yield array('object'); - yield array('defaults'); - yield array('instanceof'); - yield array('prototype'); - yield array('prototype_array'); - yield array('child'); - yield array('php7'); - yield array('anonymous'); - yield array('lazy_fqcn'); + yield ['basic']; + yield ['object']; + yield ['defaults']; + yield ['instanceof']; + yield ['prototype']; + yield ['prototype_array']; + yield ['child']; + yield ['php7']; + yield ['anonymous']; + yield ['lazy_fqcn']; } /** diff --git a/src/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.php b/src/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.php index 330461c7ed..6d9634c66c 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.php @@ -619,10 +619,10 @@ class XmlFileLoaderTest extends TestCase '/*', true, false, - array( + [ str_replace(\DIRECTORY_SEPARATOR, '/', $prototypeRealPath.\DIRECTORY_SEPARATOR.'OtherDir') => true, str_replace(\DIRECTORY_SEPARATOR, '/', $prototypeRealPath.\DIRECTORY_SEPARATOR.'BadClasses') => true, - ) + ] ); $this->assertContains((string) $globResource, $resources); $resources = array_map('strval', $resources); @@ -638,7 +638,7 @@ class XmlFileLoaderTest extends TestCase $ids = array_keys($container->getDefinitions()); sort($ids); - $this->assertSame(array(Prototype\Foo::class, Prototype\Sub\Bar::class, 'service_container'), $ids); + $this->assertSame([Prototype\Foo::class, Prototype\Sub\Bar::class, 'service_container'], $ids); $resources = $container->getResources(); @@ -651,10 +651,10 @@ class XmlFileLoaderTest extends TestCase '/*', true, false, - array( + [ str_replace(\DIRECTORY_SEPARATOR, '/', $prototypeRealPath.\DIRECTORY_SEPARATOR.'BadClasses') => true, str_replace(\DIRECTORY_SEPARATOR, '/', $prototypeRealPath.\DIRECTORY_SEPARATOR.'OtherDir') => true, - ) + ] ); $this->assertContains((string) $globResource, $resources); $resources = array_map('strval', $resources); @@ -849,7 +849,7 @@ class XmlFileLoaderTest extends TestCase $loader->load('services_lazy_fqcn.xml'); $definition = $container->getDefinition('foo'); - $this->assertSame(array(array('interface' => 'SomeInterface')), $definition->getTag('proxy')); + $this->assertSame([['interface' => 'SomeInterface']], $definition->getTag('proxy')); } public function testTsantosContainer() diff --git a/src/Symfony/Component/DependencyInjection/Tests/Loader/YamlFileLoaderTest.php b/src/Symfony/Component/DependencyInjection/Tests/Loader/YamlFileLoaderTest.php index 14a2b76439..37e6054f55 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Loader/YamlFileLoaderTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Loader/YamlFileLoaderTest.php @@ -371,10 +371,10 @@ class YamlFileLoaderTest extends TestCase $fixturesDir.'Prototype', '', true, - false, array( + false, [ str_replace(\DIRECTORY_SEPARATOR, '/', $prototypeRealPath.\DIRECTORY_SEPARATOR.'BadClasses') => true, str_replace(\DIRECTORY_SEPARATOR, '/', $prototypeRealPath.\DIRECTORY_SEPARATOR.'OtherDir') => true, - ) + ] ); $this->assertContains((string) $globResource, $resources); $resources = array_map('strval', $resources); @@ -768,6 +768,6 @@ class YamlFileLoaderTest extends TestCase $loader->load('services_lazy_fqcn.yml'); $definition = $container->getDefinition('foo'); - $this->assertSame(array(array('interface' => 'SomeInterface')), $definition->getTag('proxy')); + $this->assertSame([['interface' => 'SomeInterface']], $definition->getTag('proxy')); } } diff --git a/src/Symfony/Component/DependencyInjection/Tests/ServiceLocatorTest.php b/src/Symfony/Component/DependencyInjection/Tests/ServiceLocatorTest.php index 3b5c9bb009..9c0962880f 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/ServiceLocatorTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/ServiceLocatorTest.php @@ -29,10 +29,10 @@ class ServiceLocatorTest extends BaseServiceLocatorTest */ public function testGetThrowsOnUndefinedService() { - $locator = $this->getServiceLocator(array( + $locator = $this->getServiceLocator([ 'foo' => function () { return 'bar'; }, 'bar' => function () { return 'baz'; }, - )); + ]); $locator->get('dummy'); } @@ -55,7 +55,7 @@ class ServiceLocatorTest extends BaseServiceLocatorTest $container = new Container(); $container->set('foo', new \stdClass()); $subscriber = new SomeServiceSubscriber(); - $subscriber->container = $this->getServiceLocator(array('bar' => function () {})); + $subscriber->container = $this->getServiceLocator(['bar' => function () {}]); $subscriber->container = $subscriber->container->withContext('caller', $container); $subscriber->getFoo(); @@ -70,17 +70,17 @@ class ServiceLocatorTest extends BaseServiceLocatorTest $container = new Container(); $container->set('foo', new \stdClass()); - $locator = new ServiceLocator(array()); + $locator = new ServiceLocator([]); $locator = $locator->withContext('foo', $container); $locator->get('foo'); } public function testInvoke() { - $locator = $this->getServiceLocator(array( + $locator = $this->getServiceLocator([ 'foo' => function () { return 'bar'; }, 'bar' => function () { return 'baz'; }, - )); + ]); $this->assertSame('bar', $locator('foo')); $this->assertSame('baz', $locator('bar')); @@ -99,6 +99,6 @@ class SomeServiceSubscriber implements ServiceSubscriberInterface public static function getSubscribedServices() { - return array('bar' => 'stdClass'); + return ['bar' => 'stdClass']; } } diff --git a/src/Symfony/Component/DomCrawler/AbstractUriElement.php b/src/Symfony/Component/DomCrawler/AbstractUriElement.php index e26be3fcf6..1ef51df59b 100644 --- a/src/Symfony/Component/DomCrawler/AbstractUriElement.php +++ b/src/Symfony/Component/DomCrawler/AbstractUriElement.php @@ -47,7 +47,7 @@ abstract class AbstractUriElement $this->currentUri = $currentUri; $elementUriIsRelative = null === parse_url(trim($this->getRawUri()), PHP_URL_SCHEME); - $baseUriIsAbsolute = \in_array(strtolower(substr($this->currentUri, 0, 4)), array('http', 'file')); + $baseUriIsAbsolute = \in_array(strtolower(substr($this->currentUri, 0, 4)), ['http', 'file']); if ($elementUriIsRelative && !$baseUriIsAbsolute) { throw new \InvalidArgumentException(sprintf('The URL of the element is relative, so you must define its base URI passing an absolute URL to the constructor of the %s class ("%s" was passed).', __CLASS__, $this->currentUri)); } @@ -146,7 +146,7 @@ abstract class AbstractUriElement $path .= '/'; } - $output = array(); + $output = []; foreach (explode('/', $path) as $segment) { if ('..' === $segment) { diff --git a/src/Symfony/Component/Dotenv/Dotenv.php b/src/Symfony/Component/Dotenv/Dotenv.php index 3d7bc3bf93..66ca8c8cd9 100644 --- a/src/Symfony/Component/Dotenv/Dotenv.php +++ b/src/Symfony/Component/Dotenv/Dotenv.php @@ -65,7 +65,7 @@ final class Dotenv * @throws FormatException when a file has a syntax error * @throws PathException when a file does not exist or is not readable */ - public function loadEnv(string $path, string $varName = 'APP_ENV', string $defaultEnv = 'dev', array $testEnvs = array('test')): void + public function loadEnv(string $path, string $varName = 'APP_ENV', string $defaultEnv = 'dev', array $testEnvs = ['test']): void { if (file_exists($path) || !file_exists($p = "$path.dist")) { $this->load($path); @@ -74,7 +74,7 @@ final class Dotenv } if (null === $env = $_SERVER[$varName] ?? $_ENV[$varName] ?? null) { - $this->populate(array($varName => $env = $defaultEnv)); + $this->populate([$varName => $env = $defaultEnv]); } if (!\in_array($env, $testEnvs, true) && file_exists($p = "$path.local")) { diff --git a/src/Symfony/Component/Dotenv/Tests/DotenvTest.php b/src/Symfony/Component/Dotenv/Tests/DotenvTest.php index 29cae1bea2..b9918c9426 100644 --- a/src/Symfony/Component/Dotenv/Tests/DotenvTest.php +++ b/src/Symfony/Component/Dotenv/Tests/DotenvTest.php @@ -343,7 +343,7 @@ class DotenvTest extends TestCase putenv('TEST_ENV_VAR_OVERRIDEN=original_value'); $dotenv = new Dotenv(); - $dotenv->populate(array('TEST_ENV_VAR_OVERRIDEN' => 'new_value'), true); + $dotenv->populate(['TEST_ENV_VAR_OVERRIDEN' => 'new_value'], true); $this->assertSame('new_value', getenv('TEST_ENV_VAR_OVERRIDEN')); $this->assertSame('new_value', $_ENV['TEST_ENV_VAR_OVERRIDEN']); diff --git a/src/Symfony/Component/EventDispatcher/Debug/TraceableEventDispatcher.php b/src/Symfony/Component/EventDispatcher/Debug/TraceableEventDispatcher.php index d421941fc2..513d87c7e8 100644 --- a/src/Symfony/Component/EventDispatcher/Debug/TraceableEventDispatcher.php +++ b/src/Symfony/Component/EventDispatcher/Debug/TraceableEventDispatcher.php @@ -39,8 +39,8 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface $this->dispatcher = $dispatcher; $this->stopwatch = $stopwatch; $this->logger = $logger; - $this->wrappedListeners = array(); - $this->orphanedEvents = array(); + $this->wrappedListeners = []; + $this->orphanedEvents = []; } /** @@ -164,10 +164,10 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface public function getCalledListeners() { if (null === $this->callStack) { - return array(); + return []; } - $called = array(); + $called = []; foreach ($this->callStack as $listener) { list($eventName) = $this->callStack->getInfo(); @@ -186,14 +186,14 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface $allListeners = $this->getListeners(); } catch (\Exception $e) { if (null !== $this->logger) { - $this->logger->info('An exception was thrown while getting the uncalled listeners.', array('exception' => $e)); + $this->logger->info('An exception was thrown while getting the uncalled listeners.', ['exception' => $e]); } // unable to retrieve the uncalled listeners - return array(); + return []; } - $notCalled = array(); + $notCalled = []; foreach ($allListeners as $eventName => $listeners) { foreach ($listeners as $listener) { $called = false; @@ -216,7 +216,7 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface } } - uasort($notCalled, array($this, 'sortNotCalledListeners')); + uasort($notCalled, [$this, 'sortNotCalledListeners']); return $notCalled; } @@ -229,7 +229,7 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface public function reset() { $this->callStack = null; - $this->orphanedEvents = array(); + $this->orphanedEvents = []; } /** @@ -279,7 +279,7 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface $this->wrappedListeners[$eventName][] = $wrappedListener; $this->dispatcher->removeListener($eventName, $listener); $this->dispatcher->addListener($eventName, $wrappedListener, $priority); - $this->callStack->attach($wrappedListener, array($eventName)); + $this->callStack->attach($wrappedListener, [$eventName]); } } @@ -297,7 +297,7 @@ class TraceableEventDispatcher implements TraceableEventDispatcherInterface $this->dispatcher->addListener($eventName, $listener->getWrappedListener(), $priority); if (null !== $this->logger) { - $context = array('event' => $eventName, 'listener' => $listener->getPretty()); + $context = ['event' => $eventName, 'listener' => $listener->getPretty()]; } if ($listener->wasCalled()) { diff --git a/src/Symfony/Component/Filesystem/Tests/FilesystemTest.php b/src/Symfony/Component/Filesystem/Tests/FilesystemTest.php index 2c22b31bd6..8ad94a1e28 100644 --- a/src/Symfony/Component/Filesystem/Tests/FilesystemTest.php +++ b/src/Symfony/Component/Filesystem/Tests/FilesystemTest.php @@ -1334,21 +1334,21 @@ class FilesystemTest extends FilesystemTestCase public function testMirrorWithCustomIterator() { - $sourcePath = $this->workspace.DIRECTORY_SEPARATOR.'source'.DIRECTORY_SEPARATOR; + $sourcePath = $this->workspace.\DIRECTORY_SEPARATOR.'source'.\DIRECTORY_SEPARATOR; mkdir($sourcePath); - $file = $sourcePath.DIRECTORY_SEPARATOR.'file'; + $file = $sourcePath.\DIRECTORY_SEPARATOR.'file'; file_put_contents($file, 'FILE'); - $targetPath = $this->workspace.DIRECTORY_SEPARATOR.'target'.DIRECTORY_SEPARATOR; + $targetPath = $this->workspace.\DIRECTORY_SEPARATOR.'target'.\DIRECTORY_SEPARATOR; $splFile = new \SplFileInfo($file); - $iterator = new \ArrayObject(array($splFile)); + $iterator = new \ArrayObject([$splFile]); $this->filesystem->mirror($sourcePath, $targetPath, $iterator); $this->assertTrue(is_dir($targetPath)); - $this->assertFileEquals($file, $targetPath.DIRECTORY_SEPARATOR.'file'); + $this->assertFileEquals($file, $targetPath.\DIRECTORY_SEPARATOR.'file'); } /** @@ -1357,17 +1357,17 @@ class FilesystemTest extends FilesystemTestCase */ public function testMirrorWithCustomIteratorWithRelativePath() { - $sourcePath = $this->workspace.DIRECTORY_SEPARATOR.'source'.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'source'.DIRECTORY_SEPARATOR; - $realSourcePath = $this->workspace.DIRECTORY_SEPARATOR.'source'.DIRECTORY_SEPARATOR; + $sourcePath = $this->workspace.\DIRECTORY_SEPARATOR.'source'.\DIRECTORY_SEPARATOR.'..'.\DIRECTORY_SEPARATOR.'source'.\DIRECTORY_SEPARATOR; + $realSourcePath = $this->workspace.\DIRECTORY_SEPARATOR.'source'.\DIRECTORY_SEPARATOR; mkdir($realSourcePath); $file = $realSourcePath.'file'; file_put_contents($file, 'FILE'); - $targetPath = $this->workspace.DIRECTORY_SEPARATOR.'target'.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'target'.DIRECTORY_SEPARATOR; + $targetPath = $this->workspace.\DIRECTORY_SEPARATOR.'target'.\DIRECTORY_SEPARATOR.'..'.\DIRECTORY_SEPARATOR.'target'.\DIRECTORY_SEPARATOR; $splFile = new \SplFileInfo($file); - $iterator = new \ArrayObject(array($splFile)); + $iterator = new \ArrayObject([$splFile]); $this->filesystem->mirror($sourcePath, $targetPath, $iterator); } diff --git a/src/Symfony/Component/Finder/Iterator/SortableIterator.php b/src/Symfony/Component/Finder/Iterator/SortableIterator.php index 56bdcfb1a4..f95341f355 100644 --- a/src/Symfony/Component/Finder/Iterator/SortableIterator.php +++ b/src/Symfony/Component/Finder/Iterator/SortableIterator.php @@ -73,7 +73,8 @@ class SortableIterator implements \IteratorAggregate } elseif (self::SORT_BY_NONE === $sort) { $this->sort = $order; } elseif (\is_callable($sort)) { - $this->sort = $reverseOrder ? function ($a, $b) use ($sort) { return -$sort($a, $b); } : $sort; + $this->sort = $reverseOrder ? function ($a, $b) use ($sort) { return -$sort($a, $b); } + : $sort; } else { throw new \InvalidArgumentException('The SortableIterator takes a PHP callable or a valid built-in sort algorithm as an argument.'); } diff --git a/src/Symfony/Component/Finder/Tests/FinderTest.php b/src/Symfony/Component/Finder/Tests/FinderTest.php index cdd176d791..1b50663e9f 100644 --- a/src/Symfony/Component/Finder/Tests/FinderTest.php +++ b/src/Symfony/Component/Finder/Tests/FinderTest.php @@ -24,20 +24,20 @@ class FinderTest extends Iterator\RealIteratorTestCase { $finder = $this->buildFinder(); $this->assertSame($finder, $finder->directories()); - $this->assertIterator($this->toAbsolute(array('foo', 'qux', 'toto')), $finder->in(self::$tmpDir)->getIterator()); + $this->assertIterator($this->toAbsolute(['foo', 'qux', 'toto']), $finder->in(self::$tmpDir)->getIterator()); $finder = $this->buildFinder(); $finder->directories(); $finder->files(); $finder->directories(); - $this->assertIterator($this->toAbsolute(array('foo', 'qux', 'toto')), $finder->in(self::$tmpDir)->getIterator()); + $this->assertIterator($this->toAbsolute(['foo', 'qux', 'toto']), $finder->in(self::$tmpDir)->getIterator()); } public function testFiles() { $finder = $this->buildFinder(); $this->assertSame($finder, $finder->files()); - $this->assertIterator($this->toAbsolute(array('foo/bar.tmp', + $this->assertIterator($this->toAbsolute(['foo/bar.tmp', 'test.php', 'test.py', 'foo bar', @@ -49,13 +49,13 @@ class FinderTest extends Iterator\RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - )), $finder->in(self::$tmpDir)->getIterator()); + ]), $finder->in(self::$tmpDir)->getIterator()); $finder = $this->buildFinder(); $finder->files(); $finder->directories(); $finder->files(); - $this->assertIterator($this->toAbsolute(array('foo/bar.tmp', + $this->assertIterator($this->toAbsolute(['foo/bar.tmp', 'test.php', 'test.py', 'foo bar', @@ -67,14 +67,14 @@ class FinderTest extends Iterator\RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - )), $finder->in(self::$tmpDir)->getIterator()); + ]), $finder->in(self::$tmpDir)->getIterator()); } public function testRemoveTrailingSlash() { $finder = $this->buildFinder(); - $expected = $this->toAbsolute(array( + $expected = $this->toAbsolute([ 'foo/bar.tmp', 'test.php', 'test.py', @@ -87,7 +87,7 @@ class FinderTest extends Iterator\RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - )); + ]); $in = self::$tmpDir.'//'; $this->assertIterator($expected, $finder->in($in)->files()->getIterator()); @@ -102,7 +102,7 @@ class FinderTest extends Iterator\RealIteratorTestCase $finder = $this->buildFinder(); symlink($this->toAbsolute('foo'), $this->toAbsolute('baz')); - $expected = $this->toAbsolute(array('baz/bar.tmp')); + $expected = $this->toAbsolute(['baz/bar.tmp']); $in = self::$tmpDir.'/baz/'; try { $this->assertIterator($expected, $finder->in($in)->files()->getIterator()); @@ -117,7 +117,7 @@ class FinderTest extends Iterator\RealIteratorTestCase { $finder = $this->buildFinder(); - $expected = $this->toAbsolute(array('foo/../foo/bar.tmp')); + $expected = $this->toAbsolute(['foo/../foo/bar.tmp']); $in = self::$tmpDir.'/foo/../foo/'; $this->assertIterator($expected, $finder->in($in)->files()->getIterator()); } @@ -126,7 +126,7 @@ class FinderTest extends Iterator\RealIteratorTestCase { $finder = $this->buildFinder(); $this->assertSame($finder, $finder->depth('< 1')); - $this->assertIterator($this->toAbsolute(array('foo', + $this->assertIterator($this->toAbsolute(['foo', 'test.php', 'test.py', 'toto', @@ -138,11 +138,11 @@ class FinderTest extends Iterator\RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - )), $finder->in(self::$tmpDir)->getIterator()); + ]), $finder->in(self::$tmpDir)->getIterator()); $finder = $this->buildFinder(); $this->assertSame($finder, $finder->depth('<= 0')); - $this->assertIterator($this->toAbsolute(array('foo', + $this->assertIterator($this->toAbsolute(['foo', 'test.php', 'test.py', 'toto', @@ -154,37 +154,37 @@ class FinderTest extends Iterator\RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - )), $finder->in(self::$tmpDir)->getIterator()); + ]), $finder->in(self::$tmpDir)->getIterator()); $finder = $this->buildFinder(); $this->assertSame($finder, $finder->depth('>= 1')); - $this->assertIterator($this->toAbsolute(array( + $this->assertIterator($this->toAbsolute([ 'foo/bar.tmp', 'qux/baz_100_1.py', 'qux/baz_1_2.py', - )), $finder->in(self::$tmpDir)->getIterator()); + ]), $finder->in(self::$tmpDir)->getIterator()); $finder = $this->buildFinder(); $finder->depth('< 1')->depth('>= 1'); - $this->assertIterator(array(), $finder->in(self::$tmpDir)->getIterator()); + $this->assertIterator([], $finder->in(self::$tmpDir)->getIterator()); } public function testDepthWithArrayParam() { $finder = $this->buildFinder(); - $finder->depth(array('>= 1', '< 2')); - $this->assertIterator($this->toAbsolute(array( + $finder->depth(['>= 1', '< 2']); + $this->assertIterator($this->toAbsolute([ 'foo/bar.tmp', 'qux/baz_100_1.py', 'qux/baz_1_2.py', - )), $finder->in(self::$tmpDir)->getIterator()); + ]), $finder->in(self::$tmpDir)->getIterator()); } public function testName() { $finder = $this->buildFinder(); $this->assertSame($finder, $finder->name('*.php')); - $this->assertIterator($this->toAbsolute(array( + $this->assertIterator($this->toAbsolute([ 'test.php', 'qux_0_1.php', 'qux_1000_1.php', @@ -192,20 +192,20 @@ class FinderTest extends Iterator\RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - )), $finder->in(self::$tmpDir)->getIterator()); + ]), $finder->in(self::$tmpDir)->getIterator()); $finder = $this->buildFinder(); $finder->name('test.ph*'); $finder->name('test.py'); - $this->assertIterator($this->toAbsolute(array('test.php', 'test.py')), $finder->in(self::$tmpDir)->getIterator()); + $this->assertIterator($this->toAbsolute(['test.php', 'test.py']), $finder->in(self::$tmpDir)->getIterator()); $finder = $this->buildFinder(); $finder->name('~^test~i'); - $this->assertIterator($this->toAbsolute(array('test.php', 'test.py')), $finder->in(self::$tmpDir)->getIterator()); + $this->assertIterator($this->toAbsolute(['test.php', 'test.py']), $finder->in(self::$tmpDir)->getIterator()); $finder = $this->buildFinder(); $finder->name('~\\.php$~i'); - $this->assertIterator($this->toAbsolute(array( + $this->assertIterator($this->toAbsolute([ 'test.php', 'qux_0_1.php', 'qux_1000_1.php', @@ -213,25 +213,25 @@ class FinderTest extends Iterator\RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - )), $finder->in(self::$tmpDir)->getIterator()); + ]), $finder->in(self::$tmpDir)->getIterator()); $finder = $this->buildFinder(); $finder->name('test.p{hp,y}'); - $this->assertIterator($this->toAbsolute(array('test.php', 'test.py')), $finder->in(self::$tmpDir)->getIterator()); + $this->assertIterator($this->toAbsolute(['test.php', 'test.py']), $finder->in(self::$tmpDir)->getIterator()); } public function testNameWithArrayParam() { $finder = $this->buildFinder(); - $finder->name(array('test.php', 'test.py')); - $this->assertIterator($this->toAbsolute(array('test.php', 'test.py')), $finder->in(self::$tmpDir)->getIterator()); + $finder->name(['test.php', 'test.py']); + $this->assertIterator($this->toAbsolute(['test.php', 'test.py']), $finder->in(self::$tmpDir)->getIterator()); } public function testNotName() { $finder = $this->buildFinder(); $this->assertSame($finder, $finder->notName('*.php')); - $this->assertIterator($this->toAbsolute(array( + $this->assertIterator($this->toAbsolute([ 'foo', 'foo/bar.tmp', 'test.py', @@ -240,44 +240,44 @@ class FinderTest extends Iterator\RealIteratorTestCase 'qux', 'qux/baz_100_1.py', 'qux/baz_1_2.py', - )), $finder->in(self::$tmpDir)->getIterator()); + ]), $finder->in(self::$tmpDir)->getIterator()); $finder = $this->buildFinder(); $finder->notName('*.php'); $finder->notName('*.py'); - $this->assertIterator($this->toAbsolute(array( + $this->assertIterator($this->toAbsolute([ 'foo', 'foo/bar.tmp', 'toto', 'foo bar', 'qux', - )), $finder->in(self::$tmpDir)->getIterator()); + ]), $finder->in(self::$tmpDir)->getIterator()); $finder = $this->buildFinder(); $finder->name('test.ph*'); $finder->name('test.py'); $finder->notName('*.php'); $finder->notName('*.py'); - $this->assertIterator(array(), $finder->in(self::$tmpDir)->getIterator()); + $this->assertIterator([], $finder->in(self::$tmpDir)->getIterator()); $finder = $this->buildFinder(); $finder->name('test.ph*'); $finder->name('test.py'); $finder->notName('*.p{hp,y}'); - $this->assertIterator(array(), $finder->in(self::$tmpDir)->getIterator()); + $this->assertIterator([], $finder->in(self::$tmpDir)->getIterator()); } public function testNotNameWithArrayParam() { $finder = $this->buildFinder(); - $finder->notName(array('*.php', '*.py')); - $this->assertIterator($this->toAbsolute(array( + $finder->notName(['*.php', '*.py']); + $this->assertIterator($this->toAbsolute([ 'foo', 'foo/bar.tmp', 'toto', 'foo bar', 'qux', - )), $finder->in(self::$tmpDir)->getIterator()); + ]), $finder->in(self::$tmpDir)->getIterator()); } /** @@ -287,45 +287,45 @@ class FinderTest extends Iterator\RealIteratorTestCase { $finder = $this->buildFinder(); $finder->name($regex); - $this->assertIterator($this->toAbsolute(array( + $this->assertIterator($this->toAbsolute([ 'test.py', 'test.php', - )), $finder->in(self::$tmpDir)->getIterator()); + ]), $finder->in(self::$tmpDir)->getIterator()); } public function testSize() { $finder = $this->buildFinder(); $this->assertSame($finder, $finder->files()->size('< 1K')->size('> 500')); - $this->assertIterator($this->toAbsolute(array('test.php')), $finder->in(self::$tmpDir)->getIterator()); + $this->assertIterator($this->toAbsolute(['test.php']), $finder->in(self::$tmpDir)->getIterator()); } public function testSizeWithArrayParam() { $finder = $this->buildFinder(); - $this->assertSame($finder, $finder->files()->size(array('< 1K', '> 500'))); - $this->assertIterator($this->toAbsolute(array('test.php')), $finder->in(self::$tmpDir)->getIterator()); + $this->assertSame($finder, $finder->files()->size(['< 1K', '> 500'])); + $this->assertIterator($this->toAbsolute(['test.php']), $finder->in(self::$tmpDir)->getIterator()); } public function testDate() { $finder = $this->buildFinder(); $this->assertSame($finder, $finder->files()->date('until last month')); - $this->assertIterator($this->toAbsolute(array('foo/bar.tmp', 'test.php')), $finder->in(self::$tmpDir)->getIterator()); + $this->assertIterator($this->toAbsolute(['foo/bar.tmp', 'test.php']), $finder->in(self::$tmpDir)->getIterator()); } public function testDateWithArrayParam() { $finder = $this->buildFinder(); - $this->assertSame($finder, $finder->files()->date(array('>= 2005-10-15', 'until last month'))); - $this->assertIterator($this->toAbsolute(array('foo/bar.tmp', 'test.php')), $finder->in(self::$tmpDir)->getIterator()); + $this->assertSame($finder, $finder->files()->date(['>= 2005-10-15', 'until last month'])); + $this->assertIterator($this->toAbsolute(['foo/bar.tmp', 'test.php']), $finder->in(self::$tmpDir)->getIterator()); } public function testExclude() { $finder = $this->buildFinder(); $this->assertSame($finder, $finder->exclude('foo')); - $this->assertIterator($this->toAbsolute(array( + $this->assertIterator($this->toAbsolute([ 'test.php', 'test.py', 'toto', @@ -339,14 +339,14 @@ class FinderTest extends Iterator\RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - )), $finder->in(self::$tmpDir)->getIterator()); + ]), $finder->in(self::$tmpDir)->getIterator()); } public function testIgnoreVCS() { $finder = $this->buildFinder(); $this->assertSame($finder, $finder->ignoreVCS(false)->ignoreDotFiles(false)); - $this->assertIterator($this->toAbsolute(array( + $this->assertIterator($this->toAbsolute([ '.git', 'foo', 'foo/bar.tmp', @@ -368,11 +368,11 @@ class FinderTest extends Iterator\RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - )), $finder->in(self::$tmpDir)->getIterator()); + ]), $finder->in(self::$tmpDir)->getIterator()); $finder = $this->buildFinder(); $finder->ignoreVCS(false)->ignoreVCS(false)->ignoreDotFiles(false); - $this->assertIterator($this->toAbsolute(array( + $this->assertIterator($this->toAbsolute([ '.git', 'foo', 'foo/bar.tmp', @@ -394,11 +394,11 @@ class FinderTest extends Iterator\RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - )), $finder->in(self::$tmpDir)->getIterator()); + ]), $finder->in(self::$tmpDir)->getIterator()); $finder = $this->buildFinder(); $this->assertSame($finder, $finder->ignoreVCS(true)->ignoreDotFiles(false)); - $this->assertIterator($this->toAbsolute(array( + $this->assertIterator($this->toAbsolute([ 'foo', 'foo/bar.tmp', 'test.php', @@ -418,14 +418,14 @@ class FinderTest extends Iterator\RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - )), $finder->in(self::$tmpDir)->getIterator()); + ]), $finder->in(self::$tmpDir)->getIterator()); } public function testIgnoreDotFiles() { $finder = $this->buildFinder(); $this->assertSame($finder, $finder->ignoreDotFiles(false)->ignoreVCS(false)); - $this->assertIterator($this->toAbsolute(array( + $this->assertIterator($this->toAbsolute([ '.git', '.bar', '.foo', @@ -447,11 +447,11 @@ class FinderTest extends Iterator\RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - )), $finder->in(self::$tmpDir)->getIterator()); + ]), $finder->in(self::$tmpDir)->getIterator()); $finder = $this->buildFinder(); $finder->ignoreDotFiles(false)->ignoreDotFiles(false)->ignoreVCS(false); - $this->assertIterator($this->toAbsolute(array( + $this->assertIterator($this->toAbsolute([ '.git', '.bar', '.foo', @@ -473,11 +473,11 @@ class FinderTest extends Iterator\RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - )), $finder->in(self::$tmpDir)->getIterator()); + ]), $finder->in(self::$tmpDir)->getIterator()); $finder = $this->buildFinder(); $this->assertSame($finder, $finder->ignoreDotFiles(true)->ignoreVCS(false)); - $this->assertIterator($this->toAbsolute(array( + $this->assertIterator($this->toAbsolute([ 'foo', 'foo/bar.tmp', 'test.php', @@ -493,14 +493,14 @@ class FinderTest extends Iterator\RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - )), $finder->in(self::$tmpDir)->getIterator()); + ]), $finder->in(self::$tmpDir)->getIterator()); } public function testSortByName() { $finder = $this->buildFinder(); $this->assertSame($finder, $finder->sortByName()); - $this->assertIterator($this->toAbsolute(array( + $this->assertIterator($this->toAbsolute([ 'foo', 'foo bar', 'foo/bar.tmp', @@ -516,14 +516,14 @@ class FinderTest extends Iterator\RealIteratorTestCase 'test.php', 'test.py', 'toto', - )), $finder->in(self::$tmpDir)->getIterator()); + ]), $finder->in(self::$tmpDir)->getIterator()); } public function testSortByType() { $finder = $this->buildFinder(); $this->assertSame($finder, $finder->sortByType()); - $this->assertIterator($this->toAbsolute(array( + $this->assertIterator($this->toAbsolute([ 'foo', 'foo bar', 'toto', @@ -539,14 +539,14 @@ class FinderTest extends Iterator\RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - )), $finder->in(self::$tmpDir)->getIterator()); + ]), $finder->in(self::$tmpDir)->getIterator()); } public function testSortByAccessedTime() { $finder = $this->buildFinder(); $this->assertSame($finder, $finder->sortByAccessedTime()); - $this->assertIterator($this->toAbsolute(array( + $this->assertIterator($this->toAbsolute([ 'foo/bar.tmp', 'test.php', 'toto', @@ -562,14 +562,14 @@ class FinderTest extends Iterator\RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - )), $finder->in(self::$tmpDir)->getIterator()); + ]), $finder->in(self::$tmpDir)->getIterator()); } public function testSortByChangedTime() { $finder = $this->buildFinder(); $this->assertSame($finder, $finder->sortByChangedTime()); - $this->assertIterator($this->toAbsolute(array( + $this->assertIterator($this->toAbsolute([ 'toto', 'test.py', 'test.php', @@ -585,14 +585,14 @@ class FinderTest extends Iterator\RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - )), $finder->in(self::$tmpDir)->getIterator()); + ]), $finder->in(self::$tmpDir)->getIterator()); } public function testSortByModifiedTime() { $finder = $this->buildFinder(); $this->assertSame($finder, $finder->sortByModifiedTime()); - $this->assertIterator($this->toAbsolute(array( + $this->assertIterator($this->toAbsolute([ 'foo/bar.tmp', 'test.php', 'toto', @@ -608,7 +608,7 @@ class FinderTest extends Iterator\RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - )), $finder->in(self::$tmpDir)->getIterator()); + ]), $finder->in(self::$tmpDir)->getIterator()); } public function testReverseSorting() @@ -616,7 +616,7 @@ class FinderTest extends Iterator\RealIteratorTestCase $finder = $this->buildFinder(); $this->assertSame($finder, $finder->sortByName()); $this->assertSame($finder, $finder->reverseSorting()); - $this->assertOrderedIteratorInForeach($this->toAbsolute(array( + $this->assertOrderedIteratorInForeach($this->toAbsolute([ 'toto', 'test.py', 'test.php', @@ -632,14 +632,14 @@ class FinderTest extends Iterator\RealIteratorTestCase 'foo/bar.tmp', 'foo bar', 'foo', - )), $finder->in(self::$tmpDir)->getIterator()); + ]), $finder->in(self::$tmpDir)->getIterator()); } public function testSortByNameNatural() { $finder = $this->buildFinder(); $this->assertSame($finder, $finder->sortByName(true)); - $this->assertIterator($this->toAbsolute(array( + $this->assertIterator($this->toAbsolute([ 'foo', 'foo bar', 'foo/bar.tmp', @@ -655,11 +655,11 @@ class FinderTest extends Iterator\RealIteratorTestCase 'test.php', 'test.py', 'toto', - )), $finder->in(self::$tmpDir)->getIterator()); + ]), $finder->in(self::$tmpDir)->getIterator()); $finder = $this->buildFinder(); $this->assertSame($finder, $finder->sortByName(false)); - $this->assertIterator($this->toAbsolute(array( + $this->assertIterator($this->toAbsolute([ 'foo', 'foo bar', 'foo/bar.tmp', @@ -675,14 +675,14 @@ class FinderTest extends Iterator\RealIteratorTestCase 'test.php', 'test.py', 'toto', - )), $finder->in(self::$tmpDir)->getIterator()); + ]), $finder->in(self::$tmpDir)->getIterator()); } public function testSort() { $finder = $this->buildFinder(); $this->assertSame($finder, $finder->sort(function (\SplFileInfo $a, \SplFileInfo $b) { return strcmp($a->getRealPath(), $b->getRealPath()); })); - $this->assertIterator($this->toAbsolute(array( + $this->assertIterator($this->toAbsolute([ 'foo', 'foo bar', 'foo/bar.tmp', @@ -698,14 +698,14 @@ class FinderTest extends Iterator\RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - )), $finder->in(self::$tmpDir)->getIterator()); + ]), $finder->in(self::$tmpDir)->getIterator()); } public function testFilter() { $finder = $this->buildFinder(); $this->assertSame($finder, $finder->filter(function (\SplFileInfo $f) { return false !== strpos($f, 'test'); })); - $this->assertIterator($this->toAbsolute(array('test.php', 'test.py')), $finder->in(self::$tmpDir)->getIterator()); + $this->assertIterator($this->toAbsolute(['test.php', 'test.py']), $finder->in(self::$tmpDir)->getIterator()); } public function testFollowLinks() @@ -716,7 +716,7 @@ class FinderTest extends Iterator\RealIteratorTestCase $finder = $this->buildFinder(); $this->assertSame($finder, $finder->followLinks()); - $this->assertIterator($this->toAbsolute(array( + $this->assertIterator($this->toAbsolute([ 'foo', 'foo/bar.tmp', 'test.php', @@ -732,15 +732,15 @@ class FinderTest extends Iterator\RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - )), $finder->in(self::$tmpDir)->getIterator()); + ]), $finder->in(self::$tmpDir)->getIterator()); } public function testIn() { $finder = $this->buildFinder(); - $iterator = $finder->files()->name('*.php')->depth('< 1')->in(array(self::$tmpDir, __DIR__))->getIterator(); + $iterator = $finder->files()->name('*.php')->depth('< 1')->in([self::$tmpDir, __DIR__])->getIterator(); - $expected = array( + $expected = [ self::$tmpDir.\DIRECTORY_SEPARATOR.'test.php', __DIR__.\DIRECTORY_SEPARATOR.'FinderTest.php', __DIR__.\DIRECTORY_SEPARATOR.'GlobTest.php', @@ -750,7 +750,7 @@ class FinderTest extends Iterator\RealIteratorTestCase self::$tmpDir.\DIRECTORY_SEPARATOR.'qux_10_2.php', self::$tmpDir.\DIRECTORY_SEPARATOR.'qux_12_0.php', self::$tmpDir.\DIRECTORY_SEPARATOR.'qux_2_0.php', - ); + ]; $this->assertIterator($expected, $iterator); } @@ -767,9 +767,9 @@ class FinderTest extends Iterator\RealIteratorTestCase public function testInWithGlob() { $finder = $this->buildFinder(); - $finder->in(array(__DIR__.'/Fixtures/*/B/C/', __DIR__.'/Fixtures/*/*/B/C/'))->getIterator(); + $finder->in([__DIR__.'/Fixtures/*/B/C/', __DIR__.'/Fixtures/*/*/B/C/'])->getIterator(); - $this->assertIterator($this->toAbsoluteFixtures(array('A/B/C/abc.dat', 'copy/A/B/C/abc.dat.copy')), $finder); + $this->assertIterator($this->toAbsoluteFixtures(['A/B/C/abc.dat', 'copy/A/B/C/abc.dat.copy']), $finder); } /** @@ -784,9 +784,9 @@ class FinderTest extends Iterator\RealIteratorTestCase public function testInWithGlobBrace() { $finder = $this->buildFinder(); - $finder->in(array(__DIR__.'/Fixtures/{A,copy/A}/B/C'))->getIterator(); + $finder->in([__DIR__.'/Fixtures/{A,copy/A}/B/C'])->getIterator(); - $this->assertIterator($this->toAbsoluteFixtures(array('A/B/C/abc.dat', 'copy/A/B/C/abc.dat.copy')), $finder); + $this->assertIterator($this->toAbsoluteFixtures(['A/B/C/abc.dat', 'copy/A/B/C/abc.dat.copy']), $finder); } /** @@ -801,12 +801,12 @@ class FinderTest extends Iterator\RealIteratorTestCase public function testGetIterator() { $finder = $this->buildFinder(); - $dirs = array(); + $dirs = []; foreach ($finder->directories()->in(self::$tmpDir) as $dir) { $dirs[] = (string) $dir; } - $expected = $this->toAbsolute(array('foo', 'qux', 'toto')); + $expected = $this->toAbsolute(['foo', 'qux', 'toto']); sort($dirs); sort($expected); @@ -827,13 +827,13 @@ class FinderTest extends Iterator\RealIteratorTestCase { $finder = $this->buildFinder()->in(self::$tmpDir); - $paths = array(); + $paths = []; foreach ($finder as $file) { $paths[] = $file->getRelativePath(); } - $ref = array('', '', '', '', '', '', '', '', '', '', '', 'foo', 'qux', 'qux', ''); + $ref = ['', '', '', '', '', '', '', '', '', '', '', 'foo', 'qux', 'qux', '']; sort($ref); sort($paths); @@ -845,13 +845,13 @@ class FinderTest extends Iterator\RealIteratorTestCase { $finder = $this->buildFinder()->in(self::$tmpDir)->sortByName(); - $paths = array(); + $paths = []; foreach ($finder as $file) { $paths[] = $file->getRelativePathname(); } - $ref = array( + $ref = [ 'test.php', 'toto', 'test.py', @@ -867,7 +867,7 @@ class FinderTest extends Iterator\RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - ); + ]; sort($paths); sort($ref); @@ -885,7 +885,7 @@ class FinderTest extends Iterator\RealIteratorTestCase $finder = $finder->append($finder1); - $this->assertIterator($this->toAbsolute(array('foo', 'foo/bar.tmp', 'qux', 'toto')), $finder->getIterator()); + $this->assertIterator($this->toAbsolute(['foo', 'foo/bar.tmp', 'qux', 'toto']), $finder->getIterator()); } public function testAppendWithAnArray() @@ -893,14 +893,14 @@ class FinderTest extends Iterator\RealIteratorTestCase $finder = $this->buildFinder(); $finder->files()->in(self::$tmpDir.\DIRECTORY_SEPARATOR.'foo'); - $finder->append($this->toAbsolute(array('foo', 'toto'))); + $finder->append($this->toAbsolute(['foo', 'toto'])); - $this->assertIterator($this->toAbsolute(array('foo', 'foo/bar.tmp', 'toto')), $finder->getIterator()); + $this->assertIterator($this->toAbsolute(['foo', 'foo/bar.tmp', 'toto']), $finder->getIterator()); } public function testAppendReturnsAFinder() { - $this->assertInstanceOf('Symfony\\Component\\Finder\\Finder', Finder::create()->append(array())); + $this->assertInstanceOf('Symfony\\Component\\Finder\\Finder', Finder::create()->append([])); } public function testAppendDoesNotRequireIn() @@ -981,7 +981,7 @@ class FinderTest extends Iterator\RealIteratorTestCase ->directories() ->name('Fixtures') ->contains('abc'); - $this->assertIterator(array(), $finder); + $this->assertIterator([], $finder); } public function testNotContainsOnDirectory() @@ -991,7 +991,7 @@ class FinderTest extends Iterator\RealIteratorTestCase ->directories() ->name('Fixtures') ->notContains('abc'); - $this->assertIterator(array(), $finder); + $this->assertIterator([], $finder); } /** @@ -1002,10 +1002,10 @@ class FinderTest extends Iterator\RealIteratorTestCase */ public function testMultipleLocations() { - $locations = array( + $locations = [ self::$tmpDir.'/', self::$tmpDir.'/toto/', - ); + ]; // it is expected that there are test.py test.php in the tmpDir $finder = new Finder(); @@ -1027,18 +1027,18 @@ class FinderTest extends Iterator\RealIteratorTestCase */ public function testMultipleLocationsWithSubDirectories() { - $locations = array( + $locations = [ __DIR__.'/Fixtures/one', self::$tmpDir.\DIRECTORY_SEPARATOR.'toto', - ); + ]; $finder = $this->buildFinder(); $finder->in($locations)->depth('< 10')->name('*.neon'); - $expected = array( + $expected = [ __DIR__.'/Fixtures/one'.\DIRECTORY_SEPARATOR.'b'.\DIRECTORY_SEPARATOR.'c.neon', __DIR__.'/Fixtures/one'.\DIRECTORY_SEPARATOR.'b'.\DIRECTORY_SEPARATOR.'d.neon', - ); + ]; $this->assertIterator($expected, $finder); $this->assertIteratorInForeach($expected, $finder); @@ -1061,34 +1061,34 @@ class FinderTest extends Iterator\RealIteratorTestCase $finder->in(__DIR__.\DIRECTORY_SEPARATOR.'Fixtures'.\DIRECTORY_SEPARATOR.'r+e.gex[c]a(r)s') ->path('/^dir/'); - $expected = array('r+e.gex[c]a(r)s'.\DIRECTORY_SEPARATOR.'dir', 'r+e.gex[c]a(r)s'.\DIRECTORY_SEPARATOR.'dir'.\DIRECTORY_SEPARATOR.'bar.dat'); + $expected = ['r+e.gex[c]a(r)s'.\DIRECTORY_SEPARATOR.'dir', 'r+e.gex[c]a(r)s'.\DIRECTORY_SEPARATOR.'dir'.\DIRECTORY_SEPARATOR.'bar.dat']; $this->assertIterator($this->toAbsoluteFixtures($expected), $finder); } public function getContainsTestData() { - return array( - array('', '', array()), - array('foo', 'bar', array()), - array('', 'foobar', array('dolor.txt', 'ipsum.txt', 'lorem.txt')), - array('lorem ipsum dolor sit amet', 'foobar', array('lorem.txt')), - array('sit', 'bar', array('dolor.txt', 'ipsum.txt', 'lorem.txt')), - array('dolor sit amet', '@^L@m', array('dolor.txt', 'ipsum.txt')), - array('/^lorem ipsum dolor sit amet$/m', 'foobar', array('lorem.txt')), - array('lorem', 'foobar', array('lorem.txt')), - array('', 'lorem', array('dolor.txt', 'ipsum.txt')), - array('ipsum dolor sit amet', '/^IPSUM/m', array('lorem.txt')), - array(array('lorem', 'dolor'), array(), array('lorem.txt', 'ipsum.txt', 'dolor.txt')), - array('', array('lorem', 'ipsum'), array('dolor.txt')), - ); + return [ + ['', '', []], + ['foo', 'bar', []], + ['', 'foobar', ['dolor.txt', 'ipsum.txt', 'lorem.txt']], + ['lorem ipsum dolor sit amet', 'foobar', ['lorem.txt']], + ['sit', 'bar', ['dolor.txt', 'ipsum.txt', 'lorem.txt']], + ['dolor sit amet', '@^L@m', ['dolor.txt', 'ipsum.txt']], + ['/^lorem ipsum dolor sit amet$/m', 'foobar', ['lorem.txt']], + ['lorem', 'foobar', ['lorem.txt']], + ['', 'lorem', ['dolor.txt', 'ipsum.txt']], + ['ipsum dolor sit amet', '/^IPSUM/m', ['lorem.txt']], + [['lorem', 'dolor'], [], ['lorem.txt', 'ipsum.txt', 'dolor.txt']], + ['', ['lorem', 'ipsum'], ['dolor.txt']], + ]; } public function getRegexNameTestData() { - return array( - array('~.*t\\.p.+~i'), - array('~t.*s~i'), - ); + return [ + ['~.*t\\.p.+~i'], + ['~t.*s~i'], + ]; } /** @@ -1106,29 +1106,29 @@ class FinderTest extends Iterator\RealIteratorTestCase public function getTestPathData() { - return array( - array('', '', array()), - array('/^A\/B\/C/', '/C$/', - array('A'.\DIRECTORY_SEPARATOR.'B'.\DIRECTORY_SEPARATOR.'C'.\DIRECTORY_SEPARATOR.'abc.dat'), - ), - array('/^A\/B/', 'foobar', - array( + return [ + ['', '', []], + ['/^A\/B\/C/', '/C$/', + ['A'.\DIRECTORY_SEPARATOR.'B'.\DIRECTORY_SEPARATOR.'C'.\DIRECTORY_SEPARATOR.'abc.dat'], + ], + ['/^A\/B/', 'foobar', + [ 'A'.\DIRECTORY_SEPARATOR.'B', 'A'.\DIRECTORY_SEPARATOR.'B'.\DIRECTORY_SEPARATOR.'C', 'A'.\DIRECTORY_SEPARATOR.'B'.\DIRECTORY_SEPARATOR.'ab.dat', 'A'.\DIRECTORY_SEPARATOR.'B'.\DIRECTORY_SEPARATOR.'C'.\DIRECTORY_SEPARATOR.'abc.dat', - ), - ), - array('A/B/C', 'foobar', - array( + ], + ], + ['A/B/C', 'foobar', + [ 'A'.\DIRECTORY_SEPARATOR.'B'.\DIRECTORY_SEPARATOR.'C', 'A'.\DIRECTORY_SEPARATOR.'B'.\DIRECTORY_SEPARATOR.'C'.\DIRECTORY_SEPARATOR.'abc.dat', 'copy'.\DIRECTORY_SEPARATOR.'A'.\DIRECTORY_SEPARATOR.'B'.\DIRECTORY_SEPARATOR.'C', 'copy'.\DIRECTORY_SEPARATOR.'A'.\DIRECTORY_SEPARATOR.'B'.\DIRECTORY_SEPARATOR.'C'.\DIRECTORY_SEPARATOR.'abc.dat.copy', - ), - ), - array('A/B', 'foobar', - array( + ], + ], + ['A/B', 'foobar', + [ //dirs 'A'.\DIRECTORY_SEPARATOR.'B', 'A'.\DIRECTORY_SEPARATOR.'B'.\DIRECTORY_SEPARATOR.'C', @@ -1139,27 +1139,27 @@ class FinderTest extends Iterator\RealIteratorTestCase 'A'.\DIRECTORY_SEPARATOR.'B'.\DIRECTORY_SEPARATOR.'C'.\DIRECTORY_SEPARATOR.'abc.dat', 'copy'.\DIRECTORY_SEPARATOR.'A'.\DIRECTORY_SEPARATOR.'B'.\DIRECTORY_SEPARATOR.'ab.dat.copy', 'copy'.\DIRECTORY_SEPARATOR.'A'.\DIRECTORY_SEPARATOR.'B'.\DIRECTORY_SEPARATOR.'C'.\DIRECTORY_SEPARATOR.'abc.dat.copy', - ), - ), - array('/^with space\//', 'foobar', - array( + ], + ], + ['/^with space\//', 'foobar', + [ 'with space'.\DIRECTORY_SEPARATOR.'foo.txt', - ), - ), - array( + ], + ], + [ '/^A/', - array('a.dat', 'abc.dat'), - array( + ['a.dat', 'abc.dat'], + [ 'A', 'A'.\DIRECTORY_SEPARATOR.'B', 'A'.\DIRECTORY_SEPARATOR.'B'.\DIRECTORY_SEPARATOR.'C', 'A'.\DIRECTORY_SEPARATOR.'B'.\DIRECTORY_SEPARATOR.'ab.dat', - ), - ), - array( - array('/^A/', 'one'), + ], + ], + [ + ['/^A/', 'one'], 'foobar', - array( + [ 'A', 'A'.\DIRECTORY_SEPARATOR.'B', 'A'.\DIRECTORY_SEPARATOR.'B'.\DIRECTORY_SEPARATOR.'C', @@ -1171,9 +1171,9 @@ class FinderTest extends Iterator\RealIteratorTestCase 'one'.\DIRECTORY_SEPARATOR.'b', 'one'.\DIRECTORY_SEPARATOR.'b'.\DIRECTORY_SEPARATOR.'c.neon', 'one'.\DIRECTORY_SEPARATOR.'b'.\DIRECTORY_SEPARATOR.'d.neon', - ), - ), - ); + ], + ], + ]; } public function testAccessDeniedException() @@ -1191,7 +1191,7 @@ class FinderTest extends Iterator\RealIteratorTestCase if (false === $couldRead = is_readable($testDir)) { try { - $this->assertIterator($this->toAbsolute(array('foo bar', 'test.php', 'test.py')), $finder->getIterator()); + $this->assertIterator($this->toAbsolute(['foo bar', 'test.php', 'test.py']), $finder->getIterator()); $this->fail('Finder should throw an exception when opening a non-readable directory.'); } catch (\Exception $e) { $expectedExceptionClass = 'Symfony\\Component\\Finder\\Exception\\AccessDeniedException'; @@ -1230,7 +1230,7 @@ class FinderTest extends Iterator\RealIteratorTestCase chmod($testDir, 0333); if (false === ($couldRead = is_readable($testDir))) { - $this->assertIterator($this->toAbsolute(array( + $this->assertIterator($this->toAbsolute([ 'foo bar', 'test.php', 'test.py', @@ -1242,7 +1242,7 @@ class FinderTest extends Iterator\RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - ) + ] ), $finder->getIterator()); } diff --git a/src/Symfony/Component/Finder/Tests/Iterator/DateRangeFilterIteratorTest.php b/src/Symfony/Component/Finder/Tests/Iterator/DateRangeFilterIteratorTest.php index ade1a41a01..2d8cfb30bd 100644 --- a/src/Symfony/Component/Finder/Tests/Iterator/DateRangeFilterIteratorTest.php +++ b/src/Symfony/Component/Finder/Tests/Iterator/DateRangeFilterIteratorTest.php @@ -32,7 +32,7 @@ class DateRangeFilterIteratorTest extends RealIteratorTestCase public function getAcceptData() { - $since20YearsAgo = array( + $since20YearsAgo = [ '.git', 'test.py', 'foo', @@ -54,9 +54,9 @@ class DateRangeFilterIteratorTest extends RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - ); + ]; - $since2MonthsAgo = array( + $since2MonthsAgo = [ '.git', 'test.py', 'foo', @@ -76,17 +76,17 @@ class DateRangeFilterIteratorTest extends RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - ); + ]; - $untilLastMonth = array( + $untilLastMonth = [ 'foo/bar.tmp', 'test.php', - ); + ]; - return array( - array(array(new DateComparator('since 20 years ago')), $this->toAbsolute($since20YearsAgo)), - array(array(new DateComparator('since 2 months ago')), $this->toAbsolute($since2MonthsAgo)), - array(array(new DateComparator('until last month')), $this->toAbsolute($untilLastMonth)), - ); + return [ + [[new DateComparator('since 20 years ago')], $this->toAbsolute($since20YearsAgo)], + [[new DateComparator('since 2 months ago')], $this->toAbsolute($since2MonthsAgo)], + [[new DateComparator('until last month')], $this->toAbsolute($untilLastMonth)], + ]; } } diff --git a/src/Symfony/Component/Finder/Tests/Iterator/DepthRangeFilterIteratorTest.php b/src/Symfony/Component/Finder/Tests/Iterator/DepthRangeFilterIteratorTest.php index 3a403cb955..ef4fa2e9ac 100644 --- a/src/Symfony/Component/Finder/Tests/Iterator/DepthRangeFilterIteratorTest.php +++ b/src/Symfony/Component/Finder/Tests/Iterator/DepthRangeFilterIteratorTest.php @@ -32,7 +32,7 @@ class DepthRangeFilterIteratorTest extends RealIteratorTestCase public function getAcceptData() { - $lessThan1 = array( + $lessThan1 = [ '.git', 'test.py', 'foo', @@ -48,9 +48,9 @@ class DepthRangeFilterIteratorTest extends RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - ); + ]; - $lessThanOrEqualTo1 = array( + $lessThanOrEqualTo1 = [ '.git', 'test.py', 'foo', @@ -72,32 +72,32 @@ class DepthRangeFilterIteratorTest extends RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - ); + ]; - $graterThanOrEqualTo1 = array( + $graterThanOrEqualTo1 = [ 'toto/.git', 'foo/bar.tmp', '.foo/.bar', '.foo/bar', 'qux/baz_100_1.py', 'qux/baz_1_2.py', - ); + ]; - $equalTo1 = array( + $equalTo1 = [ 'toto/.git', 'foo/bar.tmp', '.foo/.bar', '.foo/bar', 'qux/baz_100_1.py', 'qux/baz_1_2.py', - ); + ]; - return array( - array(0, 0, $this->toAbsolute($lessThan1)), - array(0, 1, $this->toAbsolute($lessThanOrEqualTo1)), - array(2, PHP_INT_MAX, array()), - array(1, PHP_INT_MAX, $this->toAbsolute($graterThanOrEqualTo1)), - array(1, 1, $this->toAbsolute($equalTo1)), - ); + return [ + [0, 0, $this->toAbsolute($lessThan1)], + [0, 1, $this->toAbsolute($lessThanOrEqualTo1)], + [2, PHP_INT_MAX, []], + [1, PHP_INT_MAX, $this->toAbsolute($graterThanOrEqualTo1)], + [1, 1, $this->toAbsolute($equalTo1)], + ]; } } diff --git a/src/Symfony/Component/Finder/Tests/Iterator/ExcludeDirectoryFilterIteratorTest.php b/src/Symfony/Component/Finder/Tests/Iterator/ExcludeDirectoryFilterIteratorTest.php index c977b0cfdb..1729766fe4 100644 --- a/src/Symfony/Component/Finder/Tests/Iterator/ExcludeDirectoryFilterIteratorTest.php +++ b/src/Symfony/Component/Finder/Tests/Iterator/ExcludeDirectoryFilterIteratorTest.php @@ -30,7 +30,7 @@ class ExcludeDirectoryFilterIteratorTest extends RealIteratorTestCase public function getAcceptData() { - $foo = array( + $foo = [ '.bar', '.foo', '.foo/.bar', @@ -50,9 +50,9 @@ class ExcludeDirectoryFilterIteratorTest extends RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - ); + ]; - $fo = array( + $fo = [ '.bar', '.foo', '.foo/.bar', @@ -74,9 +74,9 @@ class ExcludeDirectoryFilterIteratorTest extends RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - ); + ]; - $toto = array( + $toto = [ '.bar', '.foo', '.foo/.bar', @@ -96,12 +96,12 @@ class ExcludeDirectoryFilterIteratorTest extends RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - ); + ]; - return array( - array(array('foo'), $this->toAbsolute($foo)), - array(array('fo'), $this->toAbsolute($fo)), - array(array('toto/'), $this->toAbsolute($toto)), - ); + return [ + [['foo'], $this->toAbsolute($foo)], + [['fo'], $this->toAbsolute($fo)], + [['toto/'], $this->toAbsolute($toto)], + ]; } } diff --git a/src/Symfony/Component/Finder/Tests/Iterator/FileTypeFilterIteratorTest.php b/src/Symfony/Component/Finder/Tests/Iterator/FileTypeFilterIteratorTest.php index 0ecd8dfe73..49616ce07c 100644 --- a/src/Symfony/Component/Finder/Tests/Iterator/FileTypeFilterIteratorTest.php +++ b/src/Symfony/Component/Finder/Tests/Iterator/FileTypeFilterIteratorTest.php @@ -29,7 +29,7 @@ class FileTypeFilterIteratorTest extends RealIteratorTestCase public function getAcceptData() { - $onlyFiles = array( + $onlyFiles = [ 'test.py', 'foo/bar.tmp', 'test.php', @@ -45,21 +45,21 @@ class FileTypeFilterIteratorTest extends RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - ); + ]; - $onlyDirectories = array( + $onlyDirectories = [ '.git', 'foo', 'qux', 'toto', 'toto/.git', '.foo', - ); + ]; - return array( - array(FileTypeFilterIterator::ONLY_FILES, $this->toAbsolute($onlyFiles)), - array(FileTypeFilterIterator::ONLY_DIRECTORIES, $this->toAbsolute($onlyDirectories)), - ); + return [ + [FileTypeFilterIterator::ONLY_FILES, $this->toAbsolute($onlyFiles)], + [FileTypeFilterIterator::ONLY_DIRECTORIES, $this->toAbsolute($onlyDirectories)], + ]; } } diff --git a/src/Symfony/Component/Finder/Tests/Iterator/RealIteratorTestCase.php b/src/Symfony/Component/Finder/Tests/Iterator/RealIteratorTestCase.php index 9aa68ea20d..bd14167ab8 100644 --- a/src/Symfony/Component/Finder/Tests/Iterator/RealIteratorTestCase.php +++ b/src/Symfony/Component/Finder/Tests/Iterator/RealIteratorTestCase.php @@ -20,7 +20,7 @@ abstract class RealIteratorTestCase extends IteratorTestCase { self::$tmpDir = realpath(sys_get_temp_dir()).\DIRECTORY_SEPARATOR.'symfony_finder'; - self::$files = array( + self::$files = [ '.git/', '.foo/', '.foo/.bar', @@ -42,7 +42,7 @@ abstract class RealIteratorTestCase extends IteratorTestCase 'qux/', 'qux/baz_1_2.py', 'qux/baz_100_1.py', - ); + ]; self::$files = self::toAbsolute(self::$files); @@ -97,7 +97,7 @@ abstract class RealIteratorTestCase extends IteratorTestCase } if (\is_array($files)) { - $f = array(); + $f = []; foreach ($files as $file) { if (\is_array($file)) { $f[] = self::toAbsolute($file); @@ -118,7 +118,7 @@ abstract class RealIteratorTestCase extends IteratorTestCase protected static function toAbsoluteFixtures($files) { - $f = array(); + $f = []; foreach ($files as $file) { $f[] = realpath(__DIR__.\DIRECTORY_SEPARATOR.'..'.\DIRECTORY_SEPARATOR.'Fixtures'.\DIRECTORY_SEPARATOR.$file); } diff --git a/src/Symfony/Component/Finder/Tests/Iterator/SortableIteratorTest.php b/src/Symfony/Component/Finder/Tests/Iterator/SortableIteratorTest.php index 33687c5214..e9dad1e056 100644 --- a/src/Symfony/Component/Finder/Tests/Iterator/SortableIteratorTest.php +++ b/src/Symfony/Component/Finder/Tests/Iterator/SortableIteratorTest.php @@ -18,7 +18,7 @@ class SortableIteratorTest extends RealIteratorTestCase public function testConstructor() { try { - new SortableIterator(new Iterator(array()), 'foobar'); + new SortableIterator(new Iterator([]), 'foobar'); $this->fail('__construct() throws an \InvalidArgumentException exception if the mode is not valid'); } catch (\Exception $e) { $this->assertInstanceOf('InvalidArgumentException', $e, '__construct() throws an \InvalidArgumentException exception if the mode is not valid'); @@ -73,7 +73,7 @@ class SortableIteratorTest extends RealIteratorTestCase public function getAcceptData() { - $sortByName = array( + $sortByName = [ '.bar', '.foo', '.foo/.bar', @@ -95,9 +95,9 @@ class SortableIteratorTest extends RealIteratorTestCase 'test.py', 'toto', 'toto/.git', - ); + ]; - $sortByType = array( + $sortByType = [ '.foo', '.git', 'foo', @@ -119,13 +119,13 @@ class SortableIteratorTest extends RealIteratorTestCase 'qux_2_0.php', 'test.php', 'test.py', - ); + ]; - $sortByAccessedTime = array( + $sortByAccessedTime = [ // For these two files the access time was set to 2005-10-15 - array('foo/bar.tmp', 'test.php'), + ['foo/bar.tmp', 'test.php'], // These files were created more or less at the same time - array( + [ '.git', '.foo', '.foo/.bar', @@ -144,13 +144,13 @@ class SortableIteratorTest extends RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - ), + ], // This file was accessed after sleeping for 1 sec - array('.bar'), - ); + ['.bar'], + ]; - $sortByChangedTime = array( - array( + $sortByChangedTime = [ + [ '.git', '.foo', '.foo/.bar', @@ -170,13 +170,13 @@ class SortableIteratorTest extends RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - ), - array('test.php'), - array('test.py'), - ); + ], + ['test.php'], + ['test.py'], + ]; - $sortByModifiedTime = array( - array( + $sortByModifiedTime = [ + [ '.git', '.foo', '.foo/.bar', @@ -196,12 +196,12 @@ class SortableIteratorTest extends RealIteratorTestCase 'qux_10_2.php', 'qux_12_0.php', 'qux_2_0.php', - ), - array('test.php'), - array('test.py'), - ); + ], + ['test.php'], + ['test.py'], + ]; - $sortByNameNatural = array( + $sortByNameNatural = [ '.bar', '.foo', '.foo/.bar', @@ -223,9 +223,9 @@ class SortableIteratorTest extends RealIteratorTestCase 'test.py', 'toto', 'toto/.git', - ); + ]; - $customComparison = array( + $customComparison = [ '.bar', '.foo', '.foo/.bar', @@ -247,16 +247,16 @@ class SortableIteratorTest extends RealIteratorTestCase 'test.py', 'toto', 'toto/.git', - ); + ]; - return array( - array(SortableIterator::SORT_BY_NAME, $this->toAbsolute($sortByName)), - array(SortableIterator::SORT_BY_TYPE, $this->toAbsolute($sortByType)), - array(SortableIterator::SORT_BY_ACCESSED_TIME, $this->toAbsolute($sortByAccessedTime)), - array(SortableIterator::SORT_BY_CHANGED_TIME, $this->toAbsolute($sortByChangedTime)), - array(SortableIterator::SORT_BY_MODIFIED_TIME, $this->toAbsolute($sortByModifiedTime)), - array(SortableIterator::SORT_BY_NAME_NATURAL, $this->toAbsolute($sortByNameNatural)), - array(function (\SplFileInfo $a, \SplFileInfo $b) { return strcmp($a->getRealPath(), $b->getRealPath()); }, $this->toAbsolute($customComparison)), - ); + return [ + [SortableIterator::SORT_BY_NAME, $this->toAbsolute($sortByName)], + [SortableIterator::SORT_BY_TYPE, $this->toAbsolute($sortByType)], + [SortableIterator::SORT_BY_ACCESSED_TIME, $this->toAbsolute($sortByAccessedTime)], + [SortableIterator::SORT_BY_CHANGED_TIME, $this->toAbsolute($sortByChangedTime)], + [SortableIterator::SORT_BY_MODIFIED_TIME, $this->toAbsolute($sortByModifiedTime)], + [SortableIterator::SORT_BY_NAME_NATURAL, $this->toAbsolute($sortByNameNatural)], + [function (\SplFileInfo $a, \SplFileInfo $b) { return strcmp($a->getRealPath(), $b->getRealPath()); }, $this->toAbsolute($customComparison)], + ]; } } diff --git a/src/Symfony/Component/Form/AbstractExtension.php b/src/Symfony/Component/Form/AbstractExtension.php index bce5c03676..5b437344e8 100644 --- a/src/Symfony/Component/Form/AbstractExtension.php +++ b/src/Symfony/Component/Form/AbstractExtension.php @@ -176,7 +176,7 @@ abstract class AbstractExtension implements FormExtensionInterface } if (method_exists($extension, 'getExtendedTypes')) { - $extendedTypes = array(); + $extendedTypes = []; foreach ($extension::getExtendedTypes() as $extendedType) { $extendedTypes[] = $extendedType; @@ -184,7 +184,7 @@ abstract class AbstractExtension implements FormExtensionInterface } else { @trigger_error(sprintf('Not implementing the static getExtendedTypes() method in %s when implementing the %s is deprecated since Symfony 4.2. The method will be added to the interface in 5.0.', \get_class($extension), FormTypeExtensionInterface::class), E_USER_DEPRECATED); - $extendedTypes = array($extension->getExtendedType()); + $extendedTypes = [$extension->getExtendedType()]; } foreach ($extendedTypes as $extendedType) { diff --git a/src/Symfony/Component/Form/Command/DebugCommand.php b/src/Symfony/Component/Form/Command/DebugCommand.php index 2ab3db2dde..32c9b26f33 100644 --- a/src/Symfony/Component/Form/Command/DebugCommand.php +++ b/src/Symfony/Component/Form/Command/DebugCommand.php @@ -200,7 +200,7 @@ EOF private function filterTypesByDeprecated(array $types): array { - $typesWithDeprecatedOptions = array(); + $typesWithDeprecatedOptions = []; foreach ($types as $class) { $optionsResolver = $this->formRegistry->getType($class)->getOptionsResolver(); foreach ($optionsResolver->getDefinedOptions() as $option) { diff --git a/src/Symfony/Component/Form/Console/Descriptor/Descriptor.php b/src/Symfony/Component/Form/Console/Descriptor/Descriptor.php index dda755250c..7add269e30 100644 --- a/src/Symfony/Component/Form/Console/Descriptor/Descriptor.php +++ b/src/Symfony/Component/Form/Console/Descriptor/Descriptor.php @@ -32,20 +32,20 @@ abstract class Descriptor implements DescriptorInterface /** @var OutputStyle */ protected $output; protected $type; - protected $ownOptions = array(); - protected $overriddenOptions = array(); - protected $parentOptions = array(); - protected $extensionOptions = array(); - protected $requiredOptions = array(); - protected $parents = array(); - protected $extensions = array(); + protected $ownOptions = []; + protected $overriddenOptions = []; + protected $parentOptions = []; + protected $extensionOptions = []; + protected $requiredOptions = []; + protected $parents = []; + protected $extensions = []; /** * {@inheritdoc} */ - public function describe(OutputInterface $output, $object, array $options = array()) + public function describe(OutputInterface $output, $object, array $options = []) { - $this->output = $output instanceof OutputStyle ? $output : new SymfonyStyle(new ArrayInput(array()), $output); + $this->output = $output instanceof OutputStyle ? $output : new SymfonyStyle(new ArrayInput([]), $output); switch (true) { case null === $object: @@ -64,14 +64,14 @@ abstract class Descriptor implements DescriptorInterface abstract protected function describeDefaults(array $options); - abstract protected function describeResolvedFormType(ResolvedFormTypeInterface $resolvedFormType, array $options = array()); + abstract protected function describeResolvedFormType(ResolvedFormTypeInterface $resolvedFormType, array $options = []); abstract protected function describeOption(OptionsResolver $optionsResolver, array $options); protected function collectOptions(ResolvedFormTypeInterface $type) { - $this->parents = array(); - $this->extensions = array(); + $this->parents = []; + $this->extensions = []; if (null !== $type->getParent()) { $optionsResolver = clone $this->getParentOptionsResolver($type->getParent()); @@ -83,7 +83,7 @@ abstract class Descriptor implements DescriptorInterface $this->ownOptions = array_diff($ownOptionsResolver->getDefinedOptions(), $optionsResolver->getDefinedOptions()); $overriddenOptions = array_intersect(array_merge($ownOptionsResolver->getDefinedOptions(), $ownOptionsResolver->getUndefinedOptions()), $optionsResolver->getDefinedOptions()); - $this->parentOptions = array(); + $this->parentOptions = []; foreach ($this->parents as $class => $parentOptions) { $this->overriddenOptions[$class] = array_intersect($overriddenOptions, $parentOptions); $this->parentOptions[$class] = array_diff($parentOptions, $overriddenOptions); @@ -91,7 +91,7 @@ abstract class Descriptor implements DescriptorInterface $type->getInnerType()->configureOptions($optionsResolver); $this->collectTypeExtensionsOptions($type, $optionsResolver); - $this->extensionOptions = array(); + $this->extensionOptions = []; foreach ($this->extensions as $class => $extensionOptions) { $this->overriddenOptions[$class] = array_intersect($overriddenOptions, $extensionOptions); $this->extensionOptions[$class] = array_diff($extensionOptions, $overriddenOptions); @@ -108,21 +108,21 @@ abstract class Descriptor implements DescriptorInterface protected function getOptionDefinition(OptionsResolver $optionsResolver, $option) { - $definition = array( + $definition = [ 'required' => $optionsResolver->isRequired($option), 'deprecated' => $optionsResolver->isDeprecated($option), - ); + ]; $introspector = new OptionsResolverIntrospector($optionsResolver); - $map = array( + $map = [ 'default' => 'getDefault', 'lazy' => 'getLazyClosures', 'allowedTypes' => 'getAllowedTypes', 'allowedValues' => 'getAllowedValues', 'normalizer' => 'getNormalizer', 'deprecationMessage' => 'getDeprecationMessage', - ); + ]; foreach ($map as $key => $method) { try { @@ -133,7 +133,7 @@ abstract class Descriptor implements DescriptorInterface } if (isset($definition['deprecationMessage']) && \is_string($definition['deprecationMessage'])) { - $definition['deprecationMessage'] = strtr($definition['deprecationMessage'], array('%name%' => $option)); + $definition['deprecationMessage'] = strtr($definition['deprecationMessage'], ['%name%' => $option]); } return $definition; @@ -141,7 +141,7 @@ abstract class Descriptor implements DescriptorInterface protected function filterOptionsByDeprecated(ResolvedFormTypeInterface $type) { - $deprecatedOptions = array(); + $deprecatedOptions = []; $resolver = $type->getOptionsResolver(); foreach ($resolver->getDefinedOptions() as $option) { if ($resolver->isDeprecated($option)) { @@ -169,7 +169,7 @@ abstract class Descriptor implements DescriptorInterface private function getParentOptionsResolver(ResolvedFormTypeInterface $type) { - $this->parents[$class = \get_class($type->getInnerType())] = array(); + $this->parents[$class = \get_class($type->getInnerType())] = []; if (null !== $type->getParent()) { $optionsResolver = clone $this->getParentOptionsResolver($type->getParent()); diff --git a/src/Symfony/Component/Form/Console/Descriptor/JsonDescriptor.php b/src/Symfony/Component/Form/Console/Descriptor/JsonDescriptor.php index 773d993399..31d9aa485e 100644 --- a/src/Symfony/Component/Form/Console/Descriptor/JsonDescriptor.php +++ b/src/Symfony/Component/Form/Console/Descriptor/JsonDescriptor.php @@ -33,7 +33,7 @@ class JsonDescriptor extends Descriptor $this->writeData($data, $options); } - protected function describeResolvedFormType(ResolvedFormTypeInterface $resolvedFormType, array $options = array()) + protected function describeResolvedFormType(ResolvedFormTypeInterface $resolvedFormType, array $options = []) { $this->collectOptions($resolvedFormType); @@ -41,22 +41,22 @@ class JsonDescriptor extends Descriptor $this->filterOptionsByDeprecated($resolvedFormType); } - $formOptions = array( + $formOptions = [ 'own' => $this->ownOptions, 'overridden' => $this->overriddenOptions, 'parent' => $this->parentOptions, 'extension' => $this->extensionOptions, 'required' => $this->requiredOptions, - ); + ]; $this->sortOptions($formOptions); - $data = array( + $data = [ 'class' => \get_class($resolvedFormType->getInnerType()), 'block_prefix' => $resolvedFormType->getInnerType()->getBlockPrefix(), 'options' => $formOptions, 'parent_types' => $this->parents, 'type_extensions' => $this->extensions, - ); + ]; $this->writeData($data, $options); } @@ -65,19 +65,19 @@ class JsonDescriptor extends Descriptor { $definition = $this->getOptionDefinition($optionsResolver, $options['option']); - $map = array(); + $map = []; if ($definition['deprecated']) { $map['deprecated'] = 'deprecated'; if (\is_string($definition['deprecationMessage'])) { $map['deprecation_message'] = 'deprecationMessage'; } } - $map += array( + $map += [ 'required' => 'required', 'default' => 'default', 'allowed_types' => 'allowedTypes', 'allowed_values' => 'allowedValues', - ); + ]; foreach ($map as $label => $name) { if (array_key_exists($name, $definition)) { $data[$label] = $definition[$name]; diff --git a/src/Symfony/Component/Form/Console/Descriptor/TextDescriptor.php b/src/Symfony/Component/Form/Console/Descriptor/TextDescriptor.php index 1621f9d31c..4ea8ab6d83 100644 --- a/src/Symfony/Component/Form/Console/Descriptor/TextDescriptor.php +++ b/src/Symfony/Component/Form/Console/Descriptor/TextDescriptor.php @@ -53,7 +53,7 @@ class TextDescriptor extends Descriptor } } - protected function describeResolvedFormType(ResolvedFormTypeInterface $resolvedFormType, array $options = array()) + protected function describeResolvedFormType(ResolvedFormTypeInterface $resolvedFormType, array $options = []) { $this->collectOptions($resolvedFormType); @@ -61,20 +61,20 @@ class TextDescriptor extends Descriptor $this->filterOptionsByDeprecated($resolvedFormType); } - $formOptions = $this->normalizeAndSortOptionsColumns(array_filter(array( + $formOptions = $this->normalizeAndSortOptionsColumns(array_filter([ 'own' => $this->ownOptions, 'overridden' => $this->overriddenOptions, 'parent' => $this->parentOptions, 'extension' => $this->extensionOptions, - ))); + ])); // setting headers and column order - $tableHeaders = array_intersect_key(array( + $tableHeaders = array_intersect_key([ 'own' => 'Options', 'overridden' => 'Overridden options', 'parent' => 'Parent options', 'extension' => 'Extension options', - ), $formOptions); + ], $formOptions); $this->output->title(sprintf('%s (Block prefix: "%s")', \get_class($resolvedFormType->getInnerType()), $resolvedFormType->getInnerType()->getBlockPrefix())); @@ -98,42 +98,42 @@ class TextDescriptor extends Descriptor $definition = $this->getOptionDefinition($optionsResolver, $options['option']); $dump = $this->getDumpFunction(); - $map = array(); + $map = []; if ($definition['deprecated']) { - $map = array( + $map = [ 'Deprecated' => 'deprecated', 'Deprecation message' => 'deprecationMessage', - ); + ]; } - $map += array( + $map += [ 'Required' => 'required', 'Default' => 'default', 'Allowed types' => 'allowedTypes', 'Allowed values' => 'allowedValues', 'Normalizer' => 'normalizer', - ); - $rows = array(); + ]; + $rows = []; foreach ($map as $label => $name) { $value = array_key_exists($name, $definition) ? $dump($definition[$name]) : '-'; if ('default' === $name && isset($definition['lazy'])) { $value = "Value: $value\n\nClosure(s): ".$dump($definition['lazy']); } - $rows[] = array("$label", $value); + $rows[] = ["$label", $value]; $rows[] = new TableSeparator(); } array_pop($rows); $this->output->title(sprintf('%s (%s)', \get_class($options['type']), $options['option'])); - $this->output->table(array(), $rows); + $this->output->table([], $rows); } private function buildTableRows(array $headers, array $options): array { - $tableRows = array(); + $tableRows = []; $count = \count(max($options)); for ($i = 0; $i < $count; ++$i) { - $cells = array(); + $cells = []; foreach (array_keys($headers) as $group) { $option = $options[$group][$i] ?? null; if (\is_string($option) && \in_array($option, $this->requiredOptions, true)) { @@ -161,7 +161,7 @@ class TextDescriptor extends Descriptor } if (!$sorted) { - $options[$group] = array(); + $options[$group] = []; } else { $options[$group][] = null; } @@ -184,15 +184,15 @@ class TextDescriptor extends Descriptor private function getDumpFunction() { $cloner = new VarCloner(); - $cloner->addCasters(array('Closure' => function ($c, $a) { + $cloner->addCasters(['Closure' => function ($c, $a) { $prefix = Caster::PREFIX_VIRTUAL; - return array( + return [ $prefix.'parameters' => isset($a[$prefix.'parameters']) ? \count($a[$prefix.'parameters']->value) : 0, $prefix.'file' => $a[$prefix.'file'], $prefix.'line' => $a[$prefix.'line'], - ); - })); + ]; + }]); $dumper = new CliDumper(null, null, CliDumper::DUMP_LIGHT_ARRAY | CliDumper::DUMP_COMMA_SEPARATOR); $dumper->setColors($this->output->isDecorated()); diff --git a/src/Symfony/Component/Form/Extension/Core/Type/FormType.php b/src/Symfony/Component/Form/Extension/Core/Type/FormType.php index decc9e380d..31757e2887 100644 --- a/src/Symfony/Component/Form/Extension/Core/Type/FormType.php +++ b/src/Symfony/Component/Form/Extension/Core/Type/FormType.php @@ -81,7 +81,7 @@ class FormType extends BaseType } $formConfig = $form->getConfig(); - $view->vars = array_replace($view->vars, array( + $view->vars = array_replace($view->vars, [ 'errors' => $form->getErrors(), 'valid' => $form->isSubmitted() ? $form->isValid() : true, 'value' => $form->getViewData(), @@ -95,7 +95,7 @@ class FormType extends BaseType 'method' => $formConfig->getMethod(), 'action' => $formConfig->getAction(), 'submitted' => $form->isSubmitted(), - )); + ]); } /** @@ -138,7 +138,7 @@ class FormType extends BaseType } return function (FormInterface $form) { - return $form->getConfig()->getCompound() ? array() : ''; + return $form->getConfig()->getCompound() ? [] : ''; }; }; @@ -157,11 +157,11 @@ class FormType extends BaseType // If data is given, the form is locked to that data // (independent of its value) - $resolver->setDefined(array( + $resolver->setDefined([ 'data', - )); + ]); - $resolver->setDefaults(array( + $resolver->setDefaults([ 'data_class' => $dataClass, 'empty_data' => $emptyData, 'trim' => true, @@ -170,24 +170,24 @@ class FormType extends BaseType 'mapped' => true, 'by_reference' => true, 'error_bubbling' => $errorBubbling, - 'label_attr' => array(), + 'label_attr' => [], 'inherit_data' => false, 'compound' => true, 'method' => 'POST', // According to RFC 2396 (http://www.ietf.org/rfc/rfc2396.txt) // section 4.2., empty URIs are considered same-document references 'action' => '', - 'attr' => array(), + 'attr' => [], 'post_max_size_message' => 'The uploaded file was too large. Please try to upload a smaller file.', 'upload_max_size_message' => $uploadMaxSizeMessage, // internal 'allow_file_upload' => false, 'help' => null, - 'help_attr' => array(), - )); + 'help_attr' => [], + ]); $resolver->setAllowedTypes('label_attr', 'array'); - $resolver->setAllowedTypes('upload_max_size_message', array('callable')); - $resolver->setAllowedTypes('help', array('string', 'null')); + $resolver->setAllowedTypes('upload_max_size_message', ['callable']); + $resolver->setAllowedTypes('help', ['string', 'null']); $resolver->setAllowedTypes('help_attr', 'array'); } diff --git a/src/Symfony/Component/Form/Extension/Core/Type/IntegerType.php b/src/Symfony/Component/Form/Extension/Core/Type/IntegerType.php index 22f6d9cb35..af52002ebd 100644 --- a/src/Symfony/Component/Form/Extension/Core/Type/IntegerType.php +++ b/src/Symfony/Component/Form/Extension/Core/Type/IntegerType.php @@ -31,14 +31,14 @@ class IntegerType extends AbstractType */ public function configureOptions(OptionsResolver $resolver) { - $resolver->setDefaults(array( + $resolver->setDefaults([ 'grouping' => false, // Integer cast rounds towards 0, so do the same when displaying fractions 'rounding_mode' => IntegerToLocalizedStringTransformer::ROUND_DOWN, 'compound' => false, - )); + ]); - $resolver->setAllowedValues('rounding_mode', array( + $resolver->setAllowedValues('rounding_mode', [ IntegerToLocalizedStringTransformer::ROUND_FLOOR, IntegerToLocalizedStringTransformer::ROUND_DOWN, IntegerToLocalizedStringTransformer::ROUND_HALF_DOWN, @@ -46,10 +46,10 @@ class IntegerType extends AbstractType IntegerToLocalizedStringTransformer::ROUND_HALF_UP, IntegerToLocalizedStringTransformer::ROUND_UP, IntegerToLocalizedStringTransformer::ROUND_CEILING, - )); + ]); $resolver->setDefined('scale'); - $resolver->setAllowedTypes('scale', array('null', 'int')); + $resolver->setAllowedTypes('scale', ['null', 'int']); $resolver->setDeprecated('scale'); } diff --git a/src/Symfony/Component/Form/Extension/Core/Type/TransformationFailureExtension.php b/src/Symfony/Component/Form/Extension/Core/Type/TransformationFailureExtension.php index 2e98acc0da..8712fff99b 100644 --- a/src/Symfony/Component/Form/Extension/Core/Type/TransformationFailureExtension.php +++ b/src/Symfony/Component/Form/Extension/Core/Type/TransformationFailureExtension.php @@ -40,6 +40,6 @@ class TransformationFailureExtension extends AbstractTypeExtension */ public static function getExtendedTypes(): iterable { - return array(FormType::class); + return [FormType::class]; } } diff --git a/src/Symfony/Component/Form/Extension/Csrf/EventListener/CsrfValidationListener.php b/src/Symfony/Component/Form/Extension/Csrf/EventListener/CsrfValidationListener.php index 8d22e7c11e..fe25f1f497 100644 --- a/src/Symfony/Component/Form/Extension/Csrf/EventListener/CsrfValidationListener.php +++ b/src/Symfony/Component/Form/Extension/Csrf/EventListener/CsrfValidationListener.php @@ -74,7 +74,7 @@ class CsrfValidationListener implements EventSubscriberInterface $errorMessage = $this->translator->trans($errorMessage, [], $this->translationDomain); } - $form->addError(new FormError($errorMessage, $errorMessage, array(), null, $csrfToken)); + $form->addError(new FormError($errorMessage, $errorMessage, [], null, $csrfToken)); } if (\is_array($data)) { diff --git a/src/Symfony/Component/Form/Extension/Csrf/Type/FormTypeCsrfExtension.php b/src/Symfony/Component/Form/Extension/Csrf/Type/FormTypeCsrfExtension.php index e3ca321d82..bc7b616b45 100644 --- a/src/Symfony/Component/Form/Extension/Csrf/Type/FormTypeCsrfExtension.php +++ b/src/Symfony/Component/Form/Extension/Csrf/Type/FormTypeCsrfExtension.php @@ -117,6 +117,6 @@ class FormTypeCsrfExtension extends AbstractTypeExtension */ public static function getExtendedTypes(): iterable { - return array(FormType::class); + return [FormType::class]; } } diff --git a/src/Symfony/Component/Form/Extension/DataCollector/Type/DataCollectorTypeExtension.php b/src/Symfony/Component/Form/Extension/DataCollector/Type/DataCollectorTypeExtension.php index 5dffe481cc..d25fd132c0 100644 --- a/src/Symfony/Component/Form/Extension/DataCollector/Type/DataCollectorTypeExtension.php +++ b/src/Symfony/Component/Form/Extension/DataCollector/Type/DataCollectorTypeExtension.php @@ -48,6 +48,6 @@ class DataCollectorTypeExtension extends AbstractTypeExtension */ public static function getExtendedTypes(): iterable { - return array(FormType::class); + return [FormType::class]; } } diff --git a/src/Symfony/Component/Form/Extension/DependencyInjection/DependencyInjectionExtension.php b/src/Symfony/Component/Form/Extension/DependencyInjection/DependencyInjectionExtension.php index 5f4fc3d81d..a0a82495bd 100644 --- a/src/Symfony/Component/Form/Extension/DependencyInjection/DependencyInjectionExtension.php +++ b/src/Symfony/Component/Form/Extension/DependencyInjection/DependencyInjectionExtension.php @@ -59,13 +59,13 @@ class DependencyInjectionExtension implements FormExtensionInterface $extensions[] = $extension; if (method_exists($extension, 'getExtendedTypes')) { - $extendedTypes = array(); + $extendedTypes = []; foreach ($extension::getExtendedTypes() as $extendedType) { $extendedTypes[] = $extendedType; } } else { - $extendedTypes = array($extension->getExtendedType()); + $extendedTypes = [$extension->getExtendedType()]; } // validate the result of getExtendedTypes()/getExtendedType() to ensure it is consistent with the service definition diff --git a/src/Symfony/Component/Form/Extension/HttpFoundation/Type/FormTypeHttpFoundationExtension.php b/src/Symfony/Component/Form/Extension/HttpFoundation/Type/FormTypeHttpFoundationExtension.php index c3551d55e0..33b053b3a3 100644 --- a/src/Symfony/Component/Form/Extension/HttpFoundation/Type/FormTypeHttpFoundationExtension.php +++ b/src/Symfony/Component/Form/Extension/HttpFoundation/Type/FormTypeHttpFoundationExtension.php @@ -42,6 +42,6 @@ class FormTypeHttpFoundationExtension extends AbstractTypeExtension */ public static function getExtendedTypes(): iterable { - return array(FormType::class); + return [FormType::class]; } } diff --git a/src/Symfony/Component/Form/Extension/Validator/Type/FormTypeValidatorExtension.php b/src/Symfony/Component/Form/Extension/Validator/Type/FormTypeValidatorExtension.php index 66c27ffc8c..9de782ffc9 100644 --- a/src/Symfony/Component/Form/Extension/Validator/Type/FormTypeValidatorExtension.php +++ b/src/Symfony/Component/Form/Extension/Validator/Type/FormTypeValidatorExtension.php @@ -70,6 +70,6 @@ class FormTypeValidatorExtension extends BaseValidatorExtension */ public static function getExtendedTypes(): iterable { - return array(FormType::class); + return [FormType::class]; } } diff --git a/src/Symfony/Component/Form/Extension/Validator/Type/RepeatedTypeValidatorExtension.php b/src/Symfony/Component/Form/Extension/Validator/Type/RepeatedTypeValidatorExtension.php index d868f8a6cb..4bda0b27d1 100644 --- a/src/Symfony/Component/Form/Extension/Validator/Type/RepeatedTypeValidatorExtension.php +++ b/src/Symfony/Component/Form/Extension/Validator/Type/RepeatedTypeValidatorExtension.php @@ -41,6 +41,6 @@ class RepeatedTypeValidatorExtension extends AbstractTypeExtension */ public static function getExtendedTypes(): iterable { - return array(RepeatedType::class); + return [RepeatedType::class]; } } diff --git a/src/Symfony/Component/Form/Extension/Validator/Type/SubmitTypeValidatorExtension.php b/src/Symfony/Component/Form/Extension/Validator/Type/SubmitTypeValidatorExtension.php index ef14faa99b..ea273d0ad9 100644 --- a/src/Symfony/Component/Form/Extension/Validator/Type/SubmitTypeValidatorExtension.php +++ b/src/Symfony/Component/Form/Extension/Validator/Type/SubmitTypeValidatorExtension.php @@ -23,6 +23,6 @@ class SubmitTypeValidatorExtension extends BaseValidatorExtension */ public static function getExtendedTypes(): iterable { - return array(SubmitType::class); + return [SubmitType::class]; } } diff --git a/src/Symfony/Component/Form/Extension/Validator/Type/UploadValidatorExtension.php b/src/Symfony/Component/Form/Extension/Validator/Type/UploadValidatorExtension.php index 97ffc14bde..c5b71f903c 100644 --- a/src/Symfony/Component/Form/Extension/Validator/Type/UploadValidatorExtension.php +++ b/src/Symfony/Component/Form/Extension/Validator/Type/UploadValidatorExtension.php @@ -58,6 +58,6 @@ class UploadValidatorExtension extends AbstractTypeExtension */ public static function getExtendedTypes(): iterable { - return array(FormType::class); + return [FormType::class]; } } diff --git a/src/Symfony/Component/Form/Form.php b/src/Symfony/Component/Form/Form.php index ff79db648c..11056ae425 100644 --- a/src/Symfony/Component/Form/Form.php +++ b/src/Symfony/Component/Form/Form.php @@ -808,7 +808,7 @@ class Form implements \IteratorAggregate, FormInterface, ClearableErrorsInterfac */ public function clearErrors(bool $deep = false): self { - $this->errors = array(); + $this->errors = []; if ($deep) { // Clear errors from children diff --git a/src/Symfony/Component/Form/FormConfigBuilder.php b/src/Symfony/Component/Form/FormConfigBuilder.php index 5040363e3e..344751b159 100644 --- a/src/Symfony/Component/Form/FormConfigBuilder.php +++ b/src/Symfony/Component/Form/FormConfigBuilder.php @@ -82,12 +82,12 @@ class FormConfigBuilder implements FormConfigBuilderInterface /** * @var array */ - private $viewTransformers = array(); + private $viewTransformers = []; /** * @var array */ - private $modelTransformers = array(); + private $modelTransformers = []; /** * @var DataMapperInterface @@ -117,7 +117,7 @@ class FormConfigBuilder implements FormConfigBuilderInterface /** * @var array */ - private $attributes = array(); + private $attributes = []; /** * @var mixed @@ -175,7 +175,7 @@ class FormConfigBuilder implements FormConfigBuilderInterface * @throws InvalidArgumentException if the data class is not a valid class or if * the name contains invalid characters */ - public function __construct($name, ?string $dataClass, EventDispatcherInterface $dispatcher, array $options = array()) + public function __construct($name, ?string $dataClass, EventDispatcherInterface $dispatcher, array $options = []) { self::validateName($name); @@ -244,7 +244,7 @@ class FormConfigBuilder implements FormConfigBuilderInterface throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); } - $this->viewTransformers = array(); + $this->viewTransformers = []; return $this; } @@ -276,7 +276,7 @@ class FormConfigBuilder implements FormConfigBuilderInterface throw new BadMethodCallException('FormConfigBuilder methods cannot be accessed anymore once the builder is turned into a FormConfigInterface instance.'); } - $this->modelTransformers = array(); + $this->modelTransformers = []; return $this; } diff --git a/src/Symfony/Component/Form/Tests/Command/DebugCommandTest.php b/src/Symfony/Component/Form/Tests/Command/DebugCommandTest.php index cc549a4bec..3f4f3b1bff 100644 --- a/src/Symfony/Component/Form/Tests/Command/DebugCommandTest.php +++ b/src/Symfony/Component/Form/Tests/Command/DebugCommandTest.php @@ -28,7 +28,7 @@ class DebugCommandTest extends TestCase public function testDebugDefaults() { $tester = $this->createCommandTester(); - $ret = $tester->execute(array(), array('decorated' => false)); + $ret = $tester->execute([], ['decorated' => false]); $this->assertEquals(0, $ret, 'Returns 0 in case of success'); $this->assertContains('Built-in form types', $tester->getDisplay()); @@ -36,8 +36,8 @@ class DebugCommandTest extends TestCase public function testDebugDeprecatedDefaults() { - $tester = $this->createCommandTester(array('Symfony\Component\Form\Tests\Console\Descriptor'), array(TextType::class, FooType::class)); - $ret = $tester->execute(array('--show-deprecated' => true), array('decorated' => false)); + $tester = $this->createCommandTester(['Symfony\Component\Form\Tests\Console\Descriptor'], [TextType::class, FooType::class]); + $ret = $tester->execute(['--show-deprecated' => true], ['decorated' => false]); $this->assertEquals(0, $ret, 'Returns 0 in case of success'); $this->assertSame(<<createCommandTester(); - $ret = $tester->execute(array('class' => 'FormType'), array('decorated' => false)); + $ret = $tester->execute(['class' => 'FormType'], ['decorated' => false]); $this->assertEquals(0, $ret, 'Returns 0 in case of success'); $this->assertContains('Symfony\Component\Form\Extension\Core\Type\FormType (Block prefix: "form")', $tester->getDisplay()); @@ -69,7 +69,7 @@ TXT public function testDebugFormTypeOption() { $tester = $this->createCommandTester(); - $ret = $tester->execute(array('class' => 'FormType', 'option' => 'method'), array('decorated' => false)); + $ret = $tester->execute(['class' => 'FormType', 'option' => 'method'], ['decorated' => false]); $this->assertEquals(0, $ret, 'Returns 0 in case of success'); $this->assertContains('Symfony\Component\Form\Extension\Core\Type\FormType (method)', $tester->getDisplay()); @@ -82,7 +82,7 @@ TXT public function testDebugSingleFormTypeNotFound() { $tester = $this->createCommandTester(); - $tester->execute(array('class' => 'NonExistentType'), array('decorated' => false, 'interactive' => false)); + $tester->execute(['class' => 'NonExistentType'], ['decorated' => false, 'interactive' => false]); } public function testDebugAmbiguousFormType() @@ -102,23 +102,23 @@ TXT; $this->setExpectedException(InvalidArgumentException::class, $expectedMessage); } - $tester = $this->createCommandTester(array( + $tester = $this->createCommandTester([ 'Symfony\Component\Form\Tests\Fixtures\Debug\A', 'Symfony\Component\Form\Tests\Fixtures\Debug\B', - )); + ]); - $tester->execute(array('class' => 'AmbiguousType'), array('decorated' => false, 'interactive' => false)); + $tester->execute(['class' => 'AmbiguousType'], ['decorated' => false, 'interactive' => false]); } public function testDebugAmbiguousFormTypeInteractive() { - $tester = $this->createCommandTester(array( + $tester = $this->createCommandTester([ 'Symfony\Component\Form\Tests\Fixtures\Debug\A', 'Symfony\Component\Form\Tests\Fixtures\Debug\B', - )); + ]); - $tester->setInputs(array(0)); - $tester->execute(array('class' => 'AmbiguousType'), array('decorated' => false, 'interactive' => true)); + $tester->setInputs([0]); + $tester->execute(['class' => 'AmbiguousType'], ['decorated' => false, 'interactive' => true]); $this->assertEquals(0, $tester->getStatusCode(), 'Returns 0 in case of success'); $output = $tester->getDisplay(true); @@ -141,12 +141,12 @@ TXT */ public function testDebugInvalidFormType() { - $this->createCommandTester()->execute(array('class' => 'test')); + $this->createCommandTester()->execute(['class' => 'test']); } - private function createCommandTester(array $namespaces = array('Symfony\Component\Form\Extension\Core\Type'), array $types = array()) + private function createCommandTester(array $namespaces = ['Symfony\Component\Form\Extension\Core\Type'], array $types = []) { - $formRegistry = new FormRegistry(array(), new ResolvedFormTypeFactory()); + $formRegistry = new FormRegistry([], new ResolvedFormTypeFactory()); $command = new DebugCommand($formRegistry, $namespaces, $types); $application = new Application(); $application->add($command); @@ -166,11 +166,11 @@ class FooType extends AbstractType $foo = $options['foo']; return function (FormInterface $form) use ($foo) { - return $form->getConfig()->getCompound() ? array($foo) : $foo; + return $form->getConfig()->getCompound() ? [$foo] : $foo; }; }); $resolver->setAllowedTypes('foo', 'string'); - $resolver->setAllowedValues('foo', array('bar', 'baz')); + $resolver->setAllowedValues('foo', ['bar', 'baz']); $resolver->setNormalizer('foo', function (Options $options, $value) { return (string) $value; }); diff --git a/src/Symfony/Component/Form/Tests/Console/Descriptor/AbstractDescriptorTest.php b/src/Symfony/Component/Form/Tests/Console/Descriptor/AbstractDescriptorTest.php index 37831608a5..2ace5eef37 100644 --- a/src/Symfony/Component/Form/Tests/Console/Descriptor/AbstractDescriptorTest.php +++ b/src/Symfony/Component/Form/Tests/Console/Descriptor/AbstractDescriptorTest.php @@ -69,28 +69,28 @@ abstract class AbstractDescriptorTest extends TestCase public function getDescribeDefaultsTestData() { - $options['core_types'] = array('Symfony\Component\Form\Extension\Core\Type\FormType'); - $options['service_types'] = array('Symfony\Bridge\Doctrine\Form\Type\EntityType'); - $options['extensions'] = array('Symfony\Component\Form\Extension\Csrf\Type\FormTypeCsrfExtension'); - $options['guessers'] = array('Symfony\Component\Form\Extension\Validator\ValidatorTypeGuesser'); + $options['core_types'] = ['Symfony\Component\Form\Extension\Core\Type\FormType']; + $options['service_types'] = ['Symfony\Bridge\Doctrine\Form\Type\EntityType']; + $options['extensions'] = ['Symfony\Component\Form\Extension\Csrf\Type\FormTypeCsrfExtension']; + $options['guessers'] = ['Symfony\Component\Form\Extension\Validator\ValidatorTypeGuesser']; $options['decorated'] = false; $options['show_deprecated'] = false; - yield array(null, $options, 'defaults_1'); + yield [null, $options, 'defaults_1']; - $options['core_types'] = array(); - $options['service_types'] = array(FooType::class); + $options['core_types'] = []; + $options['service_types'] = [FooType::class]; $options['show_deprecated'] = true; - yield array(null, $options, 'types_with_deprecated_options'); + yield [null, $options, 'types_with_deprecated_options']; } public function getDescribeResolvedFormTypeTestData() { - $typeExtensions = array(new FormTypeCsrfExtension(new CsrfTokenManager())); + $typeExtensions = [new FormTypeCsrfExtension(new CsrfTokenManager())]; $parent = new ResolvedFormType(new FormType(), $typeExtensions); - yield array(new ResolvedFormType(new ChoiceType(), array(), $parent), array('decorated' => false, 'show_deprecated' => false), 'resolved_form_type_1'); - yield array(new ResolvedFormType(new FormType()), array('decorated' => false, 'show_deprecated' => false), 'resolved_form_type_2'); - yield array(new ResolvedFormType(new FooType(), array(), $parent), array('decorated' => false, 'show_deprecated' => true), 'deprecated_options_of_type'); + yield [new ResolvedFormType(new ChoiceType(), [], $parent), ['decorated' => false, 'show_deprecated' => false], 'resolved_form_type_1']; + yield [new ResolvedFormType(new FormType()), ['decorated' => false, 'show_deprecated' => false], 'resolved_form_type_2']; + yield [new ResolvedFormType(new FooType(), [], $parent), ['decorated' => false, 'show_deprecated' => true], 'deprecated_options_of_type']; } public function getDescribeOptionTestData() @@ -99,24 +99,24 @@ abstract class AbstractDescriptorTest extends TestCase $options['decorated'] = false; $options['show_deprecated'] = false; - $resolvedType = new ResolvedFormType(new ChoiceType(), array(), $parent); + $resolvedType = new ResolvedFormType(new ChoiceType(), [], $parent); $options['type'] = $resolvedType->getInnerType(); $options['option'] = 'choice_translation_domain'; - yield array($resolvedType->getOptionsResolver(), $options, 'default_option_with_normalizer'); + yield [$resolvedType->getOptionsResolver(), $options, 'default_option_with_normalizer']; - $resolvedType = new ResolvedFormType(new FooType(), array(), $parent); + $resolvedType = new ResolvedFormType(new FooType(), [], $parent); $options['type'] = $resolvedType->getInnerType(); $options['option'] = 'foo'; - yield array($resolvedType->getOptionsResolver(), $options, 'required_option_with_allowed_values'); + yield [$resolvedType->getOptionsResolver(), $options, 'required_option_with_allowed_values']; $options['option'] = 'empty_data'; - yield array($resolvedType->getOptionsResolver(), $options, 'overridden_option_with_default_closures'); + yield [$resolvedType->getOptionsResolver(), $options, 'overridden_option_with_default_closures']; - $resolvedType = new ResolvedFormType(new FooType(), array(), $parent); + $resolvedType = new ResolvedFormType(new FooType(), [], $parent); $options['type'] = $resolvedType->getInnerType(); $options['option'] = 'bar'; $options['show_deprecated'] = true; - yield array($resolvedType->getOptionsResolver(), $options, 'deprecated_option'); + yield [$resolvedType->getOptionsResolver(), $options, 'deprecated_option']; } abstract protected function getDescriptor(); @@ -126,7 +126,7 @@ abstract class AbstractDescriptorTest extends TestCase private function getObjectDescription($object, array $options) { $output = new BufferedOutput(BufferedOutput::VERBOSITY_NORMAL, $options['decorated']); - $io = new SymfonyStyle(new ArrayInput(array()), $output); + $io = new SymfonyStyle(new ArrayInput([]), $output); $this->getDescriptor()->describe($io, $object, $options); @@ -155,11 +155,11 @@ class FooType extends AbstractType $foo = $options['foo']; return function (FormInterface $form) use ($foo) { - return $form->getConfig()->getCompound() ? array($foo) : $foo; + return $form->getConfig()->getCompound() ? [$foo] : $foo; }; }); $resolver->setAllowedTypes('foo', 'string'); - $resolver->setAllowedValues('foo', array('bar', 'baz')); + $resolver->setAllowedValues('foo', ['bar', 'baz']); $resolver->setNormalizer('foo', function (Options $options, $value) { return (string) $value; }); diff --git a/src/Symfony/Component/Form/Tests/DependencyInjection/FormPassTest.php b/src/Symfony/Component/Form/Tests/DependencyInjection/FormPassTest.php index debbddfdb3..1b202b5df1 100644 --- a/src/Symfony/Component/Form/Tests/DependencyInjection/FormPassTest.php +++ b/src/Symfony/Component/Form/Tests/DependencyInjection/FormPassTest.php @@ -59,10 +59,10 @@ class FormPassTest extends TestCase $extDefinition = $container->getDefinition('form.extension'); $this->assertEquals( - (new Definition(ServiceLocator::class, array(array( + (new Definition(ServiceLocator::class, [[ __CLASS__.'_Type1' => new ServiceClosureArgument(new Reference('my.type1')), __CLASS__.'_Type2' => new ServiceClosureArgument(new Reference('my.type2')), - ))))->addTag('container.service_locator')->setPublic(false), + ]]))->addTag('container.service_locator')->setPublic(false), $extDefinition->getArgument(0) ); } @@ -81,10 +81,10 @@ class FormPassTest extends TestCase $cmdDefinition = $container->getDefinition('console.command.form_debug'); $this->assertEquals( - array( + [ 'Symfony\Component\Form\Extension\Core\Type', __NAMESPACE__, - ), + ], $cmdDefinition->getArgument(1) ); } @@ -110,83 +110,83 @@ class FormPassTest extends TestCase public function addTaggedTypeExtensionsDataProvider() { - return array( - array( - array( - Type1TypeExtension::class => array( + return [ + [ + [ + Type1TypeExtension::class => [ 'class' => Type1TypeExtension::class, - 'tag' => array('extended_type' => 'type1'), - ), - Type1Type2TypeExtension::class => array( + 'tag' => ['extended_type' => 'type1'], + ], + Type1Type2TypeExtension::class => [ 'class' => Type1Type2TypeExtension::class, - 'tag' => array('extended_type' => 'type2'), - ), - ), - array( - 'type1' => new IteratorArgument(array(new Reference(Type1TypeExtension::class))), - 'type2' => new IteratorArgument(array(new Reference(Type1Type2TypeExtension::class))), - ), - ), - array( - array( - Type1TypeExtension::class => array( + 'tag' => ['extended_type' => 'type2'], + ], + ], + [ + 'type1' => new IteratorArgument([new Reference(Type1TypeExtension::class)]), + 'type2' => new IteratorArgument([new Reference(Type1Type2TypeExtension::class)]), + ], + ], + [ + [ + Type1TypeExtension::class => [ 'class' => Type1TypeExtension::class, - 'tag' => array(), - ), - Type1Type2TypeExtension::class => array( + 'tag' => [], + ], + Type1Type2TypeExtension::class => [ 'class' => Type1Type2TypeExtension::class, - 'tag' => array(), - ), - ), - array( - 'type1' => new IteratorArgument(array( + 'tag' => [], + ], + ], + [ + 'type1' => new IteratorArgument([ new Reference(Type1TypeExtension::class), new Reference(Type1Type2TypeExtension::class), - )), - 'type2' => new IteratorArgument(array(new Reference(Type1Type2TypeExtension::class))), - ), - ), - array( - array( - 'my.type_extension1' => array( + ]), + 'type2' => new IteratorArgument([new Reference(Type1Type2TypeExtension::class)]), + ], + ], + [ + [ + 'my.type_extension1' => [ 'class' => Type1TypeExtension::class, - 'tag' => array('extended_type' => 'type1', 'priority' => 1), - ), - 'my.type_extension2' => array( + 'tag' => ['extended_type' => 'type1', 'priority' => 1], + ], + 'my.type_extension2' => [ 'class' => Type1TypeExtension::class, - 'tag' => array('extended_type' => 'type1', 'priority' => 2), - ), - 'my.type_extension3' => array( + 'tag' => ['extended_type' => 'type1', 'priority' => 2], + ], + 'my.type_extension3' => [ 'class' => Type1TypeExtension::class, - 'tag' => array('extended_type' => 'type1', 'priority' => -1), - ), - 'my.type_extension4' => array( + 'tag' => ['extended_type' => 'type1', 'priority' => -1], + ], + 'my.type_extension4' => [ 'class' => Type2TypeExtension::class, - 'tag' => array('extended_type' => 'type2', 'priority' => 2), - ), - 'my.type_extension5' => array( + 'tag' => ['extended_type' => 'type2', 'priority' => 2], + ], + 'my.type_extension5' => [ 'class' => Type2TypeExtension::class, - 'tag' => array('extended_type' => 'type2', 'priority' => 1), - ), - 'my.type_extension6' => array( + 'tag' => ['extended_type' => 'type2', 'priority' => 1], + ], + 'my.type_extension6' => [ 'class' => Type2TypeExtension::class, - 'tag' => array('extended_type' => 'type2', 'priority' => 1), - ), - ), - array( - 'type1' => new IteratorArgument(array( + 'tag' => ['extended_type' => 'type2', 'priority' => 1], + ], + ], + [ + 'type1' => new IteratorArgument([ new Reference('my.type_extension2'), new Reference('my.type_extension1'), new Reference('my.type_extension3'), - )), - 'type2' => new IteratorArgument(array( + ]), + 'type2' => new IteratorArgument([ new Reference('my.type_extension4'), new Reference('my.type_extension5'), new Reference('my.type_extension6'), - )), - ), - ), - ); + ]), + ], + ], + ]; } /** @@ -214,44 +214,44 @@ class FormPassTest extends TestCase */ public function addLegacyTaggedTypeExtensionsDataProvider() { - return array( - array( - array( - 'my.type_extension1' => array('extended_type' => 'type1'), - 'my.type_extension2' => array('extended_type' => 'type1'), - 'my.type_extension3' => array('extended_type' => 'type2'), - ), - array( - 'type1' => new IteratorArgument(array( + return [ + [ + [ + 'my.type_extension1' => ['extended_type' => 'type1'], + 'my.type_extension2' => ['extended_type' => 'type1'], + 'my.type_extension3' => ['extended_type' => 'type2'], + ], + [ + 'type1' => new IteratorArgument([ new Reference('my.type_extension1'), new Reference('my.type_extension2'), - )), - 'type2' => new IteratorArgument(array(new Reference('my.type_extension3'))), - ), - ), - array( - array( - 'my.type_extension1' => array('extended_type' => 'type1', 'priority' => 1), - 'my.type_extension2' => array('extended_type' => 'type1', 'priority' => 2), - 'my.type_extension3' => array('extended_type' => 'type1', 'priority' => -1), - 'my.type_extension4' => array('extended_type' => 'type2', 'priority' => 2), - 'my.type_extension5' => array('extended_type' => 'type2', 'priority' => 1), - 'my.type_extension6' => array('extended_type' => 'type2', 'priority' => 1), - ), - array( - 'type1' => new IteratorArgument(array( + ]), + 'type2' => new IteratorArgument([new Reference('my.type_extension3')]), + ], + ], + [ + [ + 'my.type_extension1' => ['extended_type' => 'type1', 'priority' => 1], + 'my.type_extension2' => ['extended_type' => 'type1', 'priority' => 2], + 'my.type_extension3' => ['extended_type' => 'type1', 'priority' => -1], + 'my.type_extension4' => ['extended_type' => 'type2', 'priority' => 2], + 'my.type_extension5' => ['extended_type' => 'type2', 'priority' => 1], + 'my.type_extension6' => ['extended_type' => 'type2', 'priority' => 1], + ], + [ + 'type1' => new IteratorArgument([ new Reference('my.type_extension2'), new Reference('my.type_extension1'), new Reference('my.type_extension3'), - )), - 'type2' => new IteratorArgument(array( + ]), + 'type2' => new IteratorArgument([ new Reference('my.type_extension4'), new Reference('my.type_extension5'), new Reference('my.type_extension6'), - )), - ), - ), - ); + ]), + ], + ], + ]; } /** @@ -304,10 +304,10 @@ class FormPassTest extends TestCase $extDefinition = $container->getDefinition('form.extension'); $this->assertEquals( - new IteratorArgument(array( + new IteratorArgument([ new Reference('my.guesser1'), new Reference('my.guesser2'), - )), + ]), $extDefinition->getArgument(2) ); } @@ -315,7 +315,7 @@ class FormPassTest extends TestCase /** * @dataProvider privateTaggedServicesProvider */ - public function testPrivateTaggedServices($id, $class, $tagName, callable $assertion, array $tagAttributes = array()) + public function testPrivateTaggedServices($id, $class, $tagName, callable $assertion, array $tagAttributes = []) { $formPass = new FormPass(); $container = new ContainerBuilder(); @@ -329,8 +329,8 @@ class FormPassTest extends TestCase public function privateTaggedServicesProvider() { - return array( - array( + return [ + [ 'my.type', 'stdClass', 'form.type', @@ -340,41 +340,41 @@ class FormPassTest extends TestCase $this->assertInstanceOf(Reference::class, $formTypes); $locator = $container->getDefinition((string) $formTypes); - $expectedLocatorMap = array( + $expectedLocatorMap = [ 'stdClass' => new ServiceClosureArgument(new Reference('my.type')), - ); + ]; $this->assertInstanceOf(Definition::class, $locator); $this->assertEquals($expectedLocatorMap, $locator->getArgument(0)); }, - ), - array( + ], + [ 'my.type_extension', Type1TypeExtension::class, 'form.type_extension', function (ContainerBuilder $container) { $this->assertEquals( - array('Symfony\Component\Form\Extension\Core\Type\FormType' => new IteratorArgument(array(new Reference('my.type_extension')))), + ['Symfony\Component\Form\Extension\Core\Type\FormType' => new IteratorArgument([new Reference('my.type_extension')])], $container->getDefinition('form.extension')->getArgument(1) ); }, - array('extended_type' => 'Symfony\Component\Form\Extension\Core\Type\FormType'), - ), - array('my.guesser', 'stdClass', 'form.type_guesser', function (ContainerBuilder $container) { - $this->assertEquals(new IteratorArgument(array(new Reference('my.guesser'))), $container->getDefinition('form.extension')->getArgument(2)); - }), - ); + ['extended_type' => 'Symfony\Component\Form\Extension\Core\Type\FormType'], + ], + ['my.guesser', 'stdClass', 'form.type_guesser', function (ContainerBuilder $container) { + $this->assertEquals(new IteratorArgument([new Reference('my.guesser')]), $container->getDefinition('form.extension')->getArgument(2)); + }], + ]; } private function createExtensionDefinition() { $definition = new Definition('Symfony\Component\Form\Extension\DependencyInjection\DependencyInjectionExtension'); $definition->setPublic(true); - $definition->setArguments(array( - array(), - array(), - new IteratorArgument(array()), - )); + $definition->setArguments([ + [], + [], + new IteratorArgument([]), + ]); return $definition; } @@ -383,11 +383,11 @@ class FormPassTest extends TestCase { $definition = new Definition('Symfony\Component\Form\Command\DebugCommand'); $definition->setPublic(true); - $definition->setArguments(array( + $definition->setArguments([ $formRegistry = $this->getMockBuilder(FormRegistryInterface::class)->getMock(), - array(), - array('Symfony\Component\Form\Extension\Core\Type'), - )); + [], + ['Symfony\Component\Form\Extension\Core\Type'], + ]); return $definition; } @@ -413,7 +413,7 @@ class Type1TypeExtension extends AbstractTypeExtension { public static function getExtendedTypes(): iterable { - return array('type1'); + return ['type1']; } } @@ -421,7 +421,7 @@ class Type2TypeExtension extends AbstractTypeExtension { public static function getExtendedTypes(): iterable { - return array('type2'); + return ['type2']; } } @@ -438,6 +438,6 @@ class WithoutExtendedTypesTypeExtension extends AbstractTypeExtension { public static function getExtendedTypes(): iterable { - return array(); + return []; } } diff --git a/src/Symfony/Component/Form/Tests/Extension/Csrf/Type/FormTypeCsrfExtensionTest.php b/src/Symfony/Component/Form/Tests/Extension/Csrf/Type/FormTypeCsrfExtensionTest.php index 3838ca21de..5478db9b83 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Csrf/Type/FormTypeCsrfExtensionTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Csrf/Type/FormTypeCsrfExtensionTest.php @@ -391,7 +391,7 @@ class FormTypeCsrfExtensionTest extends TypeTestCase ]); $errors = $form->getErrors(); - $expected = new FormError('[trans]Foobar[/trans]', null, array(), null, $csrfToken); + $expected = new FormError('[trans]Foobar[/trans]', null, [], null, $csrfToken); $expected->setOrigin($form); $this->assertGreaterThan(0, \count($errors)); diff --git a/src/Symfony/Component/Form/Tests/Extension/DependencyInjection/DependencyInjectionExtensionTest.php b/src/Symfony/Component/Form/Tests/Extension/DependencyInjection/DependencyInjectionExtensionTest.php index 9d8020b078..0498c764d1 100644 --- a/src/Symfony/Component/Form/Tests/Extension/DependencyInjection/DependencyInjectionExtensionTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/DependencyInjection/DependencyInjectionExtensionTest.php @@ -29,18 +29,18 @@ class DependencyInjectionExtensionTest extends TestCase $typeExtension3 = new OtherTypeExtension(); $typeExtension4 = new MultipleTypesTypeExtension(); - $extensions = array( - 'test' => new \ArrayIterator(array($typeExtension1, $typeExtension2, $typeExtension4)), - 'other' => new \ArrayIterator(array($typeExtension3, $typeExtension4)), - ); + $extensions = [ + 'test' => new \ArrayIterator([$typeExtension1, $typeExtension2, $typeExtension4]), + 'other' => new \ArrayIterator([$typeExtension3, $typeExtension4]), + ]; - $extension = new DependencyInjectionExtension($container, $extensions, array()); + $extension = new DependencyInjectionExtension($container, $extensions, []); $this->assertTrue($extension->hasTypeExtensions('test')); $this->assertTrue($extension->hasTypeExtensions('other')); $this->assertFalse($extension->hasTypeExtensions('unknown')); - $this->assertSame(array($typeExtension1, $typeExtension2, $typeExtension4), $extension->getTypeExtensions('test')); - $this->assertSame(array($typeExtension3, $typeExtension4), $extension->getTypeExtensions('other')); + $this->assertSame([$typeExtension1, $typeExtension2, $typeExtension4], $extension->getTypeExtensions('test')); + $this->assertSame([$typeExtension3, $typeExtension4], $extension->getTypeExtensions('other')); } /** @@ -51,11 +51,11 @@ class DependencyInjectionExtensionTest extends TestCase $container = $this->getMockBuilder('Psr\Container\ContainerInterface')->getMock(); $container->expects($this->never())->method('get'); - $extensions = array( - 'unmatched' => new \ArrayIterator(array(new TestTypeExtension())), - ); + $extensions = [ + 'unmatched' => new \ArrayIterator([new TestTypeExtension()]), + ]; - $extension = new DependencyInjectionExtension($container, $extensions, array()); + $extension = new DependencyInjectionExtension($container, $extensions, []); $extension->getTypeExtensions('unmatched'); } @@ -63,7 +63,7 @@ class DependencyInjectionExtensionTest extends TestCase public function testGetTypeGuesser() { $container = $this->createContainerMock(); - $extension = new DependencyInjectionExtension($container, array(), array($this->getMockBuilder(FormTypeGuesserInterface::class)->getMock())); + $extension = new DependencyInjectionExtension($container, [], [$this->getMockBuilder(FormTypeGuesserInterface::class)->getMock()]); $this->assertInstanceOf(FormTypeGuesserChain::class, $extension->getTypeGuesser()); } @@ -71,7 +71,7 @@ class DependencyInjectionExtensionTest extends TestCase public function testGetTypeGuesserReturnsNullWhenNoTypeGuessersHaveBeenConfigured() { $container = $this->createContainerMock(); - $extension = new DependencyInjectionExtension($container, array(), array()); + $extension = new DependencyInjectionExtension($container, [], []); $this->assertNull($extension->getTypeGuesser()); } @@ -79,7 +79,7 @@ class DependencyInjectionExtensionTest extends TestCase private function createContainerMock() { return $this->getMockBuilder('Psr\Container\ContainerInterface') - ->setMethods(array('get', 'has')) + ->setMethods(['get', 'has']) ->getMock(); } } @@ -88,7 +88,7 @@ class TestTypeExtension extends AbstractTypeExtension { public static function getExtendedTypes(): iterable { - return array('test'); + return ['test']; } } @@ -96,7 +96,7 @@ class OtherTypeExtension extends AbstractTypeExtension { public static function getExtendedTypes(): iterable { - return array('other'); + return ['other']; } } diff --git a/src/Symfony/Component/Form/Tests/Fixtures/ChoiceTypeExtension.php b/src/Symfony/Component/Form/Tests/Fixtures/ChoiceTypeExtension.php index 97f8980b7a..34242c5b69 100644 --- a/src/Symfony/Component/Form/Tests/Fixtures/ChoiceTypeExtension.php +++ b/src/Symfony/Component/Form/Tests/Fixtures/ChoiceTypeExtension.php @@ -34,6 +34,6 @@ class ChoiceTypeExtension extends AbstractTypeExtension */ public static function getExtendedTypes(): iterable { - return array(self::$extendedType); + return [self::$extendedType]; } } diff --git a/src/Symfony/Component/Form/Tests/Fixtures/FooTypeBarExtension.php b/src/Symfony/Component/Form/Tests/Fixtures/FooTypeBarExtension.php index de49bd3ef7..fbe1601d5b 100644 --- a/src/Symfony/Component/Form/Tests/Fixtures/FooTypeBarExtension.php +++ b/src/Symfony/Component/Form/Tests/Fixtures/FooTypeBarExtension.php @@ -30,6 +30,6 @@ class FooTypeBarExtension extends AbstractTypeExtension public static function getExtendedTypes(): iterable { - return array(__NAMESPACE__.'\FooType'); + return [__NAMESPACE__.'\FooType']; } } diff --git a/src/Symfony/Component/Form/Tests/Fixtures/FooTypeBazExtension.php b/src/Symfony/Component/Form/Tests/Fixtures/FooTypeBazExtension.php index 1f722776e0..250c122f9c 100644 --- a/src/Symfony/Component/Form/Tests/Fixtures/FooTypeBazExtension.php +++ b/src/Symfony/Component/Form/Tests/Fixtures/FooTypeBazExtension.php @@ -23,6 +23,6 @@ class FooTypeBazExtension extends AbstractTypeExtension public static function getExtendedTypes(): iterable { - return array(__NAMESPACE__.'\FooType'); + return [__NAMESPACE__.'\FooType']; } } diff --git a/src/Symfony/Component/Form/Tests/Fixtures/LazyChoiceTypeExtension.php b/src/Symfony/Component/Form/Tests/Fixtures/LazyChoiceTypeExtension.php index 044464eb94..e25d84c8bd 100644 --- a/src/Symfony/Component/Form/Tests/Fixtures/LazyChoiceTypeExtension.php +++ b/src/Symfony/Component/Form/Tests/Fixtures/LazyChoiceTypeExtension.php @@ -37,6 +37,6 @@ class LazyChoiceTypeExtension extends AbstractTypeExtension */ public static function getExtendedTypes(): iterable { - return array(self::$extendedType); + return [self::$extendedType]; } } diff --git a/src/Symfony/Component/Form/Tests/Fixtures/TestExtension.php b/src/Symfony/Component/Form/Tests/Fixtures/TestExtension.php index 0173bae6f9..578db1242c 100644 --- a/src/Symfony/Component/Form/Tests/Fixtures/TestExtension.php +++ b/src/Symfony/Component/Form/Tests/Fixtures/TestExtension.php @@ -18,9 +18,9 @@ use Symfony\Component\Form\FormTypeInterface; class TestExtension implements FormExtensionInterface { - private $types = array(); + private $types = []; - private $extensions = array(); + private $extensions = []; private $guesser; @@ -48,7 +48,7 @@ class TestExtension implements FormExtensionInterface { foreach ($extension::getExtendedTypes() as $type) { if (!isset($this->extensions[$type])) { - $this->extensions[$type] = array(); + $this->extensions[$type] = []; } $this->extensions[$type][] = $extension; @@ -57,7 +57,7 @@ class TestExtension implements FormExtensionInterface public function getTypeExtensions($name) { - return isset($this->extensions[$name]) ? $this->extensions[$name] : array(); + return isset($this->extensions[$name]) ? $this->extensions[$name] : []; } public function hasTypeExtensions($name) diff --git a/src/Symfony/Component/HttpFoundation/HeaderUtils.php b/src/Symfony/Component/HttpFoundation/HeaderUtils.php index 570ea1a83c..31db1bd0de 100644 --- a/src/Symfony/Component/HttpFoundation/HeaderUtils.php +++ b/src/Symfony/Component/HttpFoundation/HeaderUtils.php @@ -163,7 +163,7 @@ class HeaderUtils */ public static function makeDisposition(string $disposition, string $filename, string $filenameFallback = ''): string { - if (!\in_array($disposition, array(self::DISPOSITION_ATTACHMENT, self::DISPOSITION_INLINE))) { + if (!\in_array($disposition, [self::DISPOSITION_ATTACHMENT, self::DISPOSITION_INLINE])) { throw new \InvalidArgumentException(sprintf('The disposition must be either "%s" or "%s".', self::DISPOSITION_ATTACHMENT, self::DISPOSITION_INLINE)); } @@ -186,7 +186,7 @@ class HeaderUtils throw new \InvalidArgumentException('The filename and the fallback cannot contain the "/" and "\\" characters.'); } - $params = array('filename' => $filenameFallback); + $params = ['filename' => $filenameFallback]; if ($filename !== $filenameFallback) { $params['filename*'] = "utf-8''".rawurlencode($filename); } diff --git a/src/Symfony/Component/HttpFoundation/Request.php b/src/Symfony/Component/HttpFoundation/Request.php index c13016e522..7f44aab1d5 100644 --- a/src/Symfony/Component/HttpFoundation/Request.php +++ b/src/Symfony/Component/HttpFoundation/Request.php @@ -52,17 +52,17 @@ class Request /** * @var string[] */ - protected static $trustedProxies = array(); + protected static $trustedProxies = []; /** * @var string[] */ - protected static $trustedHostPatterns = array(); + protected static $trustedHostPatterns = []; /** * @var string[] */ - protected static $trustedHosts = array(); + protected static $trustedHosts = []; protected static $httpMethodParameterOverride = false; @@ -197,12 +197,12 @@ class Request private static $trustedHeaderSet = -1; - private static $forwardedParams = array( + private static $forwardedParams = [ self::HEADER_X_FORWARDED_FOR => 'for', self::HEADER_X_FORWARDED_HOST => 'host', self::HEADER_X_FORWARDED_PROTO => 'proto', self::HEADER_X_FORWARDED_PORT => 'host', - ); + ]; /** * Names for headers that can be trusted when @@ -213,13 +213,13 @@ class Request * The other headers are non-standard, but widely used * by popular reverse proxies (like Apache mod_proxy or Amazon EC2). */ - private static $trustedHeaders = array( + private static $trustedHeaders = [ self::HEADER_FORWARDED => 'FORWARDED', self::HEADER_X_FORWARDED_FOR => 'X_FORWARDED_FOR', self::HEADER_X_FORWARDED_HOST => 'X_FORWARDED_HOST', self::HEADER_X_FORWARDED_PROTO => 'X_FORWARDED_PROTO', self::HEADER_X_FORWARDED_PORT => 'X_FORWARDED_PORT', - ); + ]; /** * @param array $query The GET parameters @@ -230,7 +230,7 @@ class Request * @param array $server The SERVER parameters * @param string|resource|null $content The raw body data */ - public function __construct(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null) + public function __construct(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null) { $this->initialize($query, $request, $attributes, $cookies, $files, $server, $content); } @@ -248,7 +248,7 @@ class Request * @param array $server The SERVER parameters * @param string|resource|null $content The raw body data */ - public function initialize(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null) + public function initialize(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null) { $this->request = new ParameterBag($request); $this->query = new ParameterBag($query); @@ -278,10 +278,10 @@ class Request */ public static function createFromGlobals() { - $request = self::createRequestFromFactory($_GET, $_POST, array(), $_COOKIE, $_FILES, $_SERVER); + $request = self::createRequestFromFactory($_GET, $_POST, [], $_COOKIE, $_FILES, $_SERVER); if (0 === strpos($request->headers->get('CONTENT_TYPE'), 'application/x-www-form-urlencoded') - && \in_array(strtoupper($request->server->get('REQUEST_METHOD', 'GET')), array('PUT', 'DELETE', 'PATCH')) + && \in_array(strtoupper($request->server->get('REQUEST_METHOD', 'GET')), ['PUT', 'DELETE', 'PATCH']) ) { parse_str($request->getContent(), $data); $request->request = new ParameterBag($data); @@ -306,9 +306,9 @@ class Request * * @return static */ - public static function create($uri, $method = 'GET', $parameters = array(), $cookies = array(), $files = array(), $server = array(), $content = null) + public static function create($uri, $method = 'GET', $parameters = [], $cookies = [], $files = [], $server = [], $content = null) { - $server = array_replace(array( + $server = array_replace([ 'SERVER_NAME' => 'localhost', 'SERVER_PORT' => 80, 'HTTP_HOST' => 'localhost', @@ -321,7 +321,7 @@ class Request 'SCRIPT_FILENAME' => '', 'SERVER_PROTOCOL' => 'HTTP/1.1', 'REQUEST_TIME' => time(), - ), $server); + ], $server); $server['PATH_INFO'] = ''; $server['REQUEST_METHOD'] = strtoupper($method); @@ -369,10 +369,10 @@ class Request // no break case 'PATCH': $request = $parameters; - $query = array(); + $query = []; break; default: - $request = array(); + $request = []; $query = $parameters; break; } @@ -395,7 +395,7 @@ class Request $server['REQUEST_URI'] = $components['path'].('' !== $queryString ? '?'.$queryString : ''); $server['QUERY_STRING'] = $queryString; - return self::createRequestFromFactory($query, $request, array(), $cookies, $files, $server, $content); + return self::createRequestFromFactory($query, $request, [], $cookies, $files, $server, $content); } /** @@ -499,7 +499,7 @@ class Request } $cookieHeader = ''; - $cookies = array(); + $cookies = []; foreach ($this->cookies as $k => $v) { $cookies[] = $k.'='.$v; @@ -533,19 +533,19 @@ class Request foreach ($this->headers->all() as $key => $value) { $key = strtoupper(str_replace('-', '_', $key)); - if (\in_array($key, array('CONTENT_TYPE', 'CONTENT_LENGTH'))) { + if (\in_array($key, ['CONTENT_TYPE', 'CONTENT_LENGTH'])) { $_SERVER[$key] = implode(', ', $value); } else { $_SERVER['HTTP_'.$key] = implode(', ', $value); } } - $request = array('g' => $_GET, 'p' => $_POST, 'c' => $_COOKIE); + $request = ['g' => $_GET, 'p' => $_POST, 'c' => $_COOKIE]; $requestOrder = ini_get('request_order') ?: ini_get('variables_order'); $requestOrder = preg_replace('#[^cgp]#', '', strtolower($requestOrder)) ?: 'gp'; - $_REQUEST = array(array()); + $_REQUEST = [[]]; foreach (str_split($requestOrder) as $order) { $_REQUEST[] = $request[$order]; @@ -603,7 +603,7 @@ class Request return sprintf('{%s}i', $hostPattern); }, $hostPatterns); // we need to reset trusted hosts on trusted host patterns change - self::$trustedHosts = array(); + self::$trustedHosts = []; } /** @@ -777,10 +777,10 @@ class Request $ip = $this->server->get('REMOTE_ADDR'); if (!$this->isFromTrustedProxy()) { - return array($ip); + return [$ip]; } - return $this->getTrustedValues(self::HEADER_X_FORWARDED_FOR, $ip) ?: array($ip); + return $this->getTrustedValues(self::HEADER_X_FORWARDED_FOR, $ip) ?: [$ip]; } /** @@ -1114,7 +1114,7 @@ class Request public function isSecure() { if ($this->isFromTrustedProxy() && $proto = $this->getTrustedValues(self::HEADER_X_FORWARDED_PROTO)) { - return \in_array(strtolower($proto[0]), array('https', 'on', 'ssl', '1'), true); + return \in_array(strtolower($proto[0]), ['https', 'on', 'ssl', '1'], true); } $https = $this->server->get('HTTPS'); @@ -1273,7 +1273,7 @@ class Request static::initializeFormats(); } - return isset(static::$formats[$format]) ? static::$formats[$format] : array(); + return isset(static::$formats[$format]) ? static::$formats[$format] : []; } /** @@ -1316,7 +1316,7 @@ class Request static::initializeFormats(); } - static::$formats[$format] = \is_array($mimeTypes) ? $mimeTypes : array($mimeTypes); + static::$formats[$format] = \is_array($mimeTypes) ? $mimeTypes : [$mimeTypes]; } /** @@ -1433,7 +1433,7 @@ class Request throw new \BadMethodCallException('Checking only for cacheable HTTP methods with Symfony\Component\HttpFoundation\Request::isMethodSafe() is not supported.'); } - return \in_array($this->getMethod(), array('GET', 'HEAD', 'OPTIONS', 'TRACE')); + return \in_array($this->getMethod(), ['GET', 'HEAD', 'OPTIONS', 'TRACE']); } /** @@ -1443,7 +1443,7 @@ class Request */ public function isMethodIdempotent() { - return \in_array($this->getMethod(), array('HEAD', 'GET', 'PUT', 'DELETE', 'TRACE', 'OPTIONS', 'PURGE')); + return \in_array($this->getMethod(), ['HEAD', 'GET', 'PUT', 'DELETE', 'TRACE', 'OPTIONS', 'PURGE']); } /** @@ -1455,7 +1455,7 @@ class Request */ public function isMethodCacheable() { - return \in_array($this->getMethod(), array('GET', 'HEAD')); + return \in_array($this->getMethod(), ['GET', 'HEAD']); } /** @@ -1566,7 +1566,7 @@ class Request return $locales[0]; } - $extendedPreferredLanguages = array(); + $extendedPreferredLanguages = []; foreach ($preferredLanguages as $language) { $extendedPreferredLanguages[] = $language; if (false !== $position = strpos($language, '_')) { @@ -1594,7 +1594,7 @@ class Request } $languages = AcceptHeader::fromString($this->headers->get('Accept-Language'))->all(); - $this->languages = array(); + $this->languages = []; foreach ($languages as $lang => $acceptHeaderItem) { if (false !== strpos($lang, '-')) { $codes = explode('-', $lang); @@ -1864,19 +1864,19 @@ class Request */ protected static function initializeFormats() { - static::$formats = array( - 'html' => array('text/html', 'application/xhtml+xml'), - 'txt' => array('text/plain'), - 'js' => array('application/javascript', 'application/x-javascript', 'text/javascript'), - 'css' => array('text/css'), - 'json' => array('application/json', 'application/x-json'), - 'jsonld' => array('application/ld+json'), - 'xml' => array('text/xml', 'application/xml', 'application/x-xml'), - 'rdf' => array('application/rdf+xml'), - 'atom' => array('application/atom+xml'), - 'rss' => array('application/rss+xml'), - 'form' => array('application/x-www-form-urlencoded'), - ); + static::$formats = [ + 'html' => ['text/html', 'application/xhtml+xml'], + 'txt' => ['text/plain'], + 'js' => ['application/javascript', 'application/x-javascript', 'text/javascript'], + 'css' => ['text/css'], + 'json' => ['application/json', 'application/x-json'], + 'jsonld' => ['application/ld+json'], + 'xml' => ['text/xml', 'application/xml', 'application/x-xml'], + 'rdf' => ['application/rdf+xml'], + 'atom' => ['application/atom+xml'], + 'rss' => ['application/rss+xml'], + 'form' => ['application/x-www-form-urlencoded'], + ]; } private function setPhpDefaultLocale(string $locale) @@ -1913,7 +1913,7 @@ class Request return false; } - private static function createRequestFromFactory(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null) + private static function createRequestFromFactory(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null) { if (self::$requestFactory) { $request = (self::$requestFactory)($query, $request, $attributes, $cookies, $files, $server, $content); @@ -1943,8 +1943,8 @@ class Request private function getTrustedValues($type, $ip = null) { - $clientValues = array(); - $forwardedValues = array(); + $clientValues = []; + $forwardedValues = []; if ((self::$trustedHeaderSet & $type) && $this->headers->has(self::$trustedHeaders[$type])) { foreach (explode(',', $this->headers->get(self::$trustedHeaders[$type])) as $v) { @@ -1955,7 +1955,7 @@ class Request if ((self::$trustedHeaderSet & self::HEADER_FORWARDED) && $this->headers->has(self::$trustedHeaders[self::HEADER_FORWARDED])) { $forwarded = $this->headers->get(self::$trustedHeaders[self::HEADER_FORWARDED]); $parts = HeaderUtils::split($forwarded, ',;='); - $forwardedValues = array(); + $forwardedValues = []; $param = self::$forwardedParams[$type]; foreach ($parts as $subParts) { if (null === $v = HeaderUtils::combine($subParts)[$param] ?? null) { @@ -1985,7 +1985,7 @@ class Request } if (!$this->isForwardedValid) { - return null !== $ip ? array('0.0.0.0', $ip) : array(); + return null !== $ip ? ['0.0.0.0', $ip] : []; } $this->isForwardedValid = false; @@ -1995,7 +1995,7 @@ class Request private function normalizeAndFilterClientIps(array $clientIps, $ip) { if (!$clientIps) { - return array(); + return []; } $clientIps[] = $ip; // Complete the IP chain with the IP the request actually came from $firstTrustedIp = null; @@ -2031,6 +2031,6 @@ class Request } // Now the IP chain contains only untrusted proxies and the client IP - return $clientIps ? array_reverse($clientIps) : array($firstTrustedIp); + return $clientIps ? array_reverse($clientIps) : [$firstTrustedIp]; } } diff --git a/src/Symfony/Component/HttpFoundation/RequestMatcher.php b/src/Symfony/Component/HttpFoundation/RequestMatcher.php index ab9434f43f..d79c7f2ea2 100644 --- a/src/Symfony/Component/HttpFoundation/RequestMatcher.php +++ b/src/Symfony/Component/HttpFoundation/RequestMatcher.php @@ -36,22 +36,22 @@ class RequestMatcher implements RequestMatcherInterface /** * @var string[] */ - private $methods = array(); + private $methods = []; /** * @var string[] */ - private $ips = array(); + private $ips = []; /** * @var array */ - private $attributes = array(); + private $attributes = []; /** * @var string[] */ - private $schemes = array(); + private $schemes = []; /** * @param string|null $path @@ -61,7 +61,7 @@ class RequestMatcher implements RequestMatcherInterface * @param array $attributes * @param string|string[]|null $schemes */ - public function __construct(string $path = null, string $host = null, $methods = null, $ips = null, array $attributes = array(), $schemes = null, int $port = null) + public function __construct(string $path = null, string $host = null, $methods = null, $ips = null, array $attributes = [], $schemes = null, int $port = null) { $this->matchPath($path); $this->matchHost($host); @@ -82,7 +82,7 @@ class RequestMatcher implements RequestMatcherInterface */ public function matchScheme($scheme) { - $this->schemes = null !== $scheme ? array_map('strtolower', (array) $scheme) : array(); + $this->schemes = null !== $scheme ? array_map('strtolower', (array) $scheme) : []; } /** @@ -132,7 +132,7 @@ class RequestMatcher implements RequestMatcherInterface */ public function matchIps($ips) { - $this->ips = null !== $ips ? (array) $ips : array(); + $this->ips = null !== $ips ? (array) $ips : []; } /** @@ -142,7 +142,7 @@ class RequestMatcher implements RequestMatcherInterface */ public function matchMethod($method) { - $this->methods = null !== $method ? array_map('strtoupper', (array) $method) : array(); + $this->methods = null !== $method ? array_map('strtoupper', (array) $method) : []; } /** diff --git a/src/Symfony/Component/HttpFoundation/ResponseHeaderBag.php b/src/Symfony/Component/HttpFoundation/ResponseHeaderBag.php index 1141e8d987..9dd8908b27 100644 --- a/src/Symfony/Component/HttpFoundation/ResponseHeaderBag.php +++ b/src/Symfony/Component/HttpFoundation/ResponseHeaderBag.php @@ -24,11 +24,11 @@ class ResponseHeaderBag extends HeaderBag const DISPOSITION_ATTACHMENT = 'attachment'; const DISPOSITION_INLINE = 'inline'; - protected $computedCacheControl = array(); - protected $cookies = array(); - protected $headerNames = array(); + protected $computedCacheControl = []; + protected $cookies = []; + protected $headerNames = []; - public function __construct(array $headers = array()) + public function __construct(array $headers = []) { parent::__construct($headers); @@ -49,7 +49,7 @@ class ResponseHeaderBag extends HeaderBag */ public function allPreserveCase() { - $headers = array(); + $headers = []; foreach ($this->all() as $name => $value) { $headers[isset($this->headerNames[$name]) ? $this->headerNames[$name] : $name] = $value; } @@ -70,9 +70,9 @@ class ResponseHeaderBag extends HeaderBag /** * {@inheritdoc} */ - public function replace(array $headers = array()) + public function replace(array $headers = []) { - $this->headerNames = array(); + $this->headerNames = []; parent::replace($headers); @@ -107,7 +107,7 @@ class ResponseHeaderBag extends HeaderBag if ('set-cookie' === $uniqueKey) { if ($replace) { - $this->cookies = array(); + $this->cookies = []; } foreach ((array) $values as $cookie) { $this->setCookie(Cookie::fromString($cookie)); @@ -122,9 +122,9 @@ class ResponseHeaderBag extends HeaderBag parent::set($key, $values, $replace); // ensure the cache-control header has sensible defaults - if (\in_array($uniqueKey, array('cache-control', 'etag', 'last-modified', 'expires'), true)) { + if (\in_array($uniqueKey, ['cache-control', 'etag', 'last-modified', 'expires'], true)) { $computed = $this->computeCacheControlValue(); - $this->headers['cache-control'] = array($computed); + $this->headers['cache-control'] = [$computed]; $this->headerNames['cache-control'] = 'Cache-Control'; $this->computedCacheControl = $this->parseCacheControl($computed); } @@ -139,7 +139,7 @@ class ResponseHeaderBag extends HeaderBag unset($this->headerNames[$uniqueKey]); if ('set-cookie' === $uniqueKey) { - $this->cookies = array(); + $this->cookies = []; return; } @@ -147,7 +147,7 @@ class ResponseHeaderBag extends HeaderBag parent::remove($key); if ('cache-control' === $uniqueKey) { - $this->computedCacheControl = array(); + $this->computedCacheControl = []; } if ('date' === $uniqueKey) { @@ -216,15 +216,15 @@ class ResponseHeaderBag extends HeaderBag */ public function getCookies($format = self::COOKIES_FLAT) { - if (!\in_array($format, array(self::COOKIES_FLAT, self::COOKIES_ARRAY))) { - throw new \InvalidArgumentException(sprintf('Format "%s" invalid (%s).', $format, implode(', ', array(self::COOKIES_FLAT, self::COOKIES_ARRAY)))); + if (!\in_array($format, [self::COOKIES_FLAT, self::COOKIES_ARRAY])) { + throw new \InvalidArgumentException(sprintf('Format "%s" invalid (%s).', $format, implode(', ', [self::COOKIES_FLAT, self::COOKIES_ARRAY]))); } if (self::COOKIES_ARRAY === $format) { return $this->cookies; } - $flattenedCookies = array(); + $flattenedCookies = []; foreach ($this->cookies as $path) { foreach ($path as $cookies) { foreach ($cookies as $cookie) { diff --git a/src/Symfony/Component/HttpFoundation/Session/SessionUtils.php b/src/Symfony/Component/HttpFoundation/Session/SessionUtils.php index 91737c39ac..b5bce4a884 100644 --- a/src/Symfony/Component/HttpFoundation/Session/SessionUtils.php +++ b/src/Symfony/Component/HttpFoundation/Session/SessionUtils.php @@ -30,7 +30,7 @@ final class SessionUtils $sessionCookie = null; $sessionCookiePrefix = sprintf(' %s=', urlencode($sessionName)); $sessionCookieWithId = sprintf('%s%s;', $sessionCookiePrefix, urlencode($sessionId)); - $otherCookies = array(); + $otherCookies = []; foreach (headers_list() as $h) { if (0 !== stripos($h, 'Set-Cookie:')) { continue; diff --git a/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/AbstractSessionHandler.php b/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/AbstractSessionHandler.php index 95f110332a..defca606ef 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/AbstractSessionHandler.php +++ b/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/AbstractSessionHandler.php @@ -104,7 +104,7 @@ abstract class AbstractSessionHandler implements \SessionHandlerInterface, \Sess { if (null === $this->igbinaryEmptyData) { // see https://github.com/igbinary/igbinary/issues/146 - $this->igbinaryEmptyData = \function_exists('igbinary_serialize') ? igbinary_serialize(array()) : ''; + $this->igbinaryEmptyData = \function_exists('igbinary_serialize') ? igbinary_serialize([]) : ''; } if ('' === $data || $this->igbinaryEmptyData === $data) { return $this->destroy($sessionId); diff --git a/src/Symfony/Component/HttpFoundation/Tests/HeaderUtilsTest.php b/src/Symfony/Component/HttpFoundation/Tests/HeaderUtilsTest.php index c0425fcfdc..2f82dc4e67 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/HeaderUtilsTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/HeaderUtilsTest.php @@ -101,14 +101,14 @@ class HeaderUtilsTest extends TestCase public function provideMakeDisposition() { - return array( - array('attachment', 'foo.html', 'foo.html', 'attachment; filename=foo.html'), - array('attachment', 'foo.html', '', 'attachment; filename=foo.html'), - array('attachment', 'foo bar.html', '', 'attachment; filename="foo bar.html"'), - array('attachment', 'foo "bar".html', '', 'attachment; filename="foo \\"bar\\".html"'), - array('attachment', 'foo%20bar.html', 'foo bar.html', 'attachment; filename="foo bar.html"; filename*=utf-8\'\'foo%2520bar.html'), - array('attachment', 'föö.html', 'foo.html', 'attachment; filename=foo.html; filename*=utf-8\'\'f%C3%B6%C3%B6.html'), - ); + return [ + ['attachment', 'foo.html', 'foo.html', 'attachment; filename=foo.html'], + ['attachment', 'foo.html', '', 'attachment; filename=foo.html'], + ['attachment', 'foo bar.html', '', 'attachment; filename="foo bar.html"'], + ['attachment', 'foo "bar".html', '', 'attachment; filename="foo \\"bar\\".html"'], + ['attachment', 'foo%20bar.html', 'foo bar.html', 'attachment; filename="foo bar.html"; filename*=utf-8\'\'foo%2520bar.html'], + ['attachment', 'föö.html', 'foo.html', 'attachment; filename=foo.html; filename*=utf-8\'\'f%C3%B6%C3%B6.html'], + ]; } /** @@ -122,13 +122,13 @@ class HeaderUtilsTest extends TestCase public function provideMakeDispositionFail() { - return array( - array('attachment', 'foo%20bar.html'), - array('attachment', 'foo/bar.html'), - array('attachment', '/foo.html'), - array('attachment', 'foo\bar.html'), - array('attachment', '\foo.html'), - array('attachment', 'föö.html'), - ); + return [ + ['attachment', 'foo%20bar.html'], + ['attachment', 'foo/bar.html'], + ['attachment', '/foo.html'], + ['attachment', 'foo\bar.html'], + ['attachment', '\foo.html'], + ['attachment', 'föö.html'], + ]; } } diff --git a/src/Symfony/Component/HttpFoundation/Tests/RequestMatcherTest.php b/src/Symfony/Component/HttpFoundation/Tests/RequestMatcherTest.php index 6bf034dcee..57e9c3d30f 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/RequestMatcherTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/RequestMatcherTest.php @@ -81,7 +81,7 @@ class RequestMatcherTest extends TestCase public function testPort() { $matcher = new RequestMatcher(); - $request = Request::create('', 'get', array(), array(), array(), array('HTTP_HOST' => null, 'SERVER_PORT' => 8000)); + $request = Request::create('', 'get', [], [], [], ['HTTP_HOST' => null, 'SERVER_PORT' => 8000]); $matcher->matchPort(8000); $this->assertTrue($matcher->matches($request)); @@ -89,7 +89,7 @@ class RequestMatcherTest extends TestCase $matcher->matchPort(9000); $this->assertFalse($matcher->matches($request)); - $matcher = new RequestMatcher(null, null, null, null, array(), null, 8000); + $matcher = new RequestMatcher(null, null, null, null, [], null, 8000); $this->assertTrue($matcher->matches($request)); } diff --git a/src/Symfony/Component/HttpFoundation/Tests/ResponseHeaderBagTest.php b/src/Symfony/Component/HttpFoundation/Tests/ResponseHeaderBagTest.php index f6ddb98ea7..35df36c1c6 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/ResponseHeaderBagTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/ResponseHeaderBagTest.php @@ -22,7 +22,7 @@ class ResponseHeaderBagTest extends TestCase { public function testAllPreserveCase() { - $headers = array( + $headers = [ 'fOo' => 'BAR', 'ETag' => 'xyzzy', 'Content-MD5' => 'Q2hlY2sgSW50ZWdyaXR5IQ==', @@ -30,7 +30,7 @@ class ResponseHeaderBagTest extends TestCase 'WWW-Authenticate' => 'Basic realm="WallyWorld"', 'X-UA-Compatible' => 'IE=edge,chrome=1', 'X-XSS-Protection' => '1; mode=block', - ); + ]; $bag = new ResponseHeaderBag($headers); $allPreservedCase = $bag->allPreserveCase(); @@ -42,45 +42,45 @@ class ResponseHeaderBagTest extends TestCase public function testCacheControlHeader() { - $bag = new ResponseHeaderBag(array()); + $bag = new ResponseHeaderBag([]); $this->assertEquals('no-cache, private', $bag->get('Cache-Control')); $this->assertTrue($bag->hasCacheControlDirective('no-cache')); - $bag = new ResponseHeaderBag(array('Cache-Control' => 'public')); + $bag = new ResponseHeaderBag(['Cache-Control' => 'public']); $this->assertEquals('public', $bag->get('Cache-Control')); $this->assertTrue($bag->hasCacheControlDirective('public')); - $bag = new ResponseHeaderBag(array('ETag' => 'abcde')); + $bag = new ResponseHeaderBag(['ETag' => 'abcde']); $this->assertEquals('private, must-revalidate', $bag->get('Cache-Control')); $this->assertTrue($bag->hasCacheControlDirective('private')); $this->assertTrue($bag->hasCacheControlDirective('must-revalidate')); $this->assertFalse($bag->hasCacheControlDirective('max-age')); - $bag = new ResponseHeaderBag(array('Expires' => 'Wed, 16 Feb 2011 14:17:43 GMT')); + $bag = new ResponseHeaderBag(['Expires' => 'Wed, 16 Feb 2011 14:17:43 GMT']); $this->assertEquals('private, must-revalidate', $bag->get('Cache-Control')); - $bag = new ResponseHeaderBag(array( + $bag = new ResponseHeaderBag([ 'Expires' => 'Wed, 16 Feb 2011 14:17:43 GMT', 'Cache-Control' => 'max-age=3600', - )); + ]); $this->assertEquals('max-age=3600, private', $bag->get('Cache-Control')); - $bag = new ResponseHeaderBag(array('Last-Modified' => 'abcde')); + $bag = new ResponseHeaderBag(['Last-Modified' => 'abcde']); $this->assertEquals('private, must-revalidate', $bag->get('Cache-Control')); - $bag = new ResponseHeaderBag(array('Etag' => 'abcde', 'Last-Modified' => 'abcde')); + $bag = new ResponseHeaderBag(['Etag' => 'abcde', 'Last-Modified' => 'abcde']); $this->assertEquals('private, must-revalidate', $bag->get('Cache-Control')); - $bag = new ResponseHeaderBag(array('cache-control' => 'max-age=100')); + $bag = new ResponseHeaderBag(['cache-control' => 'max-age=100']); $this->assertEquals('max-age=100, private', $bag->get('Cache-Control')); - $bag = new ResponseHeaderBag(array('cache-control' => 's-maxage=100')); + $bag = new ResponseHeaderBag(['cache-control' => 's-maxage=100']); $this->assertEquals('s-maxage=100', $bag->get('Cache-Control')); - $bag = new ResponseHeaderBag(array('cache-control' => 'private, max-age=100')); + $bag = new ResponseHeaderBag(['cache-control' => 'private, max-age=100']); $this->assertEquals('max-age=100, private', $bag->get('Cache-Control')); - $bag = new ResponseHeaderBag(array('cache-control' => 'public, max-age=100')); + $bag = new ResponseHeaderBag(['cache-control' => 'public, max-age=100']); $this->assertEquals('max-age=100, public', $bag->get('Cache-Control')); $bag = new ResponseHeaderBag(); @@ -88,7 +88,7 @@ class ResponseHeaderBagTest extends TestCase $this->assertEquals('private, must-revalidate', $bag->get('Cache-Control')); $bag = new ResponseHeaderBag(); - $bag->set('Cache-Control', array('public', 'must-revalidate')); + $bag->set('Cache-Control', ['public', 'must-revalidate']); $this->assertCount(1, $bag->get('Cache-Control', null, false)); $this->assertEquals('must-revalidate, public', $bag->get('Cache-Control')); @@ -101,7 +101,7 @@ class ResponseHeaderBagTest extends TestCase public function testCacheControlClone() { - $headers = array('foo' => 'bar'); + $headers = ['foo' => 'bar']; $bag1 = new ResponseHeaderBag($headers); $bag2 = new ResponseHeaderBag($bag1->allPreserveCase()); $this->assertEquals($bag1->allPreserveCase(), $bag2->allPreserveCase()); @@ -109,7 +109,7 @@ class ResponseHeaderBagTest extends TestCase public function testToStringIncludesCookieHeaders() { - $bag = new ResponseHeaderBag(array()); + $bag = new ResponseHeaderBag([]); $bag->setCookie(Cookie::create('foo', 'bar')); $this->assertSetCookieHeader('foo=bar; path=/; httponly; samesite=lax', $bag); @@ -121,7 +121,7 @@ class ResponseHeaderBagTest extends TestCase public function testClearCookieSecureNotHttpOnly() { - $bag = new ResponseHeaderBag(array()); + $bag = new ResponseHeaderBag([]); $bag->clearCookie('foo', '/', null, true, false); @@ -130,23 +130,23 @@ class ResponseHeaderBagTest extends TestCase public function testReplace() { - $bag = new ResponseHeaderBag(array()); + $bag = new ResponseHeaderBag([]); $this->assertEquals('no-cache, private', $bag->get('Cache-Control')); $this->assertTrue($bag->hasCacheControlDirective('no-cache')); - $bag->replace(array('Cache-Control' => 'public')); + $bag->replace(['Cache-Control' => 'public']); $this->assertEquals('public', $bag->get('Cache-Control')); $this->assertTrue($bag->hasCacheControlDirective('public')); } public function testReplaceWithRemove() { - $bag = new ResponseHeaderBag(array()); + $bag = new ResponseHeaderBag([]); $this->assertEquals('no-cache, private', $bag->get('Cache-Control')); $this->assertTrue($bag->hasCacheControlDirective('no-cache')); $bag->remove('Cache-Control'); - $bag->replace(array()); + $bag->replace([]); $this->assertEquals('no-cache, private', $bag->get('Cache-Control')); $this->assertTrue($bag->hasCacheControlDirective('no-cache')); } @@ -161,12 +161,12 @@ class ResponseHeaderBagTest extends TestCase $this->assertCount(4, $bag->getCookies()); $this->assertEquals('foo=bar; path=/path/foo; domain=foo.bar; httponly; samesite=lax', $bag->get('set-cookie')); - $this->assertEquals(array( + $this->assertEquals([ 'foo=bar; path=/path/foo; domain=foo.bar; httponly; samesite=lax', 'foo=bar; path=/path/bar; domain=foo.bar; httponly; samesite=lax', 'foo=bar; path=/path/bar; domain=bar.foo; httponly; samesite=lax', 'foo=bar; path=/; httponly; samesite=lax', - ), $bag->get('set-cookie', null, false)); + ], $bag->get('set-cookie', null, false)); $this->assertSetCookieHeader('foo=bar; path=/path/foo; domain=foo.bar; httponly; samesite=lax', $bag); $this->assertSetCookieHeader('foo=bar; path=/path/bar; domain=foo.bar; httponly; samesite=lax', $bag); @@ -228,16 +228,16 @@ class ResponseHeaderBagTest extends TestCase { $bag = new ResponseHeaderBag(); $bag->set('set-cookie', 'foo=bar'); - $this->assertEquals(array(Cookie::create('foo', 'bar', 0, '/', null, false, false, true, null)), $bag->getCookies()); + $this->assertEquals([Cookie::create('foo', 'bar', 0, '/', null, false, false, true, null)], $bag->getCookies()); $bag->set('set-cookie', 'foo2=bar2', false); - $this->assertEquals(array( + $this->assertEquals([ Cookie::create('foo', 'bar', 0, '/', null, false, false, true, null), Cookie::create('foo2', 'bar2', 0, '/', null, false, false, true, null), - ), $bag->getCookies()); + ], $bag->getCookies()); $bag->remove('set-cookie'); - $this->assertEquals(array(), $bag->getCookies()); + $this->assertEquals([], $bag->getCookies()); } /** @@ -260,8 +260,8 @@ class ResponseHeaderBagTest extends TestCase (string) $headers; $allHeaders = $headers->allPreserveCase(); - $this->assertEquals(array('http://www.symfony.com'), $allHeaders['Location']); - $this->assertEquals(array('text/html'), $allHeaders['Content-type']); + $this->assertEquals(['http://www.symfony.com'], $allHeaders['Location']); + $this->assertEquals(['text/html'], $allHeaders['Content-type']); } public function testDateHeaderAddedOnCreation() @@ -277,7 +277,7 @@ class ResponseHeaderBagTest extends TestCase public function testDateHeaderCanBeSetOnCreation() { $someDate = 'Thu, 23 Mar 2017 09:15:12 GMT'; - $bag = new ResponseHeaderBag(array('Date' => $someDate)); + $bag = new ResponseHeaderBag(['Date' => $someDate]); $this->assertEquals($someDate, $bag->get('Date')); } @@ -285,7 +285,7 @@ class ResponseHeaderBagTest extends TestCase public function testDateHeaderWillBeRecreatedWhenRemoved() { $someDate = 'Thu, 23 Mar 2017 09:15:12 GMT'; - $bag = new ResponseHeaderBag(array('Date' => $someDate)); + $bag = new ResponseHeaderBag(['Date' => $someDate]); $bag->remove('Date'); // a (new) Date header is still present @@ -296,7 +296,7 @@ class ResponseHeaderBagTest extends TestCase public function testDateHeaderWillBeRecreatedWhenHeadersAreReplaced() { $bag = new ResponseHeaderBag(); - $bag->replace(array()); + $bag->replace([]); $this->assertTrue($bag->has('Date')); } diff --git a/src/Symfony/Component/HttpFoundation/Tests/Session/Attribute/AttributeBagTest.php b/src/Symfony/Component/HttpFoundation/Tests/Session/Attribute/AttributeBagTest.php index 8c41e47510..44c8174e30 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/Session/Attribute/AttributeBagTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/Session/Attribute/AttributeBagTest.php @@ -21,7 +21,7 @@ use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag; */ class AttributeBagTest extends TestCase { - private $array = array(); + private $array = []; /** * @var AttributeBag @@ -30,21 +30,21 @@ class AttributeBagTest extends TestCase protected function setUp() { - $this->array = array( + $this->array = [ 'hello' => 'world', 'always' => 'be happy', 'user.login' => 'drak', - 'csrf.token' => array( + 'csrf.token' => [ 'a' => '1234', 'b' => '4321', - ), - 'category' => array( - 'fishing' => array( + ], + 'category' => [ + 'fishing' => [ 'first' => 'cod', 'second' => 'sole', - ), - ), - ); + ], + ], + ]; $this->bag = new AttributeBag('_sf'); $this->bag->initialize($this->array); } @@ -52,7 +52,7 @@ class AttributeBagTest extends TestCase protected function tearDown() { $this->bag = null; - $this->array = array(); + $this->array = []; } public function testInitialize() @@ -60,7 +60,7 @@ class AttributeBagTest extends TestCase $bag = new AttributeBag(); $bag->initialize($this->array); $this->assertEquals($this->array, $bag->all()); - $array = array('should' => 'change'); + $array = ['should' => 'change']; $bag->initialize($array); $this->assertEquals($array, $bag->all()); } @@ -122,7 +122,7 @@ class AttributeBagTest extends TestCase public function testReplace() { - $array = array(); + $array = []; $array['name'] = 'jack'; $array['foo.bar'] = 'beep'; $this->bag->replace($array); @@ -150,22 +150,22 @@ class AttributeBagTest extends TestCase public function testClear() { $this->bag->clear(); - $this->assertEquals(array(), $this->bag->all()); + $this->assertEquals([], $this->bag->all()); } public function attributesProvider() { - return array( - array('hello', 'world', true), - array('always', 'be happy', true), - array('user.login', 'drak', true), - array('csrf.token', array('a' => '1234', 'b' => '4321'), true), - array('category', array('fishing' => array('first' => 'cod', 'second' => 'sole')), true), - array('user2.login', null, false), - array('never', null, false), - array('bye', null, false), - array('bye/for/now', null, false), - ); + return [ + ['hello', 'world', true], + ['always', 'be happy', true], + ['user.login', 'drak', true], + ['csrf.token', ['a' => '1234', 'b' => '4321'], true], + ['category', ['fishing' => ['first' => 'cod', 'second' => 'sole']], true], + ['user2.login', null, false], + ['never', null, false], + ['bye', null, false], + ['bye/for/now', null, false], + ]; } public function testGetIterator() diff --git a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/Fixtures/with_samesite.php b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/Fixtures/with_samesite.php index 2d32792a8f..fc2c418289 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/Fixtures/with_samesite.php +++ b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/Fixtures/with_samesite.php @@ -4,10 +4,10 @@ require __DIR__.'/common.inc'; use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage; -$storage = new NativeSessionStorage(array('cookie_samesite' => 'lax')); +$storage = new NativeSessionStorage(['cookie_samesite' => 'lax']); $storage->setSaveHandler(new TestSessionHandler()); $storage->start(); -$_SESSION = array('foo' => 'bar'); +$_SESSION = ['foo' => 'bar']; ob_start(function ($buffer) { return str_replace(session_id(), 'random_session_id', $buffer); }); diff --git a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/Fixtures/with_samesite_and_migration.php b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/Fixtures/with_samesite_and_migration.php index e0ff64b951..a28b6fedfc 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/Fixtures/with_samesite_and_migration.php +++ b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/Fixtures/with_samesite_and_migration.php @@ -4,11 +4,11 @@ require __DIR__.'/common.inc'; use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage; -$storage = new NativeSessionStorage(array('cookie_samesite' => 'lax')); +$storage = new NativeSessionStorage(['cookie_samesite' => 'lax']); $storage->setSaveHandler(new TestSessionHandler()); $storage->start(); -$_SESSION = array('foo' => 'bar'); +$_SESSION = ['foo' => 'bar']; $storage->regenerate(true); diff --git a/src/Symfony/Component/HttpKernel/CacheWarmer/CacheWarmerAggregate.php b/src/Symfony/Component/HttpKernel/CacheWarmer/CacheWarmerAggregate.php index 171b38596f..dd527708be 100644 --- a/src/Symfony/Component/HttpKernel/CacheWarmer/CacheWarmerAggregate.php +++ b/src/Symfony/Component/HttpKernel/CacheWarmer/CacheWarmerAggregate.php @@ -26,7 +26,7 @@ class CacheWarmerAggregate implements CacheWarmerInterface private $optionalsEnabled = false; private $onlyOptionalsEnabled = false; - public function __construct(iterable $warmers = array(), bool $debug = false, string $deprecationLogsFilepath = null) + public function __construct(iterable $warmers = [], bool $debug = false, string $deprecationLogsFilepath = null) { $this->warmers = $warmers; $this->debug = $debug; @@ -51,7 +51,7 @@ class CacheWarmerAggregate implements CacheWarmerInterface public function warmUp($cacheDir) { if ($this->debug) { - $collectedLogs = array(); + $collectedLogs = []; $previousHandler = \defined('PHPUNIT_COMPOSER_INSTALL'); $previousHandler = $previousHandler ?: set_error_handler(function ($type, $message, $file, $line) use (&$collectedLogs, &$previousHandler) { if (E_USER_DEPRECATED !== $type && E_DEPRECATED !== $type) { @@ -73,14 +73,14 @@ class CacheWarmerAggregate implements CacheWarmerInterface } } - $collectedLogs[$message] = array( + $collectedLogs[$message] = [ 'type' => $type, 'message' => $message, 'file' => $file, 'line' => $line, 'trace' => $backtrace, 'count' => 1, - ); + ]; }); } diff --git a/src/Symfony/Component/HttpKernel/DataCollector/DumpDataCollector.php b/src/Symfony/Component/HttpKernel/DataCollector/DumpDataCollector.php index 13694f5a59..1a3021dcb4 100644 --- a/src/Symfony/Component/HttpKernel/DataCollector/DumpDataCollector.php +++ b/src/Symfony/Component/HttpKernel/DataCollector/DumpDataCollector.php @@ -52,12 +52,12 @@ class DumpDataCollector extends DataCollector implements DataDumperInterface $this->dumper = $dumper; // All clones share these properties by reference: - $this->rootRefs = array( + $this->rootRefs = [ &$this->data, &$this->dataCount, &$this->isCollected, &$this->clonesCount, - ); + ]; $this->sourceContextProvider = $dumper instanceof Connection && isset($dumper->getContextProviders()['source']) ? $dumper->getContextProviders()['source'] : new SourceContextProvider($this->charset); } @@ -110,7 +110,7 @@ class DumpDataCollector extends DataCollector implements DataDumperInterface ) { if ($response->headers->has('Content-Type') && false !== strpos($response->headers->get('Content-Type'), 'html')) { $dumper = new HtmlDumper('php://output', $this->charset); - $dumper->setDisplayOptions(array('fileLinkFormat' => $this->fileLinkFormat)); + $dumper->setDisplayOptions(['fileLinkFormat' => $this->fileLinkFormat]); } else { $dumper = new CliDumper('php://output', $this->charset); } @@ -126,7 +126,7 @@ class DumpDataCollector extends DataCollector implements DataDumperInterface if ($this->stopwatch) { $this->stopwatch->reset(); } - $this->data = array(); + $this->data = []; $this->dataCount = 0; $this->isCollected = true; $this->clonesCount = 0; @@ -142,7 +142,7 @@ class DumpDataCollector extends DataCollector implements DataDumperInterface $this->data[] = $this->fileLinkFormat; $this->data[] = $this->charset; $ser = serialize($this->data); - $this->data = array(); + $this->data = []; $this->dataCount = 0; $this->isCollected = true; @@ -169,11 +169,11 @@ class DumpDataCollector extends DataCollector implements DataDumperInterface if ('html' === $format) { $dumper = new HtmlDumper($data, $this->charset); - $dumper->setDisplayOptions(array('fileLinkFormat' => $this->fileLinkFormat)); + $dumper->setDisplayOptions(['fileLinkFormat' => $this->fileLinkFormat]); } else { throw new \InvalidArgumentException(sprintf('Invalid dump format: %s', $format)); } - $dumps = array(); + $dumps = []; foreach ($this->data as $dump) { $dumper->dump($dump['data']->withMaxDepth($maxDepthLimit)->withMaxItemsPerDepth($maxItemsPerDepth)); @@ -207,12 +207,12 @@ class DumpDataCollector extends DataCollector implements DataDumperInterface if (isset($_SERVER['VAR_DUMPER_FORMAT'])) { $html = 'html' === $_SERVER['VAR_DUMPER_FORMAT']; } else { - $html = !\in_array(\PHP_SAPI, array('cli', 'phpdbg'), true) && stripos($h[$i], 'html'); + $html = !\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) && stripos($h[$i], 'html'); } if ($html) { $dumper = new HtmlDumper('php://output', $this->charset); - $dumper->setDisplayOptions(array('fileLinkFormat' => $this->fileLinkFormat)); + $dumper->setDisplayOptions(['fileLinkFormat' => $this->fileLinkFormat]); } else { $dumper = new CliDumper('php://output', $this->charset); } @@ -222,7 +222,7 @@ class DumpDataCollector extends DataCollector implements DataDumperInterface $this->doDump($dumper, $dump['data'], $dump['name'], $dump['file'], $dump['line']); } - $this->data = array(); + $this->data = []; $this->dataCount = 0; } } @@ -236,7 +236,7 @@ class DumpDataCollector extends DataCollector implements DataDumperInterface $s = $this->style('meta', '%s'); $f = strip_tags($this->style('', $file)); $name = strip_tags($this->style('', $name)); - if ($fmt && $link = \is_string($fmt) ? strtr($fmt, array('%f' => $file, '%l' => $line)) : $fmt->format($file, $line)) { + if ($fmt && $link = \is_string($fmt) ? strtr($fmt, ['%f' => $file, '%l' => $line]) : $fmt->format($file, $line)) { $name = sprintf(''.$s.'', strip_tags($this->style('', $link)), $f, $name); } else { $name = sprintf(''.$s.'', $f, $name); diff --git a/src/Symfony/Component/HttpKernel/DataCollector/RequestDataCollector.php b/src/Symfony/Component/HttpKernel/DataCollector/RequestDataCollector.php index ed75382618..2df5f94fd4 100644 --- a/src/Symfony/Component/HttpKernel/DataCollector/RequestDataCollector.php +++ b/src/Symfony/Component/HttpKernel/DataCollector/RequestDataCollector.php @@ -38,7 +38,7 @@ class RequestDataCollector extends DataCollector implements EventSubscriberInter public function collect(Request $request, Response $response, \Exception $exception = null) { // attributes are serialized and as they can be anything, they need to be converted to strings. - $attributes = array(); + $attributes = []; $route = ''; foreach ($request->attributes->all() as $key => $value) { if ('_route' === $key) { @@ -57,10 +57,10 @@ class RequestDataCollector extends DataCollector implements EventSubscriberInter $content = false; } - $sessionMetadata = array(); - $sessionAttributes = array(); + $sessionMetadata = []; + $sessionAttributes = []; $session = null; - $flashes = array(); + $flashes = []; if ($request->hasSession()) { $session = $request->getSession(); if ($session->isStarted()) { @@ -74,19 +74,19 @@ class RequestDataCollector extends DataCollector implements EventSubscriberInter $statusCode = $response->getStatusCode(); - $responseCookies = array(); + $responseCookies = []; foreach ($response->headers->getCookies() as $cookie) { $responseCookies[$cookie->getName()] = $cookie; } - $dotenvVars = array(); + $dotenvVars = []; foreach (explode(',', getenv('SYMFONY_DOTENV_VARS')) as $name) { if ('' !== $name && false !== $value = getenv($name)) { $dotenvVars[$name] = $value; } } - $this->data = array( + $this->data = [ 'method' => $request->getMethod(), 'format' => $request->getRequestFormat(), 'content' => $content, @@ -110,7 +110,7 @@ class RequestDataCollector extends DataCollector implements EventSubscriberInter 'controller' => 'n/a', 'locale' => $request->getLocale(), 'dotenv_vars' => $dotenvVars, - ); + ]; if (isset($this->data['request_headers']['php-auth-pw'])) { $this->data['request_headers']['php-auth-pw'] = '******'; @@ -147,14 +147,14 @@ class RequestDataCollector extends DataCollector implements EventSubscriberInter if ($response->isRedirect()) { $response->headers->setCookie(new Cookie( 'sf_redirect', - json_encode(array( + json_encode([ 'token' => $response->headers->get('x-debug-token'), 'route' => $request->attributes->get('_route', 'n/a'), 'method' => $request->getMethod(), 'controller' => $this->parseController($request->attributes->get('_controller')), 'status_code' => $statusCode, 'status_text' => Response::$statusTexts[(int) $statusCode], - )), + ]), 0, '/', null, $request->isSecure(), true, false, 'lax' )); } @@ -173,7 +173,7 @@ class RequestDataCollector extends DataCollector implements EventSubscriberInter public function reset() { - $this->data = array(); + $this->data = []; $this->controllers = new \SplObjectStorage(); } @@ -308,7 +308,7 @@ class RequestDataCollector extends DataCollector implements EventSubscriberInter */ public function getRouteParams() { - return isset($this->data['request_attributes']['_route_params']) ? $this->data['request_attributes']['_route_params']->getValue() : array(); + return isset($this->data['request_attributes']['_route_params']) ? $this->data['request_attributes']['_route_params']->getValue() : []; } /** @@ -356,10 +356,10 @@ class RequestDataCollector extends DataCollector implements EventSubscriberInter public static function getSubscribedEvents() { - return array( + return [ KernelEvents::CONTROLLER => 'onKernelController', KernelEvents::RESPONSE => 'onKernelResponse', - ); + ]; } /** @@ -387,21 +387,21 @@ class RequestDataCollector extends DataCollector implements EventSubscriberInter try { $r = new \ReflectionMethod($controller[0], $controller[1]); - return array( + return [ 'class' => \is_object($controller[0]) ? \get_class($controller[0]) : $controller[0], 'method' => $controller[1], 'file' => $r->getFileName(), 'line' => $r->getStartLine(), - ); + ]; } catch (\ReflectionException $e) { if (\is_callable($controller)) { // using __call or __callStatic - return array( + return [ 'class' => \is_object($controller[0]) ? \get_class($controller[0]) : $controller[0], 'method' => $controller[1], 'file' => 'n/a', 'line' => 'n/a', - ); + ]; } } } @@ -409,12 +409,12 @@ class RequestDataCollector extends DataCollector implements EventSubscriberInter if ($controller instanceof \Closure) { $r = new \ReflectionFunction($controller); - $controller = array( + $controller = [ 'class' => $r->getName(), 'method' => null, 'file' => $r->getFileName(), 'line' => $r->getStartLine(), - ); + ]; if (false !== strpos($r->name, '{closure}')) { return $controller; @@ -433,12 +433,12 @@ class RequestDataCollector extends DataCollector implements EventSubscriberInter if (\is_object($controller)) { $r = new \ReflectionClass($controller); - return array( + return [ 'class' => $r->getName(), 'method' => null, 'file' => $r->getFileName(), 'line' => $r->getStartLine(), - ); + ]; } return \is_string($controller) ? $controller : 'n/a'; diff --git a/src/Symfony/Component/HttpKernel/EventListener/AbstractTestSessionListener.php b/src/Symfony/Component/HttpKernel/EventListener/AbstractTestSessionListener.php index ff93ce6e9f..58b3580024 100644 --- a/src/Symfony/Component/HttpKernel/EventListener/AbstractTestSessionListener.php +++ b/src/Symfony/Component/HttpKernel/EventListener/AbstractTestSessionListener.php @@ -32,7 +32,7 @@ abstract class AbstractTestSessionListener implements EventSubscriberInterface private $sessionId; private $sessionOptions; - public function __construct(array $sessionOptions = array()) + public function __construct(array $sessionOptions = []) { $this->sessionOptions = $sessionOptions; } @@ -78,7 +78,7 @@ abstract class AbstractTestSessionListener implements EventSubscriberInterface } if ($session instanceof Session ? !$session->isEmpty() || (null !== $this->sessionId && $session->getId() !== $this->sessionId) : $wasStarted) { - $params = session_get_cookie_params() + array('samesite' => null); + $params = session_get_cookie_params() + ['samesite' => null]; foreach ($this->sessionOptions as $k => $v) { if (0 === strpos($k, 'cookie_')) { $params[substr($k, 7)] = $v; diff --git a/src/Symfony/Component/HttpKernel/EventListener/ExceptionListener.php b/src/Symfony/Component/HttpKernel/EventListener/ExceptionListener.php index 02b1d4ddc3..dd00797f5f 100644 --- a/src/Symfony/Component/HttpKernel/EventListener/ExceptionListener.php +++ b/src/Symfony/Component/HttpKernel/EventListener/ExceptionListener.php @@ -112,12 +112,12 @@ class ExceptionListener implements EventSubscriberInterface public static function getSubscribedEvents() { - return array( - KernelEvents::EXCEPTION => array( - array('logKernelException', 0), - array('onKernelException', -128), - ), - ); + return [ + KernelEvents::EXCEPTION => [ + ['logKernelException', 0], + ['onKernelException', -128], + ], + ]; } /** @@ -130,9 +130,9 @@ class ExceptionListener implements EventSubscriberInterface { if (null !== $this->logger) { if (!$exception instanceof HttpExceptionInterface || $exception->getStatusCode() >= 500) { - $this->logger->critical($message, array('exception' => $exception)); + $this->logger->critical($message, ['exception' => $exception]); } else { - $this->logger->error($message, array('exception' => $exception)); + $this->logger->error($message, ['exception' => $exception]); } } } @@ -147,7 +147,7 @@ class ExceptionListener implements EventSubscriberInterface */ protected function duplicateRequest(\Exception $exception, Request $request) { - $attributes = array( + $attributes = [ 'exception' => $exception = FlattenException::create($exception), '_controller' => $this->controller ?: function () use ($exception) { $handler = new ExceptionHandler($this->debug, $this->charset, $this->fileLinkFormat); @@ -155,7 +155,7 @@ class ExceptionListener implements EventSubscriberInterface return new Response($handler->getHtml($exception), $exception->getStatusCode(), $exception->getHeaders()); }, 'logger' => $this->logger instanceof DebugLoggerInterface ? $this->logger : null, - ); + ]; $request = $request->duplicate(null, null, $attributes); $request->setMethod('GET'); diff --git a/src/Symfony/Component/HttpKernel/EventListener/SessionListener.php b/src/Symfony/Component/HttpKernel/EventListener/SessionListener.php index 75624b6c5c..aaf3be507f 100644 --- a/src/Symfony/Component/HttpKernel/EventListener/SessionListener.php +++ b/src/Symfony/Component/HttpKernel/EventListener/SessionListener.php @@ -42,7 +42,7 @@ class SessionListener extends AbstractSessionListener && ($storage = $this->container->get('session_storage')) instanceof NativeSessionStorage && $this->container->get('request_stack')->getMasterRequest()->isSecure() ) { - $storage->setOptions(array('cookie_secure' => true)); + $storage->setOptions(['cookie_secure' => true]); } return $this->container->get('session'); diff --git a/src/Symfony/Component/HttpKernel/EventListener/TestSessionListener.php b/src/Symfony/Component/HttpKernel/EventListener/TestSessionListener.php index 23589a2bb3..46323ae2a8 100644 --- a/src/Symfony/Component/HttpKernel/EventListener/TestSessionListener.php +++ b/src/Symfony/Component/HttpKernel/EventListener/TestSessionListener.php @@ -24,7 +24,7 @@ class TestSessionListener extends AbstractTestSessionListener { private $container; - public function __construct(ContainerInterface $container, array $sessionOptions = array()) + public function __construct(ContainerInterface $container, array $sessionOptions = []) { $this->container = $container; parent::__construct($sessionOptions); diff --git a/src/Symfony/Component/HttpKernel/Exception/ControllerDoesNotReturnResponseException.php b/src/Symfony/Component/HttpKernel/Exception/ControllerDoesNotReturnResponseException.php index 39149aa5b7..517313db60 100644 --- a/src/Symfony/Component/HttpKernel/Exception/ControllerDoesNotReturnResponseException.php +++ b/src/Symfony/Component/HttpKernel/Exception/ControllerDoesNotReturnResponseException.php @@ -28,12 +28,12 @@ class ControllerDoesNotReturnResponseException extends \LogicException $this->line = $controllerDefinition['line']; $r = new \ReflectionProperty(\Exception::class, 'trace'); $r->setAccessible(true); - $r->setValue($this, array_merge(array( - array( + $r->setValue($this, array_merge([ + [ 'line' => $line, 'file' => $file, - ), - ), $this->getTrace())); + ], + ], $this->getTrace())); } private function parseControllerDefinition(callable $controller): ?array @@ -46,10 +46,10 @@ class ControllerDoesNotReturnResponseException extends \LogicException try { $r = new \ReflectionMethod($controller[0], $controller[1]); - return array( + return [ 'file' => $r->getFileName(), 'line' => $r->getEndLine(), - ); + ]; } catch (\ReflectionException $e) { return null; } @@ -58,19 +58,19 @@ class ControllerDoesNotReturnResponseException extends \LogicException if ($controller instanceof \Closure) { $r = new \ReflectionFunction($controller); - return array( + return [ 'file' => $r->getFileName(), 'line' => $r->getEndLine(), - ); + ]; } if (\is_object($controller)) { $r = new \ReflectionClass($controller); - return array( + return [ 'file' => $r->getFileName(), 'line' => $r->getEndLine(), - ); + ]; } return null; diff --git a/src/Symfony/Component/HttpKernel/Kernel.php b/src/Symfony/Component/HttpKernel/Kernel.php index fd1d0c0e89..f2528aab26 100644 --- a/src/Symfony/Component/HttpKernel/Kernel.php +++ b/src/Symfony/Component/HttpKernel/Kernel.php @@ -52,7 +52,7 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl /** * @var BundleInterface[] */ - protected $bundles = array(); + protected $bundles = []; protected $container; /** @@ -258,7 +258,7 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl $isResource = 0 === strpos($path, 'Resources') && null !== $dir; $overridePath = substr($path, 9); $bundle = $this->getBundle($bundleName); - $files = array(); + $files = []; if ($isResource && file_exists($file = $dir.'/'.$bundle->getName().$overridePath)) { $files[] = $file; @@ -409,7 +409,7 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl */ public function getAnnotatedClassesToCompile(): array { - return array(); + return []; } /** @@ -420,7 +420,7 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl protected function initializeBundles() { // init bundles - $this->bundles = array(); + $this->bundles = []; foreach ($this->registerBundles() as $bundle) { $name = $bundle->getName(); if (isset($this->bundles[$name])) { @@ -498,7 +498,7 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl } if ($this->debug) { - $collectedLogs = array(); + $collectedLogs = []; $previousHandler = \defined('PHPUNIT_COMPOSER_INSTALL'); $previousHandler = $previousHandler ?: set_error_handler(function ($type, $message, $file, $line) use (&$collectedLogs, &$previousHandler) { if (E_USER_DEPRECATED !== $type && E_DEPRECATED !== $type) { @@ -522,19 +522,19 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl // Remove frames added by DebugClassLoader. for ($i = \count($backtrace) - 2; 0 < $i; --$i) { if (DebugClassLoader::class === ($backtrace[$i]['class'] ?? null)) { - $backtrace = array($backtrace[$i + 1]); + $backtrace = [$backtrace[$i + 1]]; break; } } - $collectedLogs[$message] = array( + $collectedLogs[$message] = [ 'type' => $type, 'message' => $message, 'file' => $file, 'line' => $line, - 'trace' => array($backtrace[0]), + 'trace' => [$backtrace[0]], 'count' => 1, - ); + ]; }); } @@ -571,7 +571,7 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl // Because concurrent requests might still be using them, // old container files are not removed immediately, // but on a next dump of the container. - static $legacyContainers = array(); + static $legacyContainers = []; $oldContainerDir = \dirname($oldContainer->getFileName()); $legacyContainers[$oldContainerDir.'.legacy'] = true; foreach (glob(\dirname($oldContainerDir).\DIRECTORY_SEPARATOR.'*.legacy') as $legacyContainer) { @@ -595,18 +595,18 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl */ protected function getKernelParameters() { - $bundles = array(); - $bundlesMetadata = array(); + $bundles = []; + $bundlesMetadata = []; foreach ($this->bundles as $name => $bundle) { $bundles[$name] = \get_class($bundle); - $bundlesMetadata[$name] = array( + $bundlesMetadata[$name] = [ 'path' => $bundle->getPath(), 'namespace' => $bundle->getNamespace(), - ); + ]; } - return array( + return [ /* * @deprecated since Symfony 4.2, use kernel.project_dir instead */ @@ -624,7 +624,7 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl 'kernel.bundles_metadata' => $bundlesMetadata, 'kernel.charset' => $this->getCharset(), 'kernel.container_class' => $this->getContainerClass(), - ); + ]; } /** @@ -636,7 +636,7 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl */ protected function buildContainer() { - foreach (array('cache' => $this->warmupDir ?: $this->getCacheDir(), 'logs' => $this->getLogDir()) as $name => $dir) { + foreach (['cache' => $this->warmupDir ?: $this->getCacheDir(), 'logs' => $this->getLogDir()] as $name => $dir) { if (!is_dir($dir)) { if (false === @mkdir($dir, 0777, true) && !is_dir($dir)) { throw new \RuntimeException(sprintf("Unable to create the %s directory (%s)\n", $name, $dir)); @@ -664,7 +664,7 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl */ protected function prepareContainer(ContainerBuilder $container) { - $extensions = array(); + $extensions = []; foreach ($this->bundles as $bundle) { if ($extension = $bundle->getContainerExtension()) { $container->registerExtension($extension); @@ -726,14 +726,14 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl $dumper->setProxyDumper(new ProxyDumper()); } - $content = $dumper->dump(array( + $content = $dumper->dump([ 'class' => $class, 'base_class' => $baseClass, 'file' => $cache->getPath(), 'as_files' => true, 'debug' => $this->debug, 'build_time' => $container->hasParameter('kernel.container_build_time') ? $container->getParameter('kernel.container_build_time') : time(), - )); + ]); $rootCode = array_pop($content); $dir = \dirname($cache->getPath()).'/'; @@ -759,7 +759,7 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl protected function getContainerLoader(ContainerInterface $container) { $locator = new FileLocator($this); - $resolver = new LoaderResolver(array( + $resolver = new LoaderResolver([ new XmlFileLoader($container, $locator), new YamlFileLoader($container, $locator), new IniFileLoader($container, $locator), @@ -767,7 +767,7 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl new GlobFileLoader($container, $locator), new DirectoryLoader($container, $locator), new ClosureLoader($container), - )); + ]); return new DelegatingLoader($resolver); } @@ -811,8 +811,8 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl } // replace multiple new lines with a single newline - $rawChunk .= preg_replace(array('/\n{2,}/S'), "\n", $token[1]); - } elseif (\in_array($token[0], array(T_COMMENT, T_DOC_COMMENT))) { + $rawChunk .= preg_replace(['/\n{2,}/S'], "\n", $token[1]); + } elseif (\in_array($token[0], [T_COMMENT, T_DOC_COMMENT])) { $ignoreSpace = true; } else { $rawChunk .= $token[1]; @@ -835,12 +835,12 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl public function serialize() { - return serialize(array($this->environment, $this->debug)); + return serialize([$this->environment, $this->debug]); } public function unserialize($data) { - list($environment, $debug) = unserialize($data, array('allowed_classes' => false)); + list($environment, $debug) = unserialize($data, ['allowed_classes' => false]); $this->__construct($environment, $debug); } diff --git a/src/Symfony/Component/HttpKernel/Tests/DependencyInjection/RegisterControllerArgumentLocatorsPassTest.php b/src/Symfony/Component/HttpKernel/Tests/DependencyInjection/RegisterControllerArgumentLocatorsPassTest.php index d03ea53a37..cf685b2ae2 100644 --- a/src/Symfony/Component/HttpKernel/Tests/DependencyInjection/RegisterControllerArgumentLocatorsPassTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/DependencyInjection/RegisterControllerArgumentLocatorsPassTest.php @@ -32,7 +32,7 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase public function testInvalidClass() { $container = new ContainerBuilder(); - $container->register('argument_resolver.service')->addArgument(array()); + $container->register('argument_resolver.service')->addArgument([]); $container->register('foo', NotFound::class) ->addTag('controller.service_arguments') @@ -49,10 +49,10 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase public function testNoAction() { $container = new ContainerBuilder(); - $container->register('argument_resolver.service')->addArgument(array()); + $container->register('argument_resolver.service')->addArgument([]); $container->register('foo', RegisterTestController::class) - ->addTag('controller.service_arguments', array('argument' => 'bar')) + ->addTag('controller.service_arguments', ['argument' => 'bar']) ; $pass = new RegisterControllerArgumentLocatorsPass(); @@ -66,10 +66,10 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase public function testNoArgument() { $container = new ContainerBuilder(); - $container->register('argument_resolver.service')->addArgument(array()); + $container->register('argument_resolver.service')->addArgument([]); $container->register('foo', RegisterTestController::class) - ->addTag('controller.service_arguments', array('action' => 'fooAction')) + ->addTag('controller.service_arguments', ['action' => 'fooAction']) ; $pass = new RegisterControllerArgumentLocatorsPass(); @@ -83,10 +83,10 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase public function testNoService() { $container = new ContainerBuilder(); - $container->register('argument_resolver.service')->addArgument(array()); + $container->register('argument_resolver.service')->addArgument([]); $container->register('foo', RegisterTestController::class) - ->addTag('controller.service_arguments', array('action' => 'fooAction', 'argument' => 'bar')) + ->addTag('controller.service_arguments', ['action' => 'fooAction', 'argument' => 'bar']) ; $pass = new RegisterControllerArgumentLocatorsPass(); @@ -100,10 +100,10 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase public function testInvalidMethod() { $container = new ContainerBuilder(); - $container->register('argument_resolver.service')->addArgument(array()); + $container->register('argument_resolver.service')->addArgument([]); $container->register('foo', RegisterTestController::class) - ->addTag('controller.service_arguments', array('action' => 'barAction', 'argument' => 'bar', 'id' => 'bar_service')) + ->addTag('controller.service_arguments', ['action' => 'barAction', 'argument' => 'bar', 'id' => 'bar_service']) ; $pass = new RegisterControllerArgumentLocatorsPass(); @@ -117,10 +117,10 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase public function testInvalidArgument() { $container = new ContainerBuilder(); - $container->register('argument_resolver.service')->addArgument(array()); + $container->register('argument_resolver.service')->addArgument([]); $container->register('foo', RegisterTestController::class) - ->addTag('controller.service_arguments', array('action' => 'fooAction', 'argument' => 'baz', 'id' => 'bar')) + ->addTag('controller.service_arguments', ['action' => 'fooAction', 'argument' => 'baz', 'id' => 'bar']) ; $pass = new RegisterControllerArgumentLocatorsPass(); @@ -130,7 +130,7 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase public function testAllActions() { $container = new ContainerBuilder(); - $resolver = $container->register('argument_resolver.service')->addArgument(array()); + $resolver = $container->register('argument_resolver.service')->addArgument([]); $container->register('foo', RegisterTestController::class) ->addTag('controller.service_arguments') @@ -141,7 +141,7 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase $locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0); - $this->assertEquals(array('foo::fooAction'), array_keys($locator)); + $this->assertEquals(['foo::fooAction'], array_keys($locator)); $this->assertInstanceof(ServiceClosureArgument::class, $locator['foo::fooAction']); $locator = $container->getDefinition((string) $locator['foo::fooAction']->getValues()[0]); @@ -149,18 +149,18 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase $this->assertSame(ServiceLocator::class, $locator->getClass()); $this->assertFalse($locator->isPublic()); - $expected = array('bar' => new ServiceClosureArgument(new TypedReference(ControllerDummy::class, ControllerDummy::class, ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE, 'bar'))); + $expected = ['bar' => new ServiceClosureArgument(new TypedReference(ControllerDummy::class, ControllerDummy::class, ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE, 'bar'))]; $this->assertEquals($expected, $locator->getArgument(0)); } public function testExplicitArgument() { $container = new ContainerBuilder(); - $resolver = $container->register('argument_resolver.service')->addArgument(array()); + $resolver = $container->register('argument_resolver.service')->addArgument([]); $container->register('foo', RegisterTestController::class) - ->addTag('controller.service_arguments', array('action' => 'fooAction', 'argument' => 'bar', 'id' => 'bar')) - ->addTag('controller.service_arguments', array('action' => 'fooAction', 'argument' => 'bar', 'id' => 'baz')) // should be ignored, the first wins + ->addTag('controller.service_arguments', ['action' => 'fooAction', 'argument' => 'bar', 'id' => 'bar']) + ->addTag('controller.service_arguments', ['action' => 'fooAction', 'argument' => 'bar', 'id' => 'baz']) // should be ignored, the first wins ; $pass = new RegisterControllerArgumentLocatorsPass(); @@ -169,17 +169,17 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase $locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0); $locator = $container->getDefinition((string) $locator['foo::fooAction']->getValues()[0]); - $expected = array('bar' => new ServiceClosureArgument(new TypedReference('bar', ControllerDummy::class, ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE))); + $expected = ['bar' => new ServiceClosureArgument(new TypedReference('bar', ControllerDummy::class, ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE))]; $this->assertEquals($expected, $locator->getArgument(0)); } public function testOptionalArgument() { $container = new ContainerBuilder(); - $resolver = $container->register('argument_resolver.service')->addArgument(array()); + $resolver = $container->register('argument_resolver.service')->addArgument([]); $container->register('foo', RegisterTestController::class) - ->addTag('controller.service_arguments', array('action' => 'fooAction', 'argument' => 'bar', 'id' => '?bar')) + ->addTag('controller.service_arguments', ['action' => 'fooAction', 'argument' => 'bar', 'id' => '?bar']) ; $pass = new RegisterControllerArgumentLocatorsPass(); @@ -188,14 +188,14 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase $locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0); $locator = $container->getDefinition((string) $locator['foo::fooAction']->getValues()[0]); - $expected = array('bar' => new ServiceClosureArgument(new TypedReference('bar', ControllerDummy::class, ContainerInterface::IGNORE_ON_INVALID_REFERENCE))); + $expected = ['bar' => new ServiceClosureArgument(new TypedReference('bar', ControllerDummy::class, ContainerInterface::IGNORE_ON_INVALID_REFERENCE))]; $this->assertEquals($expected, $locator->getArgument(0)); } public function testSkipSetContainer() { $container = new ContainerBuilder(); - $resolver = $container->register('argument_resolver.service')->addArgument(array()); + $resolver = $container->register('argument_resolver.service')->addArgument([]); $container->register('foo', ContainerAwareRegisterTestController::class) ->addTag('controller.service_arguments'); @@ -204,7 +204,7 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase $pass->process($container); $locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0); - $this->assertSame(array('foo::fooAction'), array_keys($locator)); + $this->assertSame(['foo::fooAction'], array_keys($locator)); } /** @@ -214,7 +214,7 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase public function testExceptionOnNonExistentTypeHint() { $container = new ContainerBuilder(); - $container->register('argument_resolver.service')->addArgument(array()); + $container->register('argument_resolver.service')->addArgument([]); $container->register('foo', NonExistentClassController::class) ->addTag('controller.service_arguments'); @@ -230,7 +230,7 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase public function testExceptionOnNonExistentTypeHintDifferentNamespace() { $container = new ContainerBuilder(); - $container->register('argument_resolver.service')->addArgument(array()); + $container->register('argument_resolver.service')->addArgument([]); $container->register('foo', NonExistentClassDifferentNamespaceController::class) ->addTag('controller.service_arguments'); @@ -242,7 +242,7 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase public function testNoExceptionOnNonExistentTypeHintOptionalArg() { $container = new ContainerBuilder(); - $resolver = $container->register('argument_resolver.service')->addArgument(array()); + $resolver = $container->register('argument_resolver.service')->addArgument([]); $container->register('foo', NonExistentClassOptionalController::class) ->addTag('controller.service_arguments'); @@ -251,13 +251,13 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase $pass->process($container); $locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0); - $this->assertSame(array('foo::barAction', 'foo::fooAction'), array_keys($locator)); + $this->assertSame(['foo::barAction', 'foo::fooAction'], array_keys($locator)); } public function testArgumentWithNoTypeHintIsOk() { $container = new ContainerBuilder(); - $resolver = $container->register('argument_resolver.service')->addArgument(array()); + $resolver = $container->register('argument_resolver.service')->addArgument([]); $container->register('foo', ArgumentWithoutTypeController::class) ->addTag('controller.service_arguments'); @@ -272,7 +272,7 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase public function testControllersAreMadePublic() { $container = new ContainerBuilder(); - $resolver = $container->register('argument_resolver.service')->addArgument(array()); + $resolver = $container->register('argument_resolver.service')->addArgument([]); $container->register('foo', ArgumentWithoutTypeController::class) ->setPublic(false) @@ -290,10 +290,10 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase public function testBindings($bindingName) { $container = new ContainerBuilder(); - $resolver = $container->register('argument_resolver.service')->addArgument(array()); + $resolver = $container->register('argument_resolver.service')->addArgument([]); $container->register('foo', RegisterTestController::class) - ->setBindings(array($bindingName => new Reference('foo'))) + ->setBindings([$bindingName => new Reference('foo')]) ->addTag('controller.service_arguments'); $pass = new RegisterControllerArgumentLocatorsPass(); @@ -303,17 +303,17 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase $locator = $container->getDefinition((string) $locator['foo::fooAction']->getValues()[0]); - $expected = array('bar' => new ServiceClosureArgument(new Reference('foo'))); + $expected = ['bar' => new ServiceClosureArgument(new Reference('foo'))]; $this->assertEquals($expected, $locator->getArgument(0)); } public function provideBindings() { - return array( - array(ControllerDummy::class.'$bar'), - array(ControllerDummy::class), - array('$bar'), - ); + return [ + [ControllerDummy::class.'$bar'], + [ControllerDummy::class], + ['$bar'], + ]; } /** @@ -322,10 +322,10 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase public function testBindScalarValueToControllerArgument($bindingKey) { $container = new ContainerBuilder(); - $resolver = $container->register('argument_resolver.service')->addArgument(array()); + $resolver = $container->register('argument_resolver.service')->addArgument([]); $container->register('foo', ArgumentWithoutTypeController::class) - ->setBindings(array($bindingKey => '%foo%')) + ->setBindings([$bindingKey => '%foo%']) ->addTag('controller.service_arguments'); $container->setParameter('foo', 'foo_val'); @@ -350,19 +350,19 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase public function provideBindScalarValueToControllerArgument() { - yield array('$someArg'); - yield array('string $someArg'); + yield ['$someArg']; + yield ['string $someArg']; } public function testBindingsOnChildDefinitions() { $container = new ContainerBuilder(); - $resolver = $container->register('argument_resolver.service')->addArgument(array()); + $resolver = $container->register('argument_resolver.service')->addArgument([]); $container->register('parent', ArgumentWithoutTypeController::class); $container->setDefinition('child', (new ChildDefinition('parent')) - ->setBindings(array('$someArg' => new Reference('parent'))) + ->setBindings(['$someArg' => new Reference('parent')]) ->addTag('controller.service_arguments') ); diff --git a/src/Symfony/Component/HttpKernel/Tests/Fragment/FragmentHandlerTest.php b/src/Symfony/Component/HttpKernel/Tests/Fragment/FragmentHandlerTest.php index 0dfaa79682..bc7236f0a8 100644 --- a/src/Symfony/Component/HttpKernel/Tests/Fragment/FragmentHandlerTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/Fragment/FragmentHandlerTest.php @@ -68,12 +68,12 @@ class FragmentHandlerTest extends TestCase public function testRender() { - $handler = $this->getHandler($this->returnValue(new Response('foo')), array('/', Request::create('/'), array('foo' => 'foo', 'ignore_errors' => true))); + $handler = $this->getHandler($this->returnValue(new Response('foo')), ['/', Request::create('/'), ['foo' => 'foo', 'ignore_errors' => true]]); - $this->assertEquals('foo', $handler->render('/', 'foo', array('foo' => 'foo'))); + $this->assertEquals('foo', $handler->render('/', 'foo', ['foo' => 'foo'])); } - protected function getHandler($returnValue, $arguments = array()) + protected function getHandler($returnValue, $arguments = []) { $renderer = $this->getMockBuilder('Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface')->getMock(); $renderer diff --git a/src/Symfony/Component/HttpKernel/Tests/HttpCache/EsiTest.php b/src/Symfony/Component/HttpKernel/Tests/HttpCache/EsiTest.php index 846caee4cc..2049a1771a 100644 --- a/src/Symfony/Component/HttpKernel/Tests/HttpCache/EsiTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/HttpCache/EsiTest.php @@ -220,13 +220,13 @@ class EsiTest extends TestCase $response1 = new Response('foo'); $response1->setStatusCode(404); $response2 = new Response('bar'); - $cache = $this->getCache(Request::create('/'), array($response1, $response2)); + $cache = $this->getCache(Request::create('/'), [$response1, $response2]); $this->assertEquals('bar', $esi->handle($cache, '/', '/alt', false)); } protected function getCache($request, $response) { - $cache = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpCache\HttpCache')->setMethods(array('getRequest', 'handle'))->disableOriginalConstructor()->getMock(); + $cache = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpCache\HttpCache')->setMethods(['getRequest', 'handle'])->disableOriginalConstructor()->getMock(); $cache->expects($this->any()) ->method('getRequest') ->will($this->returnValue($request)) diff --git a/src/Symfony/Component/HttpKernel/Tests/HttpCache/SsiTest.php b/src/Symfony/Component/HttpKernel/Tests/HttpCache/SsiTest.php index 1f1fbf8499..2b9d352c7c 100644 --- a/src/Symfony/Component/HttpKernel/Tests/HttpCache/SsiTest.php +++ b/src/Symfony/Component/HttpKernel/Tests/HttpCache/SsiTest.php @@ -187,13 +187,13 @@ class SsiTest extends TestCase $response1 = new Response('foo'); $response1->setStatusCode(404); $response2 = new Response('bar'); - $cache = $this->getCache(Request::create('/'), array($response1, $response2)); + $cache = $this->getCache(Request::create('/'), [$response1, $response2]); $this->assertEquals('bar', $ssi->handle($cache, '/', '/alt', false)); } protected function getCache($request, $response) { - $cache = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpCache\HttpCache')->setMethods(array('getRequest', 'handle'))->disableOriginalConstructor()->getMock(); + $cache = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpCache\HttpCache')->setMethods(['getRequest', 'handle'])->disableOriginalConstructor()->getMock(); $cache->expects($this->any()) ->method('getRequest') ->will($this->returnValue($request)) diff --git a/src/Symfony/Component/Intl/Data/Generator/LanguageDataGenerator.php b/src/Symfony/Component/Intl/Data/Generator/LanguageDataGenerator.php index eb26031ad0..258670f5ea 100644 --- a/src/Symfony/Component/Intl/Data/Generator/LanguageDataGenerator.php +++ b/src/Symfony/Component/Intl/Data/Generator/LanguageDataGenerator.php @@ -29,7 +29,7 @@ class LanguageDataGenerator extends AbstractDataGenerator /** * Source: http://www-01.sil.org/iso639-3/codes.asp. */ - private static $preferredAlpha2ToAlpha3Mapping = array( + private static $preferredAlpha2ToAlpha3Mapping = [ 'ak' => 'aka', 'ar' => 'ara', 'ay' => 'aym', @@ -81,20 +81,20 @@ class LanguageDataGenerator extends AbstractDataGenerator 'yi' => 'yid', 'za' => 'zha', 'zh' => 'zho', - ); - private static $blacklist = array( + ]; + private static $blacklist = [ 'mul' => true, // Multiple languages 'mis' => true, // Uncoded language 'und' => true, // Unknown language 'zxx' => true, // No linguistic content - ); + ]; /** * Collects all available language codes. * * @var string[] */ - private $languageCodes = array(); + private $languageCodes = []; /** * {@inheritdoc} @@ -118,7 +118,7 @@ class LanguageDataGenerator extends AbstractDataGenerator */ protected function preGenerate() { - $this->languageCodes = array(); + $this->languageCodes = []; } /** @@ -130,10 +130,10 @@ class LanguageDataGenerator extends AbstractDataGenerator // isset() on \ResourceBundle returns true even if the value is null if (isset($localeBundle['Languages']) && null !== $localeBundle['Languages']) { - $data = array( + $data = [ 'Version' => $localeBundle['Version'], 'Names' => self::generateLanguageNames($localeBundle), - ); + ]; $this->languageCodes = array_merge($this->languageCodes, array_keys($data['Names'])); @@ -160,12 +160,12 @@ class LanguageDataGenerator extends AbstractDataGenerator sort($this->languageCodes); - return array( + return [ 'Version' => $rootBundle['Version'], 'Languages' => $this->languageCodes, 'Aliases' => array_column(iterator_to_array($metadataBundle['alias']['language']), 'replacement'), 'Alpha2ToAlpha3' => $this->generateAlpha2ToAlpha3Mapping($metadataBundle), - ); + ]; } private static function generateLanguageNames(ArrayAccessibleResourceBundle $localeBundle): array @@ -176,7 +176,7 @@ class LanguageDataGenerator extends AbstractDataGenerator private function generateAlpha2ToAlpha3Mapping(ArrayAccessibleResourceBundle $metadataBundle) { $aliases = iterator_to_array($metadataBundle['alias']['language']); - $alpha2ToAlpha3 = array(); + $alpha2ToAlpha3 = []; foreach ($aliases as $alias => $language) { $language = $language['replacement']; diff --git a/src/Symfony/Component/Intl/Data/Util/LocaleScanner.php b/src/Symfony/Component/Intl/Data/Util/LocaleScanner.php index 1ea4ba6f1a..2d56ff9d0c 100644 --- a/src/Symfony/Component/Intl/Data/Util/LocaleScanner.php +++ b/src/Symfony/Component/Intl/Data/Util/LocaleScanner.php @@ -89,7 +89,7 @@ class LocaleScanner public function scanParents(string $sourceDir): array { $locales = $this->scanLocales($sourceDir); - $fallbacks = array(); + $fallbacks = []; foreach ($locales as $locale) { $content = \file_get_contents($sourceDir.'/'.$locale.'.txt'); diff --git a/src/Symfony/Component/Intl/Tests/Data/Util/LocaleScannerTest.php b/src/Symfony/Component/Intl/Tests/Data/Util/LocaleScannerTest.php index abbe7f83f8..03a616a6ab 100644 --- a/src/Symfony/Component/Intl/Tests/Data/Util/LocaleScannerTest.php +++ b/src/Symfony/Component/Intl/Tests/Data/Util/LocaleScannerTest.php @@ -69,21 +69,21 @@ class LocaleScannerTest extends TestCase public function testScanLocales() { - $sortedLocales = array('de', 'de_alias', 'de_child', 'en', 'en_alias', 'en_child', 'fr', 'fr_alias', 'fr_child'); + $sortedLocales = ['de', 'de_alias', 'de_child', 'en', 'en_alias', 'en_child', 'fr', 'fr_alias', 'fr_child']; $this->assertSame($sortedLocales, $this->scanner->scanLocales($this->directory)); } public function testScanAliases() { - $sortedAliases = array('de_alias' => 'de', 'en_alias' => 'en', 'fr_alias' => 'fr'); + $sortedAliases = ['de_alias' => 'de', 'en_alias' => 'en', 'fr_alias' => 'fr']; $this->assertSame($sortedAliases, $this->scanner->scanAliases($this->directory)); } public function testScanParents() { - $sortedParents = array('de_child' => 'de', 'en_child' => 'en', 'fr_child' => 'fr'); + $sortedParents = ['de_child' => 'de', 'en_child' => 'en', 'fr_child' => 'fr']; $this->assertSame($sortedParents, $this->scanner->scanParents($this->directory)); } diff --git a/src/Symfony/Component/Intl/Tests/Locale/LocaleTest.php b/src/Symfony/Component/Intl/Tests/Locale/LocaleTest.php index 1d2e47076f..e7bdb7102a 100644 --- a/src/Symfony/Component/Intl/Tests/Locale/LocaleTest.php +++ b/src/Symfony/Component/Intl/Tests/Locale/LocaleTest.php @@ -39,11 +39,11 @@ class LocaleTest extends AbstractLocaleTest */ public function testComposeLocale() { - $subtags = array( + $subtags = [ 'language' => 'pt', 'script' => 'Latn', 'region' => 'BR', - ); + ]; $this->call('composeLocale', $subtags); } @@ -140,10 +140,10 @@ class LocaleTest extends AbstractLocaleTest */ public function testLookup() { - $langtag = array( + $langtag = [ 'pt-Latn-BR', 'pt-BR', - ); + ]; $this->call('lookup', $langtag, 'pt-BR-x-priv1'); } diff --git a/src/Symfony/Component/Ldap/Adapter/ExtLdap/Connection.php b/src/Symfony/Component/Ldap/Adapter/ExtLdap/Connection.php index 73b127ce5e..8ba19ee731 100644 --- a/src/Symfony/Component/Ldap/Adapter/ExtLdap/Connection.php +++ b/src/Symfony/Component/Ldap/Adapter/ExtLdap/Connection.php @@ -100,10 +100,10 @@ class Connection extends AbstractConnection $options->setDefault('debug_level', 7); } - $options->setDefaults(array( + $options->setDefaults([ 'protocol_version' => $parent['version'], 'referrals' => $parent['referrals'], - )); + ]); }); } diff --git a/src/Symfony/Component/Ldap/Adapter/ExtLdap/EntryManager.php b/src/Symfony/Component/Ldap/Adapter/ExtLdap/EntryManager.php index f1663a2010..f80601b3ba 100644 --- a/src/Symfony/Component/Ldap/Adapter/ExtLdap/EntryManager.php +++ b/src/Symfony/Component/Ldap/Adapter/ExtLdap/EntryManager.php @@ -130,7 +130,7 @@ class EntryManager implements EntryManagerInterface */ public function applyOperations(string $dn, iterable $operations): void { - $operationsMapped = array(); + $operationsMapped = []; foreach ($operations as $modification) { $operationsMapped[] = $modification->toArray(); } diff --git a/src/Symfony/Component/Ldap/Adapter/ExtLdap/UpdateOperation.php b/src/Symfony/Component/Ldap/Adapter/ExtLdap/UpdateOperation.php index 7bf3d32f37..c09b1b8e10 100644 --- a/src/Symfony/Component/Ldap/Adapter/ExtLdap/UpdateOperation.php +++ b/src/Symfony/Component/Ldap/Adapter/ExtLdap/UpdateOperation.php @@ -19,12 +19,12 @@ class UpdateOperation private $values; private $attribute; - private $validOperationTypes = array( + private $validOperationTypes = [ LDAP_MODIFY_BATCH_ADD, LDAP_MODIFY_BATCH_REMOVE, LDAP_MODIFY_BATCH_REMOVE_ALL, LDAP_MODIFY_BATCH_REPLACE, - ); + ]; /** * @param int $operationType An LDAP_MODIFY_BATCH_* constant @@ -48,10 +48,10 @@ class UpdateOperation public function toArray(): array { - return array( + return [ 'attrib' => $this->attribute, 'modtype' => $this->operationType, 'values' => $this->values, - ); + ]; } } diff --git a/src/Symfony/Component/Ldap/Tests/Adapter/ExtLdap/LdapManagerTest.php b/src/Symfony/Component/Ldap/Tests/Adapter/ExtLdap/LdapManagerTest.php index da21433a1e..18c1461e98 100644 --- a/src/Symfony/Component/Ldap/Tests/Adapter/ExtLdap/LdapManagerTest.php +++ b/src/Symfony/Component/Ldap/Tests/Adapter/ExtLdap/LdapManagerTest.php @@ -250,7 +250,7 @@ class LdapManagerTest extends LdapTestCase $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}(UpdateOperationException::class); - $entryManager->applyOperations($entry->getDn(), array(new UpdateOperation(LDAP_MODIFY_BATCH_REMOVE_ALL, 'mail', array()))); + $entryManager->applyOperations($entry->getDn(), [new UpdateOperation(LDAP_MODIFY_BATCH_REMOVE_ALL, 'mail', [])]); } public function testLdapApplyOperationsWithWrongConstantError() @@ -262,7 +262,7 @@ class LdapManagerTest extends LdapTestCase $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}(UpdateOperationException::class); - $entryManager->applyOperations($entry->getDn(), array(new UpdateOperation(512, 'mail', array()))); + $entryManager->applyOperations($entry->getDn(), [new UpdateOperation(512, 'mail', [])]); } public function testApplyOperationsAddRemoveAttributeValues() @@ -272,20 +272,20 @@ class LdapManagerTest extends LdapTestCase $result = $this->executeSearchQuery(1); $entry = $result[0]; - $entryManager->applyOperations($entry->getDn(), array( - new UpdateOperation(LDAP_MODIFY_BATCH_ADD, 'mail', array('fabpot@example.org', 'fabpot2@example.org')), - new UpdateOperation(LDAP_MODIFY_BATCH_ADD, 'mail', array('fabpot3@example.org', 'fabpot4@example.org')), - )); + $entryManager->applyOperations($entry->getDn(), [ + new UpdateOperation(LDAP_MODIFY_BATCH_ADD, 'mail', ['fabpot@example.org', 'fabpot2@example.org']), + new UpdateOperation(LDAP_MODIFY_BATCH_ADD, 'mail', ['fabpot3@example.org', 'fabpot4@example.org']), + ]); $result = $this->executeSearchQuery(1); $newEntry = $result[0]; $this->assertCount(6, $newEntry->getAttribute('mail')); - $entryManager->applyOperations($entry->getDn(), array( - new UpdateOperation(LDAP_MODIFY_BATCH_REMOVE, 'mail', array('fabpot@example.org', 'fabpot2@example.org')), - new UpdateOperation(LDAP_MODIFY_BATCH_REMOVE, 'mail', array('fabpot3@example.org', 'fabpot4@example.org')), - )); + $entryManager->applyOperations($entry->getDn(), [ + new UpdateOperation(LDAP_MODIFY_BATCH_REMOVE, 'mail', ['fabpot@example.org', 'fabpot2@example.org']), + new UpdateOperation(LDAP_MODIFY_BATCH_REMOVE, 'mail', ['fabpot3@example.org', 'fabpot4@example.org']), + ]); $result = $this->executeSearchQuery(1); $newNewEntry = $result[0]; @@ -295,15 +295,15 @@ class LdapManagerTest extends LdapTestCase public function testUpdateOperationsWithIterator() { - $iteratorAdd = new \ArrayIterator(array( - new UpdateOperation(LDAP_MODIFY_BATCH_ADD, 'mail', array('fabpot@example.org', 'fabpot2@example.org')), - new UpdateOperation(LDAP_MODIFY_BATCH_ADD, 'mail', array('fabpot3@example.org', 'fabpot4@example.org')), - )); + $iteratorAdd = new \ArrayIterator([ + new UpdateOperation(LDAP_MODIFY_BATCH_ADD, 'mail', ['fabpot@example.org', 'fabpot2@example.org']), + new UpdateOperation(LDAP_MODIFY_BATCH_ADD, 'mail', ['fabpot3@example.org', 'fabpot4@example.org']), + ]); - $iteratorRemove = new \ArrayIterator(array( - new UpdateOperation(LDAP_MODIFY_BATCH_REMOVE, 'mail', array('fabpot@example.org', 'fabpot2@example.org')), - new UpdateOperation(LDAP_MODIFY_BATCH_REMOVE, 'mail', array('fabpot3@example.org', 'fabpot4@example.org')), - )); + $iteratorRemove = new \ArrayIterator([ + new UpdateOperation(LDAP_MODIFY_BATCH_REMOVE, 'mail', ['fabpot@example.org', 'fabpot2@example.org']), + new UpdateOperation(LDAP_MODIFY_BATCH_REMOVE, 'mail', ['fabpot3@example.org', 'fabpot4@example.org']), + ]); $entryManager = $this->adapter->getEntryManager(); @@ -327,10 +327,10 @@ class LdapManagerTest extends LdapTestCase public function testUpdateOperationsThrowsExceptionWhenAddedDuplicatedValue() { - $duplicateIterator = new \ArrayIterator(array( - new UpdateOperation(LDAP_MODIFY_BATCH_ADD, 'mail', array('fabpot@example.org')), - new UpdateOperation(LDAP_MODIFY_BATCH_ADD, 'mail', array('fabpot@example.org')), - )); + $duplicateIterator = new \ArrayIterator([ + new UpdateOperation(LDAP_MODIFY_BATCH_ADD, 'mail', ['fabpot@example.org']), + new UpdateOperation(LDAP_MODIFY_BATCH_ADD, 'mail', ['fabpot@example.org']), + ]); $entryManager = $this->adapter->getEntryManager(); diff --git a/src/Symfony/Component/Lock/Lock.php b/src/Symfony/Component/Lock/Lock.php index 03ac44cd12..97117a8204 100644 --- a/src/Symfony/Component/Lock/Lock.php +++ b/src/Symfony/Component/Lock/Lock.php @@ -76,7 +76,7 @@ final class Lock implements LockInterface, LoggerAwareInterface } $this->dirty = true; - $this->logger->info('Successfully acquired the "{resource}" lock.', array('resource' => $this->key)); + $this->logger->info('Successfully acquired the "{resource}" lock.', ['resource' => $this->key]); if ($this->ttl) { $this->refresh(); @@ -89,7 +89,7 @@ final class Lock implements LockInterface, LoggerAwareInterface return true; } catch (LockConflictedException $e) { $this->dirty = false; - $this->logger->notice('Failed to acquire the "{resource}" lock. Someone else already acquired the lock.', array('resource' => $this->key)); + $this->logger->notice('Failed to acquire the "{resource}" lock. Someone else already acquired the lock.', ['resource' => $this->key]); if ($blocking) { throw $e; @@ -97,7 +97,7 @@ final class Lock implements LockInterface, LoggerAwareInterface return false; } catch (\Exception $e) { - $this->logger->notice('Failed to acquire the "{resource}" lock.', array('resource' => $this->key, 'exception' => $e)); + $this->logger->notice('Failed to acquire the "{resource}" lock.', ['resource' => $this->key, 'exception' => $e]); throw new LockAcquiringException(sprintf('Failed to acquire the "%s" lock.', $this->key), 0, $e); } } @@ -123,13 +123,13 @@ final class Lock implements LockInterface, LoggerAwareInterface throw new LockExpiredException(sprintf('Failed to put off the expiration of the "%s" lock within the specified time.', $this->key)); } - $this->logger->info('Expiration defined for "{resource}" lock for "{ttl}" seconds.', array('resource' => $this->key, 'ttl' => $ttl)); + $this->logger->info('Expiration defined for "{resource}" lock for "{ttl}" seconds.', ['resource' => $this->key, 'ttl' => $ttl]); } catch (LockConflictedException $e) { $this->dirty = false; - $this->logger->notice('Failed to define an expiration for the "{resource}" lock, someone else acquired the lock.', array('resource' => $this->key)); + $this->logger->notice('Failed to define an expiration for the "{resource}" lock, someone else acquired the lock.', ['resource' => $this->key]); throw $e; } catch (\Exception $e) { - $this->logger->notice('Failed to define an expiration for the "{resource}" lock.', array('resource' => $this->key, 'exception' => $e)); + $this->logger->notice('Failed to define an expiration for the "{resource}" lock.', ['resource' => $this->key, 'exception' => $e]); throw new LockAcquiringException(sprintf('Failed to define an expiration for the "%s" lock.', $this->key), 0, $e); } } @@ -161,7 +161,7 @@ final class Lock implements LockInterface, LoggerAwareInterface throw new LockReleasingException(sprintf('Failed to release the "%s" lock, the resource is still locked.', $this->key)); } } catch (LockReleasingException $e) { - $this->logger->notice('Failed to release the "{resource}" lock.', array('resource' => $this->key)); + $this->logger->notice('Failed to release the "{resource}" lock.', ['resource' => $this->key]); throw $e; } } diff --git a/src/Symfony/Component/Lock/Store/PdoStore.php b/src/Symfony/Component/Lock/Store/PdoStore.php index 710eca668f..f51149d02e 100644 --- a/src/Symfony/Component/Lock/Store/PdoStore.php +++ b/src/Symfony/Component/Lock/Store/PdoStore.php @@ -45,7 +45,7 @@ class PdoStore implements StoreInterface private $expirationCol = 'key_expiration'; private $username = ''; private $password = ''; - private $connectionOptions = array(); + private $connectionOptions = []; private $gcProbability; private $initialTtl; @@ -73,7 +73,7 @@ class PdoStore implements StoreInterface * @throws InvalidArgumentException When namespace contains invalid characters * @throws InvalidArgumentException When the initial ttl is not valid */ - public function __construct($connOrDsn, array $options = array(), float $gcProbability = 0.01, int $initialTtl = 300) + public function __construct($connOrDsn, array $options = [], float $gcProbability = 0.01, int $initialTtl = 300) { if ($gcProbability < 0 || $gcProbability > 1) { throw new InvalidArgumentException(sprintf('"%s" requires gcProbability between 0 and 1, "%f" given.', __METHOD__, $gcProbability)); @@ -258,10 +258,10 @@ class PdoStore implements StoreInterface if ($conn instanceof Connection) { $schema = new Schema(); $table = $schema->createTable($this->table); - $table->addColumn($this->idCol, 'string', array('length' => 64)); - $table->addColumn($this->tokenCol, 'string', array('length' => 44)); - $table->addColumn($this->expirationCol, 'integer', array('unsigned' => true)); - $table->setPrimaryKey(array($this->idCol)); + $table->addColumn($this->idCol, 'string', ['length' => 64]); + $table->addColumn($this->tokenCol, 'string', ['length' => 44]); + $table->addColumn($this->expirationCol, 'integer', ['unsigned' => true]); + $table->setPrimaryKey([$this->idCol]); foreach ($schema->toSql($conn->getDatabasePlatform()) as $sql) { $conn->exec($sql); diff --git a/src/Symfony/Component/Lock/Store/RedisStore.php b/src/Symfony/Component/Lock/Store/RedisStore.php index 08965dbfb1..d07a2ce27f 100644 --- a/src/Symfony/Component/Lock/Store/RedisStore.php +++ b/src/Symfony/Component/Lock/Store/RedisStore.php @@ -63,7 +63,7 @@ class RedisStore implements StoreInterface '; $key->reduceLifetime($this->initialTtl); - if (!$this->evaluate($script, (string) $key, array($this->getUniqueToken($key), (int) ceil($this->initialTtl * 1000)))) { + if (!$this->evaluate($script, (string) $key, [$this->getUniqueToken($key), (int) ceil($this->initialTtl * 1000)])) { throw new LockConflictedException(); } @@ -91,7 +91,7 @@ class RedisStore implements StoreInterface '; $key->reduceLifetime($ttl); - if (!$this->evaluate($script, (string) $key, array($this->getUniqueToken($key), (int) ceil($ttl * 1000)))) { + if (!$this->evaluate($script, (string) $key, [$this->getUniqueToken($key), (int) ceil($ttl * 1000)])) { throw new LockConflictedException(); } @@ -113,7 +113,7 @@ class RedisStore implements StoreInterface end '; - $this->evaluate($script, (string) $key, array($this->getUniqueToken($key))); + $this->evaluate($script, (string) $key, [$this->getUniqueToken($key)]); } /** @@ -137,15 +137,15 @@ class RedisStore implements StoreInterface $this->redis instanceof RedisProxy || $this->redis instanceof RedisClusterProxy ) { - return $this->redis->eval($script, array_merge(array($resource), $args), 1); + return $this->redis->eval($script, array_merge([$resource], $args), 1); } if ($this->redis instanceof \RedisArray) { - return $this->redis->_instance($this->redis->_target($resource))->eval($script, array_merge(array($resource), $args), 1); + return $this->redis->_instance($this->redis->_target($resource))->eval($script, array_merge([$resource], $args), 1); } if ($this->redis instanceof \Predis\Client) { - return $this->redis->eval(...array_merge(array($script, 1, $resource), $args)); + return $this->redis->eval(...array_merge([$script, 1, $resource], $args)); } throw new InvalidArgumentException(sprintf('%s() expects being initialized with a Redis, RedisArray, RedisCluster or Predis\Client, %s given', __METHOD__, \is_object($this->redis) ? \get_class($this->redis) : \gettype($this->redis))); diff --git a/src/Symfony/Component/Lock/Store/ZookeeperStore.php b/src/Symfony/Component/Lock/Store/ZookeeperStore.php index 2304dd47a0..c755ce1a1c 100644 --- a/src/Symfony/Component/Lock/Store/ZookeeperStore.php +++ b/src/Symfony/Component/Lock/Store/ZookeeperStore.php @@ -106,7 +106,7 @@ class ZookeeperStore implements StoreInterface private function createNewLock(string $node, string $value) { // Default Node Permissions - $acl = array(array('perms' => \Zookeeper::PERM_ALL, 'scheme' => 'world', 'id' => 'anyone')); + $acl = [['perms' => \Zookeeper::PERM_ALL, 'scheme' => 'world', 'id' => 'anyone']]; // This ensures that the nodes are deleted when the client session to zookeeper server ends. $type = \Zookeeper::EPHEMERAL; @@ -128,7 +128,7 @@ class ZookeeperStore implements StoreInterface $resource = (string) $key; if (false !== \strpos($resource, '/')) { - $resource = \strtr($resource, array('/' => '-')).'-'.sha1($resource); + $resource = \strtr($resource, ['/' => '-']).'-'.sha1($resource); } if ('' === $resource) { diff --git a/src/Symfony/Component/Lock/Tests/Store/BlockingStoreTestTrait.php b/src/Symfony/Component/Lock/Tests/Store/BlockingStoreTestTrait.php index 0d91175c0c..21f1245e7e 100644 --- a/src/Symfony/Component/Lock/Tests/Store/BlockingStoreTestTrait.php +++ b/src/Symfony/Component/Lock/Tests/Store/BlockingStoreTestTrait.php @@ -45,11 +45,11 @@ trait BlockingStoreTestTrait $parentPID = posix_getpid(); // Block SIGHUP signal - pcntl_sigprocmask(SIG_BLOCK, array(SIGHUP)); + pcntl_sigprocmask(SIG_BLOCK, [SIGHUP]); if ($childPID = pcntl_fork()) { // Wait the start of the child - pcntl_sigwaitinfo(array(SIGHUP), $info); + pcntl_sigwaitinfo([SIGHUP], $info); $store = $this->getStore(); try { @@ -72,7 +72,7 @@ trait BlockingStoreTestTrait $this->assertSame(0, pcntl_wexitstatus($status1), 'The child process couldn\'t lock the resource'); } else { // Block SIGHUP signal - pcntl_sigprocmask(SIG_BLOCK, array(SIGHUP)); + pcntl_sigprocmask(SIG_BLOCK, [SIGHUP]); $store = $this->getStore(); try { @@ -81,7 +81,7 @@ trait BlockingStoreTestTrait posix_kill($parentPID, SIGHUP); // Wait for the parent to be ready - pcntl_sigwaitinfo(array(SIGHUP), $info); + pcntl_sigwaitinfo([SIGHUP], $info); // Wait ClockDelay to let parent assert to finish usleep($clockDelay); diff --git a/src/Symfony/Component/Lock/Tests/Store/PdoDbalStoreTest.php b/src/Symfony/Component/Lock/Tests/Store/PdoDbalStoreTest.php index e72fbcf76b..0dd32c0847 100644 --- a/src/Symfony/Component/Lock/Tests/Store/PdoDbalStoreTest.php +++ b/src/Symfony/Component/Lock/Tests/Store/PdoDbalStoreTest.php @@ -29,7 +29,7 @@ class PdoDbalStoreTest extends AbstractStoreTest { self::$dbFile = tempnam(sys_get_temp_dir(), 'sf_sqlite_lock'); - $store = new PdoStore(DriverManager::getConnection(array('driver' => 'pdo_sqlite', 'path' => self::$dbFile))); + $store = new PdoStore(DriverManager::getConnection(['driver' => 'pdo_sqlite', 'path' => self::$dbFile])); $store->createTable(); } @@ -51,7 +51,7 @@ class PdoDbalStoreTest extends AbstractStoreTest */ public function getStore() { - return new PdoStore(DriverManager::getConnection(array('driver' => 'pdo_sqlite', 'path' => self::$dbFile))); + return new PdoStore(DriverManager::getConnection(['driver' => 'pdo_sqlite', 'path' => self::$dbFile])); } public function testAbortAfterExpiration() diff --git a/src/Symfony/Component/Lock/Tests/Store/ZookeeperStoreTest.php b/src/Symfony/Component/Lock/Tests/Store/ZookeeperStoreTest.php index 73be28bcca..0ba6d73b9f 100644 --- a/src/Symfony/Component/Lock/Tests/Store/ZookeeperStoreTest.php +++ b/src/Symfony/Component/Lock/Tests/Store/ZookeeperStoreTest.php @@ -26,7 +26,7 @@ class ZookeeperStoreTest extends AbstractStoreTest { $zookeeper_server = getenv('ZOOKEEPER_HOST').':2181'; - $zookeeper = new \Zookeeper(implode(',', array($zookeeper_server))); + $zookeeper = new \Zookeeper(implode(',', [$zookeeper_server])); return StoreFactory::createStore($zookeeper); } diff --git a/src/Symfony/Component/Messenger/Command/ConsumeMessagesCommand.php b/src/Symfony/Component/Messenger/Command/ConsumeMessagesCommand.php index 83b834c593..c455dbafbb 100644 --- a/src/Symfony/Component/Messenger/Command/ConsumeMessagesCommand.php +++ b/src/Symfony/Component/Messenger/Command/ConsumeMessagesCommand.php @@ -40,7 +40,7 @@ class ConsumeMessagesCommand extends Command private $receiverNames; private $busNames; - public function __construct(ContainerInterface $busLocator, ContainerInterface $receiverLocator, LoggerInterface $logger = null, array $receiverNames = array(), array $busNames = array()) + public function __construct(ContainerInterface $busLocator, ContainerInterface $receiverLocator, LoggerInterface $logger = null, array $receiverNames = [], array $busNames = []) { $this->busLocator = $busLocator; $this->receiverLocator = $receiverLocator; @@ -60,13 +60,13 @@ class ConsumeMessagesCommand extends Command $defaultBusName = 1 === \count($this->busNames) ? current($this->busNames) : null; $this - ->setDefinition(array( + ->setDefinition([ new InputArgument('receiver', $defaultReceiverName ? InputArgument::OPTIONAL : InputArgument::REQUIRED, 'Name of the receiver', $defaultReceiverName), new InputOption('limit', 'l', InputOption::VALUE_REQUIRED, 'Limit the number of received messages'), new InputOption('memory-limit', 'm', InputOption::VALUE_REQUIRED, 'The memory limit the worker can consume'), new InputOption('time-limit', 't', InputOption::VALUE_REQUIRED, 'The time limit in seconds the worker can run'), new InputOption('bus', 'b', InputOption::VALUE_REQUIRED, 'Name of the bus to which received messages should be dispatched', $defaultBusName), - )) + ]) ->setDescription('Consumes messages') ->setHelp(<<<'EOF' The %command.name% command consumes messages and dispatches them to the message bus. @@ -186,7 +186,7 @@ EOF private function findAlternatives($name, array $collection) { - $alternatives = array(); + $alternatives = []; foreach ($collection as $item) { $lev = levenshtein($name, $item); if ($lev <= \strlen($name) / 3 || false !== strpos($item, $name)) { diff --git a/src/Symfony/Component/Messenger/DataCollector/MessengerDataCollector.php b/src/Symfony/Component/Messenger/DataCollector/MessengerDataCollector.php index d36c70f4ef..5d33f735b2 100644 --- a/src/Symfony/Component/Messenger/DataCollector/MessengerDataCollector.php +++ b/src/Symfony/Component/Messenger/DataCollector/MessengerDataCollector.php @@ -25,7 +25,7 @@ use Symfony\Component\VarDumper\Caster\ClassStub; */ class MessengerDataCollector extends DataCollector implements LateDataCollectorInterface { - private $traceableBuses = array(); + private $traceableBuses = []; public function registerBus(string $name, TraceableMessageBus $bus) { @@ -45,13 +45,13 @@ class MessengerDataCollector extends DataCollector implements LateDataCollectorI */ public function lateCollect() { - $this->data = array('messages' => array(), 'buses' => array_keys($this->traceableBuses)); + $this->data = ['messages' => [], 'buses' => array_keys($this->traceableBuses)]; - $messages = array(); + $messages = []; foreach ($this->traceableBuses as $busName => $bus) { foreach ($bus->getDispatchedMessages() as $message) { $debugRepresentation = $this->cloneVar($this->collectMessage($busName, $message)); - $messages[] = array($debugRepresentation, $message['callTime']); + $messages[] = [$debugRepresentation, $message['callTime']]; } } @@ -75,7 +75,7 @@ class MessengerDataCollector extends DataCollector implements LateDataCollectorI */ public function reset() { - $this->data = array(); + $this->data = []; foreach ($this->traceableBuses as $traceableBus) { $traceableBus->reset(); } @@ -85,23 +85,23 @@ class MessengerDataCollector extends DataCollector implements LateDataCollectorI { $message = $tracedMessage['message']; - $debugRepresentation = array( + $debugRepresentation = [ 'bus' => $busName, 'stamps' => $tracedMessage['stamps'] ?? null, - 'message' => array( + 'message' => [ 'type' => new ClassStub(\get_class($message)), 'value' => $message, - ), + ], 'caller' => $tracedMessage['caller'], - ); + ]; if (isset($tracedMessage['exception'])) { $exception = $tracedMessage['exception']; - $debugRepresentation['exception'] = array( + $debugRepresentation['exception'] = [ 'type' => \get_class($exception), 'value' => $exception, - ); + ]; } return $debugRepresentation; diff --git a/src/Symfony/Component/Messenger/DependencyInjection/MessengerPass.php b/src/Symfony/Component/Messenger/DependencyInjection/MessengerPass.php index 5a18dd8683..8c4773462e 100644 --- a/src/Symfony/Component/Messenger/DependencyInjection/MessengerPass.php +++ b/src/Symfony/Component/Messenger/DependencyInjection/MessengerPass.php @@ -47,7 +47,7 @@ class MessengerPass implements CompilerPassInterface */ public function process(ContainerBuilder $container) { - $busIds = array(); + $busIds = []; foreach ($container->findTaggedServiceIds($this->busTag) as $busId => $tags) { $busIds[] = $busId; if ($container->hasParameter($busMiddlewareParameter = $busId.'.middleware')) { @@ -69,8 +69,8 @@ class MessengerPass implements CompilerPassInterface private function registerHandlers(ContainerBuilder $container, array $busIds) { - $definitions = array(); - $handlersByBusAndMessage = array(); + $definitions = []; + $handlersByBusAndMessage = []; foreach ($container->findTaggedServiceIds($this->handlerTag, true) as $serviceId => $tags) { foreach ($tags as $tag) { @@ -86,7 +86,7 @@ class MessengerPass implements CompilerPassInterface } if (isset($tag['handles'])) { - $handles = isset($tag['method']) ? array($tag['handles'] => $tag['method']) : array($tag['handles']); + $handles = isset($tag['method']) ? [$tag['handles'] => $tag['method']] : [$tag['handles']]; } else { $handles = $this->guessHandledClasses($r, $serviceId); } @@ -115,7 +115,7 @@ class MessengerPass implements CompilerPassInterface throw new RuntimeException(sprintf('Invalid configuration %s for message "%s": bus "%s" does not exist.', $messageLocation, $message, $method['bus'])); } - $buses = array($method['bus']); + $buses = [$method['bus']]; } $priority = $method['priority'] ?? $priority; @@ -133,7 +133,7 @@ class MessengerPass implements CompilerPassInterface } if ('__invoke' !== $method) { - $wrapperDefinition = (new Definition('callable'))->addArgument(array(new Reference($serviceId), $method))->setFactory('Closure::fromCallable'); + $wrapperDefinition = (new Definition('callable'))->addArgument([new Reference($serviceId), $method])->setFactory('Closure::fromCallable'); $definitions[$definitionId = '.messenger.method_on_object_wrapper.'.ContainerBuilder::hash($message.':'.$priority.':'.$serviceId.':'.$method)] = $wrapperDefinition; } else { @@ -158,7 +158,7 @@ class MessengerPass implements CompilerPassInterface } } - $handlersLocatorMappingByBus = array(); + $handlersLocatorMappingByBus = []; foreach ($handlersByBusAndMessage as $bus => $handlersByMessage) { foreach ($handlersByMessage as $message => $handlerIds) { $handlers = array_map(function (string $handlerId) { return new Reference($handlerId); }, $handlerIds); @@ -169,7 +169,7 @@ class MessengerPass implements CompilerPassInterface foreach ($busIds as $bus) { $container->register($locatorId = $bus.'.messenger.handlers_locator', HandlersLocator::class) - ->setArgument(0, $handlersLocatorMappingByBus[$bus] ?? array()) + ->setArgument(0, $handlersLocatorMappingByBus[$bus] ?? []) ; if ($container->has($handleMessageId = $bus.'.middleware.handle_message')) { $container->getDefinition($handleMessageId) @@ -182,7 +182,7 @@ class MessengerPass implements CompilerPassInterface $debugCommandMapping = $handlersByBusAndMessage; foreach ($busIds as $bus) { if (!isset($debugCommandMapping[$bus])) { - $debugCommandMapping[$bus] = array(); + $debugCommandMapping[$bus] = []; } } $container->getDefinition('console.command.messenger_debug')->replaceArgument(0, $debugCommandMapping); @@ -214,12 +214,12 @@ class MessengerPass implements CompilerPassInterface throw new RuntimeException(sprintf('Invalid handler service "%s": type-hint of argument "$%s" in method "%s::__invoke()" must be a class , "%s" given.', $serviceId, $parameters[0]->getName(), $handlerClass->getName(), $type)); } - return array((string) $parameters[0]->getType()); + return [(string) $parameters[0]->getType()]; } private function registerReceivers(ContainerBuilder $container, array $busIds) { - $receiverMapping = array(); + $receiverMapping = []; foreach ($container->findTaggedServiceIds($this->receiverTag) as $id => $tags) { $receiverClass = $container->findDefinition($id)->getClass(); @@ -237,11 +237,11 @@ class MessengerPass implements CompilerPassInterface } if ($container->hasDefinition('console.command.messenger_consume_messages')) { - $receiverNames = array(); + $receiverNames = []; foreach ($receiverMapping as $name => $reference) { $receiverNames[(string) $reference] = $name; } - $buses = array(); + $buses = []; foreach ($busIds as $busId) { $buses[$busId] = new Reference($busId); } @@ -259,18 +259,18 @@ class MessengerPass implements CompilerPassInterface { $container->setDefinition( $tracedBusId = 'debug.traced.'.$busId, - (new Definition(TraceableMessageBus::class, array(new Reference($tracedBusId.'.inner'))))->setDecoratedService($busId) + (new Definition(TraceableMessageBus::class, [new Reference($tracedBusId.'.inner')]))->setDecoratedService($busId) ); - $container->getDefinition('data_collector.messenger')->addMethodCall('registerBus', array($busId, new Reference($tracedBusId))); + $container->getDefinition('data_collector.messenger')->addMethodCall('registerBus', [$busId, new Reference($tracedBusId)]); } private function registerBusMiddleware(ContainerBuilder $container, string $busId, array $middlewareCollection) { - $middlewareReferences = array(); + $middlewareReferences = []; foreach ($middlewareCollection as $middlewareItem) { $id = $middlewareItem['id']; - $arguments = $middlewareItem['arguments'] ?? array(); + $arguments = $middlewareItem['arguments'] ?? []; if (!$container->has($messengerMiddlewareId = 'messenger.middleware.'.$id)) { $messengerMiddlewareId = $id; } diff --git a/src/Symfony/Component/Messenger/Envelope.php b/src/Symfony/Component/Messenger/Envelope.php index a6e7db8476..02d0dca123 100644 --- a/src/Symfony/Component/Messenger/Envelope.php +++ b/src/Symfony/Component/Messenger/Envelope.php @@ -22,7 +22,7 @@ use Symfony\Component\Messenger\Stamp\StampInterface; */ final class Envelope { - private $stamps = array(); + private $stamps = []; private $message; /** @@ -65,7 +65,7 @@ final class Envelope public function all(string $stampFqcn = null): array { if (null !== $stampFqcn) { - return $this->stamps[$stampFqcn] ?? array(); + return $this->stamps[$stampFqcn] ?? []; } return $this->stamps; diff --git a/src/Symfony/Component/Messenger/Handler/HandlersLocator.php b/src/Symfony/Component/Messenger/Handler/HandlersLocator.php index d0642498ba..9094eb3dbc 100644 --- a/src/Symfony/Component/Messenger/Handler/HandlersLocator.php +++ b/src/Symfony/Component/Messenger/Handler/HandlersLocator.php @@ -37,10 +37,10 @@ class HandlersLocator implements HandlersLocatorInterface */ public function getHandlers(Envelope $envelope): iterable { - $seen = array(); + $seen = []; foreach (self::listTypes($envelope) as $type) { - foreach ($this->handlers[$type] ?? array() as $alias => $handler) { + foreach ($this->handlers[$type] ?? [] as $alias => $handler) { if (!\in_array($handler, $seen, true)) { yield $alias => $seen[] = $handler; } @@ -55,9 +55,9 @@ class HandlersLocator implements HandlersLocatorInterface { $class = \get_class($envelope->getMessage()); - return array($class => $class) + return [$class => $class] + class_parents($class) + class_implements($class) - + array('*' => '*'); + + ['*' => '*']; } } diff --git a/src/Symfony/Component/Messenger/Middleware/LoggingMiddleware.php b/src/Symfony/Component/Messenger/Middleware/LoggingMiddleware.php index 22c88edb7e..7518d018b8 100644 --- a/src/Symfony/Component/Messenger/Middleware/LoggingMiddleware.php +++ b/src/Symfony/Component/Messenger/Middleware/LoggingMiddleware.php @@ -34,10 +34,10 @@ class LoggingMiddleware implements MiddlewareInterface public function handle(Envelope $envelope, StackInterface $stack): Envelope { $message = $envelope->getMessage(); - $context = array( + $context = [ 'message' => $message, 'class' => \get_class($envelope->getMessage()), - ); + ]; $this->logger->debug('Starting handling message "{class}"', $context); try { diff --git a/src/Symfony/Component/Messenger/Tests/Command/ConsumeMessagesCommandTest.php b/src/Symfony/Component/Messenger/Tests/Command/ConsumeMessagesCommandTest.php index e5a1940d8c..336cd8129c 100644 --- a/src/Symfony/Component/Messenger/Tests/Command/ConsumeMessagesCommandTest.php +++ b/src/Symfony/Component/Messenger/Tests/Command/ConsumeMessagesCommandTest.php @@ -19,7 +19,7 @@ class ConsumeMessagesCommandTest extends TestCase { public function testConfigurationWithDefaultReceiver() { - $command = new ConsumeMessagesCommand($this->createMock(ServiceLocator::class), $this->createMock(ServiceLocator::class), null, array('amqp')); + $command = new ConsumeMessagesCommand($this->createMock(ServiceLocator::class), $this->createMock(ServiceLocator::class), null, ['amqp']); $inputArgument = $command->getDefinition()->getArgument('receiver'); $this->assertFalse($inputArgument->isRequired()); $this->assertSame('amqp', $inputArgument->getDefault()); @@ -27,7 +27,7 @@ class ConsumeMessagesCommandTest extends TestCase public function testConfigurationWithoutDefaultReceiver() { - $command = new ConsumeMessagesCommand($this->createMock(ServiceLocator::class), $this->createMock(ServiceLocator::class), null, array('amqp', 'dummy')); + $command = new ConsumeMessagesCommand($this->createMock(ServiceLocator::class), $this->createMock(ServiceLocator::class), null, ['amqp', 'dummy']); $inputArgument = $command->getDefinition()->getArgument('receiver'); $this->assertTrue($inputArgument->isRequired()); $this->assertNull($inputArgument->getDefault()); diff --git a/src/Symfony/Component/Messenger/Tests/DependencyInjection/MessengerPassTest.php b/src/Symfony/Component/Messenger/Tests/DependencyInjection/MessengerPassTest.php index f88743aea2..6c97608c9f 100644 --- a/src/Symfony/Component/Messenger/Tests/DependencyInjection/MessengerPassTest.php +++ b/src/Symfony/Component/Messenger/Tests/DependencyInjection/MessengerPassTest.php @@ -52,7 +52,7 @@ class MessengerPassTest extends TestCase ; $container ->register(MissingArgumentTypeHandler::class, MissingArgumentTypeHandler::class) - ->addTag('messenger.message_handler', array('handles' => SecondMessage::class)) + ->addTag('messenger.message_handler', ['handles' => SecondMessage::class]) ; $container ->register(DummyReceiver::class, DummyReceiver::class) @@ -66,15 +66,15 @@ class MessengerPassTest extends TestCase $handlersLocatorDefinition = $container->getDefinition($busId.'.messenger.handlers_locator'); $this->assertSame(HandlersLocator::class, $handlersLocatorDefinition->getClass()); $this->assertEquals( - array( - DummyMessage::class => new IteratorArgument(array(new Reference(DummyHandler::class))), - SecondMessage::class => new IteratorArgument(array(new Reference(MissingArgumentTypeHandler::class))), - ), + [ + DummyMessage::class => new IteratorArgument([new Reference(DummyHandler::class)]), + SecondMessage::class => new IteratorArgument([new Reference(MissingArgumentTypeHandler::class)]), + ], $handlersLocatorDefinition->getArgument(0) ); $this->assertEquals( - array(DummyReceiver::class => new Reference(DummyReceiver::class)), + [DummyReceiver::class => new Reference(DummyReceiver::class)], $container->getDefinition('messenger.receiver_locator')->getArgument(0) ); } @@ -82,22 +82,22 @@ class MessengerPassTest extends TestCase public function testProcessHandlersByBus() { $container = $this->getContainerBuilder($commandBusId = 'command_bus'); - $container->register($queryBusId = 'query_bus', MessageBusInterface::class)->setArgument(0, array())->addTag('messenger.bus'); + $container->register($queryBusId = 'query_bus', MessageBusInterface::class)->setArgument(0, [])->addTag('messenger.bus'); $container->register('messenger.middleware.handle_message', HandleMessageMiddleware::class) ->addArgument(null) ->setAbstract(true) ; - $middlewareHandlers = array(array('id' => 'handle_message')); + $middlewareHandlers = [['id' => 'handle_message']]; $container->setParameter($commandBusId.'.middleware', $middlewareHandlers); $container->setParameter($queryBusId.'.middleware', $middlewareHandlers); - $container->register(DummyCommandHandler::class)->addTag('messenger.message_handler', array('bus' => $commandBusId)); - $container->register(DummyQueryHandler::class)->addTag('messenger.message_handler', array('bus' => $queryBusId)); + $container->register(DummyCommandHandler::class)->addTag('messenger.message_handler', ['bus' => $commandBusId]); + $container->register(DummyQueryHandler::class)->addTag('messenger.message_handler', ['bus' => $queryBusId]); $container->register(MultipleBusesMessageHandler::class) - ->addTag('messenger.message_handler', array('bus' => $commandBusId)) - ->addTag('messenger.message_handler', array('bus' => $queryBusId)) + ->addTag('messenger.message_handler', ['bus' => $commandBusId]) + ->addTag('messenger.message_handler', ['bus' => $queryBusId]) ; (new ResolveClassPass())->process($container); @@ -106,20 +106,20 @@ class MessengerPassTest extends TestCase $commandBusHandlersLocatorDefinition = $container->getDefinition($commandBusId.'.messenger.handlers_locator'); $this->assertSame(HandlersLocator::class, $commandBusHandlersLocatorDefinition->getClass()); $this->assertEquals( - array( - MultipleBusesMessage::class => new IteratorArgument(array(new Reference(MultipleBusesMessageHandler::class))), - DummyCommand::class => new IteratorArgument(array(new Reference(DummyCommandHandler::class))), - ), + [ + MultipleBusesMessage::class => new IteratorArgument([new Reference(MultipleBusesMessageHandler::class)]), + DummyCommand::class => new IteratorArgument([new Reference(DummyCommandHandler::class)]), + ], $commandBusHandlersLocatorDefinition->getArgument(0) ); $queryBusHandlersLocatorDefinition = $container->getDefinition($queryBusId.'.messenger.handlers_locator'); $this->assertSame(HandlersLocator::class, $queryBusHandlersLocatorDefinition->getClass()); $this->assertEquals( - array( - DummyQuery::class => new IteratorArgument(array(new Reference(DummyQueryHandler::class))), - MultipleBusesMessage::class => new IteratorArgument(array(new Reference(MultipleBusesMessageHandler::class))), - ), + [ + DummyQuery::class => new IteratorArgument([new Reference(DummyQueryHandler::class)]), + MultipleBusesMessage::class => new IteratorArgument([new Reference(MultipleBusesMessageHandler::class)]), + ], $queryBusHandlersLocatorDefinition->getArgument(0) ); } @@ -132,7 +132,7 @@ class MessengerPassTest extends TestCase { $container = $this->getContainerBuilder($commandBusId = 'command_bus'); - $container->register(DummyCommandHandler::class)->addTag('messenger.message_handler', array('bus' => 'unknown_bus')); + $container->register(DummyCommandHandler::class)->addTag('messenger.message_handler', ['bus' => 'unknown_bus']); (new ResolveClassPass())->process($container); (new MessengerPass())->process($container); @@ -155,10 +155,10 @@ class MessengerPassTest extends TestCase $handlersMapping = $container->getDefinition($busId.'.messenger.handlers_locator')->getArgument(0); $this->assertArrayHasKey(DummyMessage::class, $handlersMapping); - $this->assertEquals(new IteratorArgument(array(new Reference(HandlerWithMultipleMessages::class))), $handlersMapping[DummyMessage::class]); + $this->assertEquals(new IteratorArgument([new Reference(HandlerWithMultipleMessages::class)]), $handlersMapping[DummyMessage::class]); $this->assertArrayHasKey(SecondMessage::class, $handlersMapping); - $this->assertEquals(new IteratorArgument(array(new Reference(PrioritizedHandler::class), new Reference(HandlerWithMultipleMessages::class))), $handlersMapping[SecondMessage::class]); + $this->assertEquals(new IteratorArgument([new Reference(PrioritizedHandler::class), new Reference(HandlerWithMultipleMessages::class)]), $handlersMapping[SecondMessage::class]); } public function testGetClassesAndMethodsAndPrioritiesFromTheSubscriber() @@ -183,8 +183,8 @@ class MessengerPassTest extends TestCase $dummyHandlerReference = $handlersMapping[DummyMessage::class]->getValues()[0]; $dummyHandlerDefinition = $container->getDefinition($dummyHandlerReference); $this->assertSame('callable', $dummyHandlerDefinition->getClass()); - $this->assertEquals(array(new Reference(HandlerMappingMethods::class), 'dummyMethod'), $dummyHandlerDefinition->getArgument(0)); - $this->assertSame(array('Closure', 'fromCallable'), $dummyHandlerDefinition->getFactory()); + $this->assertEquals([new Reference(HandlerMappingMethods::class), 'dummyMethod'], $dummyHandlerDefinition->getArgument(0)); + $this->assertSame(['Closure', 'fromCallable'], $dummyHandlerDefinition->getFactory()); $secondHandlerReference = $handlersMapping[SecondMessage::class]->getValues()[1]; $secondHandlerDefinition = $container->getDefinition($secondHandlerReference); @@ -227,11 +227,11 @@ class MessengerPassTest extends TestCase { $container = $this->getContainerBuilder(); $container->register('message_bus', MessageBusInterface::class)->addTag('messenger.bus'); - $container->register(AmqpReceiver::class, AmqpReceiver::class)->addTag('messenger.receiver', array('alias' => 'amqp')); + $container->register(AmqpReceiver::class, AmqpReceiver::class)->addTag('messenger.receiver', ['alias' => 'amqp']); (new MessengerPass())->process($container); - $this->assertEquals(array('amqp' => new Reference(AmqpReceiver::class), AmqpReceiver::class => new Reference(AmqpReceiver::class)), $container->getDefinition('messenger.receiver_locator')->getArgument(0)); + $this->assertEquals(['amqp' => new Reference(AmqpReceiver::class), AmqpReceiver::class => new Reference(AmqpReceiver::class)], $container->getDefinition('messenger.receiver_locator')->getArgument(0)); } public function testItRegistersReceiversWithoutTagName() @@ -242,27 +242,27 @@ class MessengerPassTest extends TestCase (new MessengerPass())->process($container); - $this->assertEquals(array(AmqpReceiver::class => new Reference(AmqpReceiver::class)), $container->getDefinition('messenger.receiver_locator')->getArgument(0)); + $this->assertEquals([AmqpReceiver::class => new Reference(AmqpReceiver::class)], $container->getDefinition('messenger.receiver_locator')->getArgument(0)); } public function testItRegistersMultipleReceiversAndSetsTheReceiverNamesOnTheCommand() { $container = $this->getContainerBuilder(); - $container->register('console.command.messenger_consume_messages', ConsumeMessagesCommand::class)->setArguments(array( + $container->register('console.command.messenger_consume_messages', ConsumeMessagesCommand::class)->setArguments([ null, new Reference('messenger.receiver_locator'), null, null, null, - )); + ]); - $container->register(AmqpReceiver::class, AmqpReceiver::class)->addTag('messenger.receiver', array('alias' => 'amqp')); - $container->register(DummyReceiver::class, DummyReceiver::class)->addTag('messenger.receiver', array('alias' => 'dummy')); + $container->register(AmqpReceiver::class, AmqpReceiver::class)->addTag('messenger.receiver', ['alias' => 'amqp']); + $container->register(DummyReceiver::class, DummyReceiver::class)->addTag('messenger.receiver', ['alias' => 'dummy']); (new MessengerPass())->process($container); - $this->assertSame(array('amqp', 'dummy'), $container->getDefinition('console.command.messenger_consume_messages')->getArgument(3)); - $this->assertSame(array('message_bus'), $container->getDefinition('console.command.messenger_consume_messages')->getArgument(4)); + $this->assertSame(['amqp', 'dummy'], $container->getDefinition('console.command.messenger_consume_messages')->getArgument(3)); + $this->assertSame(['message_bus'], $container->getDefinition('console.command.messenger_consume_messages')->getArgument(4)); } public function testItShouldNotThrowIfGeneratorIsReturnedInsteadOfArray() @@ -279,17 +279,17 @@ class MessengerPassTest extends TestCase $this->assertArrayHasKey(DummyMessage::class, $handlersMapping); $firstReference = $handlersMapping[DummyMessage::class]->getValues()[0]; - $this->assertEquals(array(new Reference(HandlerWithGenerators::class), 'dummyMethod'), $container->getDefinition($firstReference)->getArgument(0)); + $this->assertEquals([new Reference(HandlerWithGenerators::class), 'dummyMethod'], $container->getDefinition($firstReference)->getArgument(0)); $this->assertArrayHasKey(SecondMessage::class, $handlersMapping); $secondReference = $handlersMapping[SecondMessage::class]->getValues()[0]; - $this->assertEquals(array(new Reference(HandlerWithGenerators::class), 'secondMessage'), $container->getDefinition($secondReference)->getArgument(0)); + $this->assertEquals([new Reference(HandlerWithGenerators::class), 'secondMessage'], $container->getDefinition($secondReference)->getArgument(0)); } public function testItRegistersHandlersOnDifferentBuses() { $container = $this->getContainerBuilder($eventsBusId = 'event_bus'); - $container->register($commandsBusId = 'command_bus', MessageBusInterface::class)->addTag('messenger.bus')->setArgument(0, array()); + $container->register($commandsBusId = 'command_bus', MessageBusInterface::class)->addTag('messenger.bus')->setArgument(0, []); $container ->register(HandlerOnSpecificBuses::class, HandlerOnSpecificBuses::class) @@ -300,15 +300,15 @@ class MessengerPassTest extends TestCase $eventsHandlerMapping = $container->getDefinition($eventsBusId.'.messenger.handlers_locator')->getArgument(0); - $this->assertEquals(array(DummyMessage::class), array_keys($eventsHandlerMapping)); + $this->assertEquals([DummyMessage::class], array_keys($eventsHandlerMapping)); $firstReference = $eventsHandlerMapping[DummyMessage::class]->getValues()[0]; - $this->assertEquals(array(new Reference(HandlerOnSpecificBuses::class), 'dummyMethodForEvents'), $container->getDefinition($firstReference)->getArgument(0)); + $this->assertEquals([new Reference(HandlerOnSpecificBuses::class), 'dummyMethodForEvents'], $container->getDefinition($firstReference)->getArgument(0)); $commandsHandlerMapping = $container->getDefinition($commandsBusId.'.messenger.handlers_locator')->getArgument(0); - $this->assertEquals(array(DummyMessage::class), array_keys($commandsHandlerMapping)); + $this->assertEquals([DummyMessage::class], array_keys($commandsHandlerMapping)); $firstReference = $commandsHandlerMapping[DummyMessage::class]->getValues()[0]; - $this->assertEquals(array(new Reference(HandlerOnSpecificBuses::class), 'dummyMethodForCommands'), $container->getDefinition($firstReference)->getArgument(0)); + $this->assertEquals([new Reference(HandlerOnSpecificBuses::class), 'dummyMethodForCommands'], $container->getDefinition($firstReference)->getArgument(0)); } /** @@ -457,8 +457,8 @@ class MessengerPassTest extends TestCase (new MessengerPass())->process($container); $this->assertTrue($container->hasDefinition($debuggedFooBusId = 'debug.traced.'.$fooBusId)); - $this->assertSame(array($fooBusId, null, 0), $container->getDefinition($debuggedFooBusId)->getDecoratedService()); - $this->assertEquals(array(array('registerBus', array($fooBusId, new Reference($debuggedFooBusId)))), $container->getDefinition('data_collector.messenger')->getMethodCalls()); + $this->assertSame([$fooBusId, null, 0], $container->getDefinition($debuggedFooBusId)->getDecoratedService()); + $this->assertEquals([['registerBus', [$fooBusId, new Reference($debuggedFooBusId)]]], $container->getDefinition('data_collector.messenger')->getMethodCalls()); } public function testRegistersMiddlewareFromServices() @@ -468,34 +468,34 @@ class MessengerPassTest extends TestCase $container->register('middleware_with_factory_using_default', UselessMiddleware::class)->addArgument('some_default')->setAbstract(true); $container->register(UselessMiddleware::class, UselessMiddleware::class); - $container->setParameter($middlewareParameter = $fooBusId.'.middleware', array( - array('id' => UselessMiddleware::class), - array('id' => 'middleware_with_factory', 'arguments' => array('index_0' => 'foo', 'bar')), - array('id' => 'middleware_with_factory_using_default'), - )); + $container->setParameter($middlewareParameter = $fooBusId.'.middleware', [ + ['id' => UselessMiddleware::class], + ['id' => 'middleware_with_factory', 'arguments' => ['index_0' => 'foo', 'bar']], + ['id' => 'middleware_with_factory_using_default'], + ]); (new MessengerPass())->process($container); (new ResolveChildDefinitionsPass())->process($container); $this->assertTrue($container->hasDefinition($factoryChildMiddlewareId = $fooBusId.'.middleware.middleware_with_factory')); $this->assertEquals( - array('foo', 'bar'), + ['foo', 'bar'], $container->getDefinition($factoryChildMiddlewareId)->getArguments(), 'parent default argument is overridden, and next ones appended' ); $this->assertTrue($container->hasDefinition($factoryWithDefaultChildMiddlewareId = $fooBusId.'.middleware.middleware_with_factory_using_default')); $this->assertEquals( - array('some_default'), + ['some_default'], $container->getDefinition($factoryWithDefaultChildMiddlewareId)->getArguments(), 'parent default argument is used' ); - $this->assertEquals(array( + $this->assertEquals([ new Reference(UselessMiddleware::class), new Reference($factoryChildMiddlewareId), new Reference($factoryWithDefaultChildMiddlewareId), - ), $container->getDefinition($fooBusId)->getArgument(0)->getValues()); + ], $container->getDefinition($fooBusId)->getArgument(0)->getValues()); $this->assertFalse($container->hasParameter($middlewareParameter)); } @@ -506,9 +506,9 @@ class MessengerPassTest extends TestCase public function testCannotRegistersAnUndefinedMiddleware() { $container = $this->getContainerBuilder($fooBusId = 'messenger.bus.foo'); - $container->setParameter($middlewareParameter = $fooBusId.'.middleware', array( - array('id' => 'not_defined_middleware', 'arguments' => array()), - )); + $container->setParameter($middlewareParameter = $fooBusId.'.middleware', [ + ['id' => 'not_defined_middleware', 'arguments' => []], + ]); (new MessengerPass())->process($container); } @@ -521,9 +521,9 @@ class MessengerPassTest extends TestCase { $container = $this->getContainerBuilder($fooBusId = 'messenger.bus.foo'); $container->register('not_an_abstract_definition', UselessMiddleware::class); - $container->setParameter($middlewareParameter = $fooBusId.'.middleware', array( - array('id' => 'not_an_abstract_definition', 'arguments' => array('foo')), - )); + $container->setParameter($middlewareParameter = $fooBusId.'.middleware', [ + ['id' => 'not_an_abstract_definition', 'arguments' => ['foo']], + ]); (new MessengerPass())->process($container); } @@ -531,41 +531,41 @@ class MessengerPassTest extends TestCase public function testItRegistersTheDebugCommand() { $container = $this->getContainerBuilder($commandBusId = 'command_bus'); - $container->register($queryBusId = 'query_bus', MessageBusInterface::class)->setArgument(0, array())->addTag('messenger.bus'); - $container->register($emptyBus = 'empty_bus', MessageBusInterface::class)->setArgument(0, array())->addTag('messenger.bus'); + $container->register($queryBusId = 'query_bus', MessageBusInterface::class)->setArgument(0, [])->addTag('messenger.bus'); + $container->register($emptyBus = 'empty_bus', MessageBusInterface::class)->setArgument(0, [])->addTag('messenger.bus'); $container->register('messenger.middleware.handle_message', HandleMessageMiddleware::class) ->addArgument(null) ->setAbstract(true) ; - $container->register('console.command.messenger_debug', DebugCommand::class)->addArgument(array()); + $container->register('console.command.messenger_debug', DebugCommand::class)->addArgument([]); - $middlewareHandlers = array(array('id' => 'handle_message')); + $middlewareHandlers = [['id' => 'handle_message']]; $container->setParameter($commandBusId.'.middleware', $middlewareHandlers); $container->setParameter($queryBusId.'.middleware', $middlewareHandlers); - $container->register(DummyCommandHandler::class)->addTag('messenger.message_handler', array('bus' => $commandBusId)); - $container->register(DummyQueryHandler::class)->addTag('messenger.message_handler', array('bus' => $queryBusId)); + $container->register(DummyCommandHandler::class)->addTag('messenger.message_handler', ['bus' => $commandBusId]); + $container->register(DummyQueryHandler::class)->addTag('messenger.message_handler', ['bus' => $queryBusId]); $container->register(MultipleBusesMessageHandler::class) - ->addTag('messenger.message_handler', array('bus' => $commandBusId)) - ->addTag('messenger.message_handler', array('bus' => $queryBusId)) + ->addTag('messenger.message_handler', ['bus' => $commandBusId]) + ->addTag('messenger.message_handler', ['bus' => $queryBusId]) ; (new ResolveClassPass())->process($container); (new MessengerPass())->process($container); - $this->assertEquals(array( - $commandBusId => array( - DummyCommand::class => array(DummyCommandHandler::class), - MultipleBusesMessage::class => array(MultipleBusesMessageHandler::class), - ), - $queryBusId => array( - DummyQuery::class => array(DummyQueryHandler::class), - MultipleBusesMessage::class => array(MultipleBusesMessageHandler::class), - ), - $emptyBus => array(), - ), $container->getDefinition('console.command.messenger_debug')->getArgument(0)); + $this->assertEquals([ + $commandBusId => [ + DummyCommand::class => [DummyCommandHandler::class], + MultipleBusesMessage::class => [MultipleBusesMessageHandler::class], + ], + $queryBusId => [ + DummyQuery::class => [DummyQueryHandler::class], + MultipleBusesMessage::class => [MultipleBusesMessageHandler::class], + ], + $emptyBus => [], + ], $container->getDefinition('console.command.messenger_debug')->getArgument(0)); } private function getContainerBuilder(string $busId = 'message_bus'): ContainerBuilder @@ -573,7 +573,7 @@ class MessengerPassTest extends TestCase $container = new ContainerBuilder(); $container->setParameter('kernel.debug', true); - $container->register($busId, MessageBusInterface::class)->addTag('messenger.bus')->setArgument(0, array()); + $container->register($busId, MessageBusInterface::class)->addTag('messenger.bus')->setArgument(0, []); if ('message_bus' !== $busId) { $container->setAlias('message_bus', $busId); } @@ -633,7 +633,7 @@ class UndefinedMessageHandlerViaSubscriberInterface implements MessageSubscriber { public static function getHandledMessages(): iterable { - return array(UndefinedMessage::class); + return [UndefinedMessage::class]; } public function __invoke() @@ -670,10 +670,10 @@ class HandlerWithMultipleMessages implements MessageSubscriberInterface { public static function getHandledMessages(): iterable { - return array( + return [ DummyMessage::class, SecondMessage::class, - ); + ]; } public function __invoke() @@ -685,7 +685,7 @@ class PrioritizedHandler implements MessageSubscriberInterface { public static function getHandledMessages(): iterable { - yield SecondMessage::class => array('priority' => 10); + yield SecondMessage::class => ['priority' => 10]; } public function __invoke() @@ -698,7 +698,7 @@ class HandlerMappingMethods implements MessageSubscriberInterface public static function getHandledMessages(): iterable { yield DummyMessage::class => 'dummyMethod'; - yield SecondMessage::class => array('method' => 'secondMessage', 'priority' => 20); + yield SecondMessage::class => ['method' => 'secondMessage', 'priority' => 20]; } public function dummyMethod() @@ -714,9 +714,9 @@ class HandlerMappingWithNonExistentMethod implements MessageSubscriberInterface { public static function getHandledMessages(): iterable { - return array( + return [ DummyMessage::class => 'dummyMethod', - ); + ]; } } @@ -724,7 +724,7 @@ class HandleNoMessageHandler implements MessageSubscriberInterface { public static function getHandledMessages(): iterable { - return array(); + return []; } public function __invoke() @@ -753,8 +753,8 @@ class HandlerOnSpecificBuses implements MessageSubscriberInterface { public static function getHandledMessages(): iterable { - yield DummyMessage::class => array('method' => 'dummyMethodForEvents', 'bus' => 'event_bus'); - yield DummyMessage::class => array('method' => 'dummyMethodForCommands', 'bus' => 'command_bus'); + yield DummyMessage::class => ['method' => 'dummyMethodForEvents', 'bus' => 'event_bus']; + yield DummyMessage::class => ['method' => 'dummyMethodForCommands', 'bus' => 'command_bus']; } public function dummyMethodForEvents() @@ -770,7 +770,7 @@ class HandlerOnUndefinedBus implements MessageSubscriberInterface { public static function getHandledMessages(): iterable { - yield DummyMessage::class => array('method' => 'dummyMethodForSomeBus', 'bus' => 'some_undefined_bus'); + yield DummyMessage::class => ['method' => 'dummyMethodForSomeBus', 'bus' => 'some_undefined_bus']; } public function dummyMethodForSomeBus() diff --git a/src/Symfony/Component/Messenger/Tests/EnvelopeTest.php b/src/Symfony/Component/Messenger/Tests/EnvelopeTest.php index 449acd8125..67609d8cd9 100644 --- a/src/Symfony/Component/Messenger/Tests/EnvelopeTest.php +++ b/src/Symfony/Component/Messenger/Tests/EnvelopeTest.php @@ -52,7 +52,7 @@ class EnvelopeTest extends TestCase { $envelope = (new Envelope($dummy = new DummyMessage('dummy'))) ->with($receivedStamp = new ReceivedStamp()) - ->with($validationStamp = new ValidationStamp(array('foo'))) + ->with($validationStamp = new ValidationStamp(['foo'])) ; $stamps = $envelope->all(); diff --git a/src/Symfony/Component/Messenger/Tests/Handler/HandlersLocatorTest.php b/src/Symfony/Component/Messenger/Tests/Handler/HandlersLocatorTest.php index 4b4e84246d..0c258f395b 100644 --- a/src/Symfony/Component/Messenger/Tests/Handler/HandlersLocatorTest.php +++ b/src/Symfony/Component/Messenger/Tests/Handler/HandlersLocatorTest.php @@ -20,11 +20,11 @@ class HandlersLocatorTest extends TestCase { public function testItYieldsProvidedAliasAsKey() { - $handler = $this->createPartialMock(\stdClass::class, array('__invoke')); - $locator = new HandlersLocator(array( - DummyMessage::class => array('dummy' => $handler), - )); + $handler = $this->createPartialMock(\stdClass::class, ['__invoke']); + $locator = new HandlersLocator([ + DummyMessage::class => ['dummy' => $handler], + ]); - $this->assertSame(array('dummy' => $handler), iterator_to_array($locator->getHandlers(new Envelope(new DummyMessage('a'))))); + $this->assertSame(['dummy' => $handler], iterator_to_array($locator->getHandlers(new Envelope(new DummyMessage('a'))))); } } diff --git a/src/Symfony/Component/Messenger/Tests/MessageBusTest.php b/src/Symfony/Component/Messenger/Tests/MessageBusTest.php index 3dedb59c63..1d56d10104 100644 --- a/src/Symfony/Component/Messenger/Tests/MessageBusTest.php +++ b/src/Symfony/Component/Messenger/Tests/MessageBusTest.php @@ -58,10 +58,10 @@ class MessageBusTest extends TestCase ->willReturn($envelope) ; - $bus = new MessageBus(array( + $bus = new MessageBus([ $firstMiddleware, $secondMiddleware, - )); + ]); $bus->dispatch($message); } @@ -95,11 +95,11 @@ class MessageBusTest extends TestCase ->willReturn($envelopeWithAnotherStamp) ; - $bus = new MessageBus(array( + $bus = new MessageBus([ $firstMiddleware, $secondMiddleware, $thirdMiddleware, - )); + ]); $bus->dispatch($envelope); } @@ -107,7 +107,7 @@ class MessageBusTest extends TestCase public function testThatAMiddlewareCanUpdateTheMessageWhileKeepingTheEnvelopeStamps() { $message = new DummyMessage('Hello'); - $envelope = new Envelope($message, ...$stamps = array(new ReceivedStamp())); + $envelope = new Envelope($message, ...$stamps = [new ReceivedStamp()]); $changedMessage = new DummyMessage('Changed'); $expectedEnvelope = new Envelope($changedMessage, ...$stamps); @@ -127,10 +127,10 @@ class MessageBusTest extends TestCase ->willReturn($envelope) ; - $bus = new MessageBus(array( + $bus = new MessageBus([ $firstMiddleware, $secondMiddleware, - )); + ]); $bus->dispatch($envelope); } diff --git a/src/Symfony/Component/Messenger/Tests/Middleware/ActivationMiddlewareTest.php b/src/Symfony/Component/Messenger/Tests/Middleware/ActivationMiddlewareTest.php index dab0a0fb11..5c28c0de7c 100644 --- a/src/Symfony/Component/Messenger/Tests/Middleware/ActivationMiddlewareTest.php +++ b/src/Symfony/Component/Messenger/Tests/Middleware/ActivationMiddlewareTest.php @@ -42,7 +42,7 @@ class ActivationMiddlewareTest extends MiddlewareTestCase $message = new DummyMessage('Hello'); $envelope = new Envelope($message); - $activated = $this->createPartialMock(\stdClass::class, array('__invoke')); + $activated = $this->createPartialMock(\stdClass::class, ['__invoke']); $activated->expects($this->once())->method('__invoke')->with($envelope)->willReturn(true); $stack = $this->getStackMock(false); diff --git a/src/Symfony/Component/Messenger/Tests/Middleware/HandleMessageMiddlewareTest.php b/src/Symfony/Component/Messenger/Tests/Middleware/HandleMessageMiddlewareTest.php index 457428c435..953124fb9b 100644 --- a/src/Symfony/Component/Messenger/Tests/Middleware/HandleMessageMiddlewareTest.php +++ b/src/Symfony/Component/Messenger/Tests/Middleware/HandleMessageMiddlewareTest.php @@ -26,11 +26,11 @@ class HandleMessageMiddlewareTest extends MiddlewareTestCase $message = new DummyMessage('Hey'); $envelope = new Envelope($message); - $handler = $this->createPartialMock(\stdClass::class, array('__invoke')); + $handler = $this->createPartialMock(\stdClass::class, ['__invoke']); - $middleware = new HandleMessageMiddleware(new HandlersLocator(array( - DummyMessage::class => array($handler), - ))); + $middleware = new HandleMessageMiddleware(new HandlersLocator([ + DummyMessage::class => [$handler], + ])); $handler->expects($this->once())->method('__invoke')->with($message); @@ -45,9 +45,9 @@ class HandleMessageMiddlewareTest extends MiddlewareTestCase $message = new DummyMessage('Hey'); $envelope = new Envelope($message); - $middleware = new HandleMessageMiddleware(new HandlersLocator(array( + $middleware = new HandleMessageMiddleware(new HandlersLocator([ DummyMessage::class => $handlers, - ))); + ])); $envelope = $middleware->handle($envelope, $this->getStackMock()); @@ -56,34 +56,34 @@ class HandleMessageMiddlewareTest extends MiddlewareTestCase public function itAddsHandledStampsProvider() { - $first = $this->createPartialMock(\stdClass::class, array('__invoke')); + $first = $this->createPartialMock(\stdClass::class, ['__invoke']); $first->method('__invoke')->willReturn('first result'); $firstClass = \get_class($first); - $second = $this->createPartialMock(\stdClass::class, array('__invoke')); + $second = $this->createPartialMock(\stdClass::class, ['__invoke']); $second->method('__invoke')->willReturn(null); $secondClass = \get_class($second); - yield 'A stamp is added' => array( - array($first), - array(new HandledStamp('first result', $firstClass.'::__invoke')), - ); + yield 'A stamp is added' => [ + [$first], + [new HandledStamp('first result', $firstClass.'::__invoke')], + ]; - yield 'A stamp is added per handler' => array( - array($first, $second), - array( + yield 'A stamp is added per handler' => [ + [$first, $second], + [ new HandledStamp('first result', $firstClass.'::__invoke'), new HandledStamp(null, $secondClass.'::__invoke'), - ), - ); + ], + ]; - yield 'Yielded locator alias is used' => array( - array('first_alias' => $first, $second), - array( + yield 'Yielded locator alias is used' => [ + ['first_alias' => $first, $second], + [ new HandledStamp('first result', $firstClass.'::__invoke', 'first_alias'), new HandledStamp(null, $secondClass.'::__invoke'), - ), - ); + ], + ]; } /** @@ -92,14 +92,14 @@ class HandleMessageMiddlewareTest extends MiddlewareTestCase */ public function testThrowsNoHandlerException() { - $middleware = new HandleMessageMiddleware(new HandlersLocator(array())); + $middleware = new HandleMessageMiddleware(new HandlersLocator([])); $middleware->handle(new Envelope(new DummyMessage('Hey')), new StackMiddleware()); } public function testAllowNoHandlers() { - $middleware = new HandleMessageMiddleware(new HandlersLocator(array()), true); + $middleware = new HandleMessageMiddleware(new HandlersLocator([]), true); $this->assertInstanceOf(Envelope::class, $middleware->handle(new Envelope(new DummyMessage('Hey')), new StackMiddleware())); } diff --git a/src/Symfony/Component/Messenger/Tests/Middleware/SendMessageMiddlewareTest.php b/src/Symfony/Component/Messenger/Tests/Middleware/SendMessageMiddlewareTest.php index 572f237b5d..e74b18245e 100644 --- a/src/Symfony/Component/Messenger/Tests/Middleware/SendMessageMiddlewareTest.php +++ b/src/Symfony/Component/Messenger/Tests/Middleware/SendMessageMiddlewareTest.php @@ -30,7 +30,7 @@ class SendMessageMiddlewareTest extends MiddlewareTestCase $envelope = new Envelope($message); $sender = $this->getMockBuilder(SenderInterface::class)->getMock(); - $middleware = new SendMessageMiddleware(new SendersLocator(array(DummyMessage::class => array($sender)))); + $middleware = new SendMessageMiddleware(new SendersLocator([DummyMessage::class => [$sender]])); $sender->expects($this->once())->method('send')->with($envelope)->willReturn($envelope); @@ -47,7 +47,7 @@ class SendMessageMiddlewareTest extends MiddlewareTestCase $envelope = new Envelope(new ChildDummyMessage('Hey')); $sender = $this->getMockBuilder(SenderInterface::class)->getMock(); - $middleware = new SendMessageMiddleware(new SendersLocator(array(DummyMessage::class => array($sender)))); + $middleware = new SendMessageMiddleware(new SendersLocator([DummyMessage::class => [$sender]])); $sender->expects($this->once())->method('send')->with($envelope)->willReturn($envelope); @@ -60,9 +60,9 @@ class SendMessageMiddlewareTest extends MiddlewareTestCase $envelope = new Envelope($message); $sender = $this->getMockBuilder(SenderInterface::class)->getMock(); - $middleware = new SendMessageMiddleware(new SendersLocator(array('*' => array($sender)), array( + $middleware = new SendMessageMiddleware(new SendersLocator(['*' => [$sender]], [ DummyMessage::class => true, - ))); + ])); $sender->expects($this->once())->method('send')->with($envelope)->willReturn($envelope); @@ -75,9 +75,9 @@ class SendMessageMiddlewareTest extends MiddlewareTestCase $envelope = new Envelope($message); $sender = $this->getMockBuilder(SenderInterface::class)->getMock(); - $middleware = new SendMessageMiddleware(new SendersLocator(array('*' => array($sender)), array( + $middleware = new SendMessageMiddleware(new SendersLocator(['*' => [$sender]], [ DummyMessage::class => true, - ))); + ])); $sender->expects($this->once())->method('send')->with($envelope)->willReturn($envelope); @@ -90,9 +90,9 @@ class SendMessageMiddlewareTest extends MiddlewareTestCase $envelope = new Envelope($message); $sender = $this->getMockBuilder(SenderInterface::class)->getMock(); - $middleware = new SendMessageMiddleware(new SendersLocator(array('*' => array($sender)), array( + $middleware = new SendMessageMiddleware(new SendersLocator(['*' => [$sender]], [ DummyMessageInterface::class => true, - ))); + ])); $sender->expects($this->once())->method('send')->with($envelope)->willReturn($envelope); @@ -105,9 +105,9 @@ class SendMessageMiddlewareTest extends MiddlewareTestCase $envelope = new Envelope($message); $sender = $this->getMockBuilder(SenderInterface::class)->getMock(); - $middleware = new SendMessageMiddleware(new SendersLocator(array('*' => array($sender)), array( + $middleware = new SendMessageMiddleware(new SendersLocator(['*' => [$sender]], [ '*' => true, - ))); + ])); $sender->expects($this->once())->method('send')->with($envelope)->willReturn($envelope); @@ -119,7 +119,7 @@ class SendMessageMiddlewareTest extends MiddlewareTestCase $message = new DummyMessage('Hey'); $envelope = new Envelope($message); - $middleware = new SendMessageMiddleware(new SendersLocator(array())); + $middleware = new SendMessageMiddleware(new SendersLocator([])); $middleware->handle($envelope, $this->getStackMock()); } @@ -130,7 +130,7 @@ class SendMessageMiddlewareTest extends MiddlewareTestCase $sender = $this->getMockBuilder(SenderInterface::class)->getMock(); - $middleware = new SendMessageMiddleware(new SendersLocator(array('*' => array($sender)))); + $middleware = new SendMessageMiddleware(new SendersLocator(['*' => [$sender]])); $sender->expects($this->never())->method('send'); diff --git a/src/Symfony/Component/Messenger/Tests/Middleware/TraceableMiddlewareTest.php b/src/Symfony/Component/Messenger/Tests/Middleware/TraceableMiddlewareTest.php index c13f1c2262..35a8ad34f5 100644 --- a/src/Symfony/Component/Messenger/Tests/Middleware/TraceableMiddlewareTest.php +++ b/src/Symfony/Component/Messenger/Tests/Middleware/TraceableMiddlewareTest.php @@ -44,21 +44,21 @@ class TraceableMiddlewareTest extends MiddlewareTestCase $stopwatch->expects($this->exactly(2)) ->method('start') ->withConsecutive( - array($this->matches('"%sMiddlewareInterface%s" on "command_bus"'), 'messenger.middleware'), - array('Tail on "command_bus"', 'messenger.middleware') + [$this->matches('"%sMiddlewareInterface%s" on "command_bus"'), 'messenger.middleware'], + ['Tail on "command_bus"', 'messenger.middleware'] ) ; $stopwatch->expects($this->exactly(2)) ->method('stop') ->withConsecutive( - array($this->matches('"%sMiddlewareInterface%s" on "command_bus"')), - array('Tail on "command_bus"') + [$this->matches('"%sMiddlewareInterface%s" on "command_bus"')], + ['Tail on "command_bus"'] ) ; $traced = new TraceableMiddleware($stopwatch, $busId); - $traced->handle($envelope, new StackMiddleware(new \ArrayIterator(array(null, $middleware)))); + $traced->handle($envelope, new StackMiddleware(new \ArrayIterator([null, $middleware]))); } /** @@ -88,6 +88,6 @@ class TraceableMiddlewareTest extends MiddlewareTestCase ; $traced = new TraceableMiddleware($stopwatch, $busId); - $traced->handle(new Envelope(new DummyMessage('Hello')), new StackMiddleware(new \ArrayIterator(array(null, $middleware)))); + $traced->handle(new Envelope(new DummyMessage('Hello')), new StackMiddleware(new \ArrayIterator([null, $middleware]))); } } diff --git a/src/Symfony/Component/Messenger/Tests/Middleware/ValidationMiddlewareTest.php b/src/Symfony/Component/Messenger/Tests/Middleware/ValidationMiddlewareTest.php index c3c2fff3d1..510396f0a3 100644 --- a/src/Symfony/Component/Messenger/Tests/Middleware/ValidationMiddlewareTest.php +++ b/src/Symfony/Component/Messenger/Tests/Middleware/ValidationMiddlewareTest.php @@ -40,7 +40,7 @@ class ValidationMiddlewareTest extends MiddlewareTestCase public function testValidateWithStampAndNextMiddleware() { $message = new DummyMessage('Hey'); - $envelope = (new Envelope($message))->with(new ValidationStamp($groups = array('Default', 'Extra'))); + $envelope = (new Envelope($message))->with(new ValidationStamp($groups = ['Default', 'Extra'])); $validator = $this->createMock(ValidatorInterface::class); $validator ->expects($this->once()) diff --git a/src/Symfony/Component/Messenger/Tests/Stamp/HandledStampTest.php b/src/Symfony/Component/Messenger/Tests/Stamp/HandledStampTest.php index 72584c6740..2bdc7f4050 100644 --- a/src/Symfony/Component/Messenger/Tests/Stamp/HandledStampTest.php +++ b/src/Symfony/Component/Messenger/Tests/Stamp/HandledStampTest.php @@ -46,21 +46,21 @@ class HandledStampTest extends TestCase public function provideCallables() { - yield array(function () {}, 'Closure'); - yield array('var_dump', 'var_dump'); - yield array(new DummyCommandHandler(), DummyCommandHandler::class.'::__invoke'); - yield array( - array(new DummyCommandHandlerWithSpecificMethod(), 'handle'), + yield [function () {}, 'Closure']; + yield ['var_dump', 'var_dump']; + yield [new DummyCommandHandler(), DummyCommandHandler::class.'::__invoke']; + yield [ + [new DummyCommandHandlerWithSpecificMethod(), 'handle'], DummyCommandHandlerWithSpecificMethod::class.'::handle', - ); - yield array(\Closure::fromCallable(function () {}), 'Closure'); - yield array(\Closure::fromCallable(new DummyCommandHandler()), DummyCommandHandler::class.'::__invoke'); - yield array(\Closure::bind(\Closure::fromCallable(function () {}), new \stdClass()), 'Closure'); - yield array(new class() { + ]; + yield [\Closure::fromCallable(function () {}), 'Closure']; + yield [\Closure::fromCallable(new DummyCommandHandler()), DummyCommandHandler::class.'::__invoke']; + yield [\Closure::bind(\Closure::fromCallable(function () {}), new \stdClass()), 'Closure']; + yield [new class() { public function __invoke() { } - }, 'class@anonymous%sHandledStampTest.php%s::__invoke'); + }, 'class@anonymous%sHandledStampTest.php%s::__invoke']; } } diff --git a/src/Symfony/Component/Messenger/Tests/Stamp/SerializerStampTest.php b/src/Symfony/Component/Messenger/Tests/Stamp/SerializerStampTest.php index 1800d92123..6a65787803 100644 --- a/src/Symfony/Component/Messenger/Tests/Stamp/SerializerStampTest.php +++ b/src/Symfony/Component/Messenger/Tests/Stamp/SerializerStampTest.php @@ -22,7 +22,7 @@ class SerializerStampTest extends TestCase { public function testSerializable() { - $stamp = new SerializerStamp(array(ObjectNormalizer::GROUPS => array('Default', 'Extra'))); + $stamp = new SerializerStamp([ObjectNormalizer::GROUPS => ['Default', 'Extra']]); $this->assertEquals($stamp, unserialize(serialize($stamp))); } diff --git a/src/Symfony/Component/Messenger/Tests/Stamp/ValidationStampTest.php b/src/Symfony/Component/Messenger/Tests/Stamp/ValidationStampTest.php index cabcf526a3..e5af080acd 100644 --- a/src/Symfony/Component/Messenger/Tests/Stamp/ValidationStampTest.php +++ b/src/Symfony/Component/Messenger/Tests/Stamp/ValidationStampTest.php @@ -22,16 +22,16 @@ class ValidationStampTest extends TestCase { public function testStamp() { - $stamp = new ValidationStamp($groups = array('Default', 'Extra')); + $stamp = new ValidationStamp($groups = ['Default', 'Extra']); $this->assertSame($groups, $stamp->getGroups()); - $stamp = new ValidationStamp($groups = new GroupSequence(array('Default', 'Then'))); + $stamp = new ValidationStamp($groups = new GroupSequence(['Default', 'Then'])); $this->assertSame($groups, $stamp->getGroups()); } public function testSerializable() { - $this->assertEquals($stamp = new ValidationStamp(array('Default', 'Extra')), unserialize(serialize($stamp))); - $this->assertEquals($stamp = new ValidationStamp(new GroupSequence(array('Default', 'Then'))), unserialize(serialize($stamp))); + $this->assertEquals($stamp = new ValidationStamp(['Default', 'Extra']), unserialize(serialize($stamp))); + $this->assertEquals($stamp = new ValidationStamp(new GroupSequence(['Default', 'Then'])), unserialize(serialize($stamp))); } } diff --git a/src/Symfony/Component/Messenger/Tests/TraceableMessageBusTest.php b/src/Symfony/Component/Messenger/Tests/TraceableMessageBusTest.php index f4db01d855..23e47d28d0 100644 --- a/src/Symfony/Component/Messenger/Tests/TraceableMessageBusTest.php +++ b/src/Symfony/Component/Messenger/Tests/TraceableMessageBusTest.php @@ -31,15 +31,15 @@ class TraceableMessageBusTest extends TestCase $line = __LINE__ + 1; $traceableBus->dispatch($message); $this->assertCount(1, $tracedMessages = $traceableBus->getDispatchedMessages()); - $this->assertArraySubset(array( + $this->assertArraySubset([ 'message' => $message, - 'stamps' => array(), - 'caller' => array( + 'stamps' => [], + 'caller' => [ 'name' => 'TraceableMessageBusTest.php', 'file' => __FILE__, 'line' => $line, - ), - ), $tracedMessages[0], true); + ], + ], $tracedMessages[0], true); } public function testItTracesDispatchWithEnvelope() @@ -54,15 +54,15 @@ class TraceableMessageBusTest extends TestCase $line = __LINE__ + 1; $traceableBus->dispatch($envelope); $this->assertCount(1, $tracedMessages = $traceableBus->getDispatchedMessages()); - $this->assertArraySubset(array( + $this->assertArraySubset([ 'message' => $message, - 'stamps' => array(array($stamp)), - 'caller' => array( + 'stamps' => [[$stamp]], + 'caller' => [ 'name' => 'TraceableMessageBusTest.php', 'file' => __FILE__, 'line' => $line, - ), - ), $tracedMessages[0], true); + ], + ], $tracedMessages[0], true); } public function testItTracesExceptions() @@ -82,15 +82,15 @@ class TraceableMessageBusTest extends TestCase } $this->assertCount(1, $tracedMessages = $traceableBus->getDispatchedMessages()); - $this->assertArraySubset(array( + $this->assertArraySubset([ 'message' => $message, 'exception' => $exception, - 'stamps' => array(), - 'caller' => array( + 'stamps' => [], + 'caller' => [ 'name' => 'TraceableMessageBusTest.php', 'file' => __FILE__, 'line' => $line, - ), - ), $tracedMessages[0], true); + ], + ], $tracedMessages[0], true); } } diff --git a/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/AmqpSenderTest.php b/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/AmqpSenderTest.php index 398f009292..caef14c9e2 100644 --- a/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/AmqpSenderTest.php +++ b/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/AmqpSenderTest.php @@ -26,7 +26,7 @@ class AmqpSenderTest extends TestCase public function testItSendsTheEncodedMessage() { $envelope = new Envelope(new DummyMessage('Oy')); - $encoded = array('body' => '...', 'headers' => array('type' => DummyMessage::class)); + $encoded = ['body' => '...', 'headers' => ['type' => DummyMessage::class]]; $serializer = $this->getMockBuilder(SerializerInterface::class)->getMock(); $serializer->method('encode')->with($envelope)->willReturnOnConsecutiveCalls($encoded); diff --git a/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/AmqpTransportFactoryTest.php b/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/AmqpTransportFactoryTest.php index c36cc3eafd..8dc555fa89 100644 --- a/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/AmqpTransportFactoryTest.php +++ b/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/AmqpTransportFactoryTest.php @@ -26,9 +26,9 @@ class AmqpTransportFactoryTest extends TestCase true ); - $this->assertTrue($factory->supports('amqp://localhost', array())); - $this->assertFalse($factory->supports('sqs://localhost', array())); - $this->assertFalse($factory->supports('invalid-dsn', array())); + $this->assertTrue($factory->supports('amqp://localhost', [])); + $this->assertFalse($factory->supports('sqs://localhost', [])); + $this->assertFalse($factory->supports('invalid-dsn', [])); } public function testItCreatesTheTransport() @@ -38,8 +38,8 @@ class AmqpTransportFactoryTest extends TestCase true ); - $expectedTransport = new AmqpTransport(Connection::fromDsn('amqp://localhost', array('foo' => 'bar'), true), $serializer); + $expectedTransport = new AmqpTransport(Connection::fromDsn('amqp://localhost', ['foo' => 'bar'], true), $serializer); - $this->assertEquals($expectedTransport, $factory->createTransport('amqp://localhost', array('foo' => 'bar'))); + $this->assertEquals($expectedTransport, $factory->createTransport('amqp://localhost', ['foo' => 'bar'])); } } diff --git a/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/AmqpTransportTest.php b/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/AmqpTransportTest.php index 589a764c1a..c343c29226 100644 --- a/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/AmqpTransportTest.php +++ b/src/Symfony/Component/Messenger/Tests/Transport/AmqpExt/AmqpTransportTest.php @@ -42,9 +42,9 @@ class AmqpTransportTest extends TestCase $amqpEnvelope = $this->getMockBuilder(\AMQPEnvelope::class)->getMock(); $amqpEnvelope->method('getBody')->willReturn('body'); - $amqpEnvelope->method('getHeaders')->willReturn(array('my' => 'header')); + $amqpEnvelope->method('getHeaders')->willReturn(['my' => 'header']); - $serializer->method('decode')->with(array('body' => 'body', 'headers' => array('my' => 'header')))->willReturn(new Envelope($decodedMessage)); + $serializer->method('decode')->with(['body' => 'body', 'headers' => ['my' => 'header']])->willReturn(new Envelope($decodedMessage)); $connection->method('get')->willReturn($amqpEnvelope); $transport->receive(function (Envelope $envelope) use ($transport, $decodedMessage) { diff --git a/src/Symfony/Component/Messenger/Tests/Transport/Sender/SendersLocatorTest.php b/src/Symfony/Component/Messenger/Tests/Transport/Sender/SendersLocatorTest.php index e693cee53a..1de28332b3 100644 --- a/src/Symfony/Component/Messenger/Tests/Transport/Sender/SendersLocatorTest.php +++ b/src/Symfony/Component/Messenger/Tests/Transport/Sender/SendersLocatorTest.php @@ -23,21 +23,21 @@ class SendersLocatorTest extends TestCase public function testItReturnsTheSenderBasedOnTheMessageClass() { $sender = $this->getMockBuilder(SenderInterface::class)->getMock(); - $locator = new SendersLocator(array( - DummyMessage::class => array($sender), - )); + $locator = new SendersLocator([ + DummyMessage::class => [$sender], + ]); - $this->assertSame(array($sender), iterator_to_array($locator->getSenders(new Envelope(new DummyMessage('a'))))); - $this->assertSame(array(), iterator_to_array($locator->getSenders(new Envelope(new SecondMessage())))); + $this->assertSame([$sender], iterator_to_array($locator->getSenders(new Envelope(new DummyMessage('a'))))); + $this->assertSame([], iterator_to_array($locator->getSenders(new Envelope(new SecondMessage())))); } public function testItYieldsProvidedSenderAliasAsKey() { $sender = $this->getMockBuilder(SenderInterface::class)->getMock(); - $locator = new SendersLocator(array( - DummyMessage::class => array('dummy' => $sender), - )); + $locator = new SendersLocator([ + DummyMessage::class => ['dummy' => $sender], + ]); - $this->assertSame(array('dummy' => $sender), iterator_to_array($locator->getSenders(new Envelope(new DummyMessage('a'))))); + $this->assertSame(['dummy' => $sender], iterator_to_array($locator->getSenders(new Envelope(new DummyMessage('a'))))); } } diff --git a/src/Symfony/Component/Messenger/Tests/Transport/Serialization/SerializerTest.php b/src/Symfony/Component/Messenger/Tests/Transport/Serialization/SerializerTest.php index a38d8b4842..d68103f7ca 100644 --- a/src/Symfony/Component/Messenger/Tests/Transport/Serialization/SerializerTest.php +++ b/src/Symfony/Component/Messenger/Tests/Transport/Serialization/SerializerTest.php @@ -36,8 +36,8 @@ class SerializerTest extends TestCase $serializer = new Serializer(); $envelope = (new Envelope(new DummyMessage('Hello'))) - ->with(new SerializerStamp(array(ObjectNormalizer::GROUPS => array('foo')))) - ->with(new ValidationStamp(array('foo', 'bar'))) + ->with(new SerializerStamp([ObjectNormalizer::GROUPS => ['foo']])) + ->with(new ValidationStamp(['foo', 'bar'])) ; $this->assertEquals($envelope, $serializer->decode($serializer->encode($envelope))); @@ -60,10 +60,10 @@ class SerializerTest extends TestCase $message = new DummyMessage('Foo'); $serializer = $this->getMockBuilder(SerializerComponent\SerializerInterface::class)->getMock(); - $serializer->expects($this->once())->method('serialize')->with($message, 'csv', array('foo' => 'bar'))->willReturn('Yay'); - $serializer->expects($this->once())->method('deserialize')->with('Yay', DummyMessage::class, 'csv', array('foo' => 'bar'))->willReturn($message); + $serializer->expects($this->once())->method('serialize')->with($message, 'csv', ['foo' => 'bar'])->willReturn('Yay'); + $serializer->expects($this->once())->method('deserialize')->with('Yay', DummyMessage::class, 'csv', ['foo' => 'bar'])->willReturn($message); - $encoder = new Serializer($serializer, 'csv', array('foo' => 'bar')); + $encoder = new Serializer($serializer, 'csv', ['foo' => 'bar']); $encoded = $encoder->encode(new Envelope($message)); $decoded = $encoder->decode($encoded); @@ -77,8 +77,8 @@ class SerializerTest extends TestCase $serializer = new Serializer(); $envelope = (new Envelope(new DummyMessage('Hello'))) - ->with($serializerStamp = new SerializerStamp(array(ObjectNormalizer::GROUPS => array('foo')))) - ->with($validationStamp = new ValidationStamp(array('foo', 'bar'))) + ->with($serializerStamp = new SerializerStamp([ObjectNormalizer::GROUPS => ['foo']])) + ->with($validationStamp = new ValidationStamp(['foo', 'bar'])) ; $encoded = $serializer->encode($envelope); diff --git a/src/Symfony/Component/Messenger/TraceableMessageBus.php b/src/Symfony/Component/Messenger/TraceableMessageBus.php index fdc6ae08f7..1d910d4540 100644 --- a/src/Symfony/Component/Messenger/TraceableMessageBus.php +++ b/src/Symfony/Component/Messenger/TraceableMessageBus.php @@ -19,7 +19,7 @@ namespace Symfony\Component\Messenger; class TraceableMessageBus implements MessageBusInterface { private $decoratedBus; - private $dispatchedMessages = array(); + private $dispatchedMessages = []; public function __construct(MessageBusInterface $decoratedBus) { @@ -32,12 +32,12 @@ class TraceableMessageBus implements MessageBusInterface public function dispatch($message): Envelope { $envelope = $message instanceof Envelope ? $message : new Envelope($message); - $context = array( + $context = [ 'stamps' => array_values($envelope->all()), 'message' => $envelope->getMessage(), 'caller' => $this->getCaller(), 'callTime' => microtime(true), - ); + ]; try { return $this->decoratedBus->dispatch($message); @@ -57,7 +57,7 @@ class TraceableMessageBus implements MessageBusInterface public function reset() { - $this->dispatchedMessages = array(); + $this->dispatchedMessages = []; } private function getCaller(): array diff --git a/src/Symfony/Component/Messenger/Transport/AmqpExt/AmqpReceiver.php b/src/Symfony/Component/Messenger/Transport/AmqpExt/AmqpReceiver.php index ad02b80d3b..7ed1fae405 100644 --- a/src/Symfony/Component/Messenger/Transport/AmqpExt/AmqpReceiver.php +++ b/src/Symfony/Component/Messenger/Transport/AmqpExt/AmqpReceiver.php @@ -54,10 +54,10 @@ class AmqpReceiver implements ReceiverInterface } try { - $handler($this->serializer->decode(array( + $handler($this->serializer->decode([ 'body' => $AMQPEnvelope->getBody(), 'headers' => $AMQPEnvelope->getHeaders(), - ))); + ])); $this->connection->ack($AMQPEnvelope); } catch (RejectMessageExceptionInterface $e) { diff --git a/src/Symfony/Component/Messenger/Transport/Sender/SendersLocator.php b/src/Symfony/Component/Messenger/Transport/Sender/SendersLocator.php index 47f64a6d14..60dde8fb53 100644 --- a/src/Symfony/Component/Messenger/Transport/Sender/SendersLocator.php +++ b/src/Symfony/Component/Messenger/Transport/Sender/SendersLocator.php @@ -30,7 +30,7 @@ class SendersLocator implements SendersLocatorInterface * @param SenderInterface[][] $senders * @param bool[] $sendAndHandle */ - public function __construct(array $senders, array $sendAndHandle = array()) + public function __construct(array $senders, array $sendAndHandle = []) { $this->senders = $senders; $this->sendAndHandle = $sendAndHandle; @@ -43,10 +43,10 @@ class SendersLocator implements SendersLocatorInterface { $handle = false; $sender = null; - $seen = array(); + $seen = []; foreach (HandlersLocator::listTypes($envelope) as $type) { - foreach ($this->senders[$type] ?? array() as $alias => $sender) { + foreach ($this->senders[$type] ?? [] as $alias => $sender) { if (!\in_array($sender, $seen, true)) { yield $alias => $seen[] = $sender; } diff --git a/src/Symfony/Component/Messenger/Transport/Serialization/Serializer.php b/src/Symfony/Component/Messenger/Transport/Serialization/Serializer.php index 22c01debea..3f0979bcef 100644 --- a/src/Symfony/Component/Messenger/Transport/Serialization/Serializer.php +++ b/src/Symfony/Component/Messenger/Transport/Serialization/Serializer.php @@ -35,7 +35,7 @@ class Serializer implements SerializerInterface private $format; private $context; - public function __construct(SymfonySerializerInterface $serializer = null, string $format = 'json', array $context = array()) + public function __construct(SymfonySerializerInterface $serializer = null, string $format = 'json', array $context = []) { $this->serializer = $serializer ?? self::create()->serializer; $this->format = $format; @@ -48,8 +48,8 @@ class Serializer implements SerializerInterface throw new LogicException(sprintf('The default Messenger Serializer requires Symfony\'s Serializer component. Try running "composer require symfony/serializer".')); } - $encoders = array(new XmlEncoder(), new JsonEncoder()); - $normalizers = array(new ArrayDenormalizer(), new ObjectNormalizer()); + $encoders = [new XmlEncoder(), new JsonEncoder()]; + $normalizers = [new ArrayDenormalizer(), new ObjectNormalizer()]; $serializer = new SymfonySerializer($normalizers, $encoders); return new self($serializer); @@ -91,17 +91,17 @@ class Serializer implements SerializerInterface $context = $serializerStamp->getContext() + $context; } - $headers = array('type' => \get_class($envelope->getMessage())) + $this->encodeStamps($envelope); + $headers = ['type' => \get_class($envelope->getMessage())] + $this->encodeStamps($envelope); - return array( + return [ 'body' => $this->serializer->serialize($envelope->getMessage(), $this->format, $context), 'headers' => $headers, - ); + ]; } private function decodeStamps(array $encodedEnvelope): array { - $stamps = array(); + $stamps = []; foreach ($encodedEnvelope['headers'] as $name => $value) { if (0 !== strpos($name, self::STAMP_HEADER_PREFIX)) { continue; @@ -119,10 +119,10 @@ class Serializer implements SerializerInterface private function encodeStamps(Envelope $envelope): array { if (!$allStamps = $envelope->all()) { - return array(); + return []; } - $headers = array(); + $headers = []; foreach ($allStamps as $class => $stamps) { $headers[self::STAMP_HEADER_PREFIX.$class] = $this->serializer->serialize($stamps, $this->format, $this->context); } diff --git a/src/Symfony/Component/OptionsResolver/OptionsResolver.php b/src/Symfony/Component/OptionsResolver/OptionsResolver.php index 5d238f509e..c0823e3f38 100644 --- a/src/Symfony/Component/OptionsResolver/OptionsResolver.php +++ b/src/Symfony/Component/OptionsResolver/OptionsResolver.php @@ -30,68 +30,68 @@ class OptionsResolver implements Options /** * The names of all defined options. */ - private $defined = array(); + private $defined = []; /** * The default option values. */ - private $defaults = array(); + private $defaults = []; /** * A list of closure for nested options. * * @var \Closure[][] */ - private $nested = array(); + private $nested = []; /** * The names of required options. */ - private $required = array(); + private $required = []; /** * The resolved option values. */ - private $resolved = array(); + private $resolved = []; /** * A list of normalizer closures. * * @var \Closure[] */ - private $normalizers = array(); + private $normalizers = []; /** * A list of accepted values for each option. */ - private $allowedValues = array(); + private $allowedValues = []; /** * A list of accepted types for each option. */ - private $allowedTypes = array(); + private $allowedTypes = []; /** * A list of closures for evaluating lazy options. */ - private $lazy = array(); + private $lazy = []; /** * A list of lazy options whose closure is currently being called. * * This list helps detecting circular dependencies between lazy options. */ - private $calling = array(); + private $calling = []; /** * A list of deprecated options. */ - private $deprecated = array(); + private $deprecated = []; /** * The list of options provided by the user. */ - private $given = array(); + private $given = []; /** * Whether the instance is locked for reading. @@ -103,11 +103,11 @@ class OptionsResolver implements Options */ private $locked = false; - private static $typeAliases = array( + private static $typeAliases = [ 'boolean' => 'bool', 'integer' => 'int', 'double' => 'float', - ); + ]; /** * Sets the default value of a given option. @@ -186,7 +186,7 @@ class OptionsResolver implements Options // Ignore previous lazy options if the closure has no second parameter if (!isset($this->lazy[$option]) || !isset($params[1])) { - $this->lazy[$option] = array(); + $this->lazy[$option] = []; } // Store closure for later evaluation @@ -202,7 +202,7 @@ class OptionsResolver implements Options if (isset($params[0]) && null !== ($class = $params[0]->getClass()) && self::class === $class->name && (!isset($params[1]) || (null !== ($class = $params[1]->getClass()) && Options::class === $class->name))) { // Store closure for later evaluation $this->nested[$option][] = $value; - $this->defaults[$option] = array(); + $this->defaults[$option] = []; $this->defined[$option] = true; // Make sure the option is processed and is not lazy anymore @@ -523,7 +523,7 @@ class OptionsResolver implements Options throw new UndefinedOptionsException(sprintf('The option "%s" does not exist. Defined options are: "%s".', $option, implode('", "', array_keys($this->defined)))); } - $this->allowedValues[$option] = \is_array($allowedValues) ? $allowedValues : array($allowedValues); + $this->allowedValues[$option] = \is_array($allowedValues) ? $allowedValues : [$allowedValues]; // Make sure the option is processed unset($this->resolved[$option]); @@ -565,7 +565,7 @@ class OptionsResolver implements Options } if (!\is_array($allowedValues)) { - $allowedValues = array($allowedValues); + $allowedValues = [$allowedValues]; } if (!isset($this->allowedValues[$option])) { @@ -690,16 +690,16 @@ class OptionsResolver implements Options throw new AccessException('Options cannot be cleared from a lazy option or normalizer.'); } - $this->defined = array(); - $this->defaults = array(); - $this->nested = array(); - $this->required = array(); - $this->resolved = array(); - $this->lazy = array(); - $this->normalizers = array(); - $this->allowedTypes = array(); - $this->allowedValues = array(); - $this->deprecated = array(); + $this->defined = []; + $this->defaults = []; + $this->nested = []; + $this->required = []; + $this->resolved = []; + $this->lazy = []; + $this->normalizers = []; + $this->allowedTypes = []; + $this->allowedValues = []; + $this->deprecated = []; return $this; } @@ -728,7 +728,7 @@ class OptionsResolver implements Options * @throws NoSuchOptionException If a lazy option reads an unavailable option * @throws AccessException If called from a lazy option or normalizer */ - public function resolve(array $options = array()) + public function resolve(array $options = []) { if ($this->locked) { throw new AccessException('Options cannot be resolved from a lazy option or normalizer.'); @@ -802,7 +802,7 @@ class OptionsResolver implements Options // Shortcut for resolved options if (isset($this->resolved[$option]) || array_key_exists($option, $this->resolved)) { if ($triggerDeprecation && isset($this->deprecated[$option]) && (isset($this->given[$option]) || $this->calling) && \is_string($this->deprecated[$option])) { - @trigger_error(strtr($this->deprecated[$option], array('%name%' => $option)), E_USER_DEPRECATED); + @trigger_error(strtr($this->deprecated[$option], ['%name%' => $option]), E_USER_DEPRECATED); } return $this->resolved[$option]; @@ -869,7 +869,7 @@ class OptionsResolver implements Options // Validate the type of the resolved option if (isset($this->allowedTypes[$option])) { $valid = false; - $invalidTypes = array(); + $invalidTypes = []; foreach ($this->allowedTypes[$option] as $type) { $type = self::$typeAliases[$type] ?? $type; @@ -893,7 +893,7 @@ class OptionsResolver implements Options // Validate the value of the resolved option if (isset($this->allowedValues[$option])) { $success = false; - $printableAllowedValues = array(); + $printableAllowedValues = []; foreach ($this->allowedValues[$option] as $allowedValue) { if ($allowedValue instanceof \Closure) { @@ -954,7 +954,7 @@ class OptionsResolver implements Options } if ('' !== $deprecationMessage) { - @trigger_error(strtr($deprecationMessage, array('%name%' => $option)), E_USER_DEPRECATED); + @trigger_error(strtr($deprecationMessage, ['%name%' => $option]), E_USER_DEPRECATED); } } diff --git a/src/Symfony/Component/OptionsResolver/Tests/OptionsResolverTest.php b/src/Symfony/Component/OptionsResolver/Tests/OptionsResolverTest.php index 9de41871e9..886a88ebfa 100644 --- a/src/Symfony/Component/OptionsResolver/Tests/OptionsResolverTest.php +++ b/src/Symfony/Component/OptionsResolver/Tests/OptionsResolverTest.php @@ -496,7 +496,7 @@ class OptionsResolverTest extends TestCase return false; }) ; - $this->resolver->resolve(array('foo' => null)); + $this->resolver->resolve(['foo' => null]); } /** @@ -506,7 +506,7 @@ class OptionsResolverTest extends TestCase public function testFailsIfCyclicDependencyBetweenDeprecation() { $this->resolver - ->setDefined(array('foo', 'bar')) + ->setDefined(['foo', 'bar']) ->setDeprecated('foo', function (Options $options, $value) { $options['bar']; }) @@ -514,7 +514,7 @@ class OptionsResolverTest extends TestCase $options['foo']; }) ; - $this->resolver->resolve(array('foo' => null, 'bar' => null)); + $this->resolver->resolve(['foo' => null, 'bar' => null]); } public function testIsDeprecated() @@ -564,22 +564,22 @@ class OptionsResolverTest extends TestCase public function provideDeprecationData() { - yield 'It deprecates an option with default message' => array( + yield 'It deprecates an option with default message' => [ function (OptionsResolver $resolver) { $resolver - ->setDefined(array('foo', 'bar')) + ->setDefined(['foo', 'bar']) ->setDeprecated('foo') ; }, - array('foo' => 'baz'), - array( + ['foo' => 'baz'], + [ 'type' => E_USER_DEPRECATED, 'message' => 'The option "foo" is deprecated.', - ), + ], 1, - ); + ]; - yield 'It deprecates an option with custom message' => array( + yield 'It deprecates an option with custom message' => [ function (OptionsResolver $resolver) { $resolver ->setDefined('foo') @@ -589,15 +589,15 @@ class OptionsResolverTest extends TestCase ->setDeprecated('foo', 'The option "foo" is deprecated, use "bar" option instead.') ; }, - array('foo' => 'baz'), - array( + ['foo' => 'baz'], + [ 'type' => E_USER_DEPRECATED, 'message' => 'The option "foo" is deprecated, use "bar" option instead.', - ), + ], 2, - ); + ]; - yield 'It deprecates an option evaluated in another definition' => array( + yield 'It deprecates an option evaluated in another definition' => [ function (OptionsResolver $resolver) { // defined by superclass $resolver @@ -609,19 +609,19 @@ class OptionsResolverTest extends TestCase return $options['foo']; // It triggers a deprecation }); }, - array(), - array( + [], + [ 'type' => E_USER_DEPRECATED, 'message' => 'The option "foo" is deprecated.', - ), + ], 1, - ); + ]; - yield 'It deprecates allowed type and value' => array( + yield 'It deprecates allowed type and value' => [ function (OptionsResolver $resolver) { $resolver ->setDefault('foo', null) - ->setAllowedTypes('foo', array('null', 'string', \stdClass::class)) + ->setAllowedTypes('foo', ['null', 'string', \stdClass::class]) ->setDeprecated('foo', function (Options $options, $value) { if ($value instanceof \stdClass) { return sprintf('Passing an instance of "%s" to option "foo" is deprecated, pass its FQCN instead.', \stdClass::class); @@ -631,19 +631,19 @@ class OptionsResolverTest extends TestCase }) ; }, - array('foo' => new \stdClass()), - array( + ['foo' => new \stdClass()], + [ 'type' => E_USER_DEPRECATED, 'message' => 'Passing an instance of "stdClass" to option "foo" is deprecated, pass its FQCN instead.', - ), + ], 1, - ); + ]; - yield 'It triggers a deprecation based on the value only if option is provided by the user' => array( + yield 'It triggers a deprecation based on the value only if option is provided by the user' => [ function (OptionsResolver $resolver) { $resolver ->setDefined('foo') - ->setAllowedTypes('foo', array('null', 'bool')) + ->setAllowedTypes('foo', ['null', 'bool']) ->setDeprecated('foo', function (Options $options, $value) { if (!\is_bool($value)) { return 'Passing a value different than true or false is deprecated.'; @@ -652,7 +652,7 @@ class OptionsResolverTest extends TestCase return ''; }) ->setDefault('baz', null) - ->setAllowedTypes('baz', array('null', 'int')) + ->setAllowedTypes('baz', ['null', 'int']) ->setDeprecated('baz', function (Options $options, $value) { if (!\is_int($value)) { return 'Not passing an integer is deprecated.'; @@ -667,15 +667,15 @@ class OptionsResolverTest extends TestCase }) ; }, - array('foo' => null), // It triggers a deprecation - array( + ['foo' => null], // It triggers a deprecation + [ 'type' => E_USER_DEPRECATED, 'message' => 'Passing a value different than true or false is deprecated.', - ), + ], 1, - ); + ]; - yield 'It ignores a deprecation if closure returns an empty string' => array( + yield 'It ignores a deprecation if closure returns an empty string' => [ function (OptionsResolver $resolver) { $resolver ->setDefault('foo', null) @@ -684,12 +684,12 @@ class OptionsResolverTest extends TestCase }) ; }, - array('foo' => Bar::class), + ['foo' => Bar::class], null, 0, - ); + ]; - yield 'It deprecates value depending on other option value' => array( + yield 'It deprecates value depending on other option value' => [ function (OptionsResolver $resolver) { $resolver ->setDefault('widget', null) @@ -703,15 +703,15 @@ class OptionsResolverTest extends TestCase }) ; }, - array('widget' => 'single_text', 'date_format' => 2), - array( + ['widget' => 'single_text', 'date_format' => 2], + [ 'type' => E_USER_DEPRECATED, 'message' => 'Using the "date_format" option when the "widget" option is set to "single_text" is deprecated.', - ), + ], 1, - ); + ]; - yield 'It triggers a deprecation for each evaluation' => array( + yield 'It triggers a deprecation for each evaluation' => [ function (OptionsResolver $resolver) { $resolver // defined by superclass @@ -729,15 +729,15 @@ class OptionsResolverTest extends TestCase }) ; }, - array('foo' => 'baz'), // It triggers a deprecation - array( + ['foo' => 'baz'], // It triggers a deprecation + [ 'type' => E_USER_DEPRECATED, 'message' => 'The option "foo" is deprecated.', - ), + ], 4, - ); + ]; - yield 'It ignores a deprecation if no option is provided by the user' => array( + yield 'It ignores a deprecation if no option is provided by the user' => [ function (OptionsResolver $resolver) { $resolver ->setDefined('foo') @@ -746,12 +746,12 @@ class OptionsResolverTest extends TestCase ->setDeprecated('bar') ; }, - array(), + [], null, 0, - ); + ]; - yield 'It explicitly ignores a depreciation' => array( + yield 'It explicitly ignores a depreciation' => [ function (OptionsResolver $resolver) { $resolver ->setDefault('baz', function (Options $options) { @@ -764,10 +764,10 @@ class OptionsResolverTest extends TestCase }) ; }, - array(), + [], null, 0, - ); + ]; } /** @@ -2056,11 +2056,11 @@ class OptionsResolverTest extends TestCase public function testIsNestedOption() { - $this->resolver->setDefaults(array( + $this->resolver->setDefaults([ 'database' => function (OptionsResolver $resolver) { - $resolver->setDefined(array('host', 'port')); + $resolver->setDefined(['host', 'port']); }, - )); + ]); $this->assertTrue($this->resolver->isNested('database')); } @@ -2070,15 +2070,15 @@ class OptionsResolverTest extends TestCase */ public function testFailsIfUndefinedNestedOption() { - $this->resolver->setDefaults(array( + $this->resolver->setDefaults([ 'name' => 'default', 'database' => function (OptionsResolver $resolver) { - $resolver->setDefined(array('host', 'port')); + $resolver->setDefined(['host', 'port']); }, - )); - $this->resolver->resolve(array( - 'database' => array('foo' => 'bar'), - )); + ]); + $this->resolver->resolve([ + 'database' => ['foo' => 'bar'], + ]); } /** @@ -2087,15 +2087,15 @@ class OptionsResolverTest extends TestCase */ public function testFailsIfMissingRequiredNestedOption() { - $this->resolver->setDefaults(array( + $this->resolver->setDefaults([ 'name' => 'default', 'database' => function (OptionsResolver $resolver) { $resolver->setRequired('host'); }, - )); - $this->resolver->resolve(array( - 'database' => array(), - )); + ]); + $this->resolver->resolve([ + 'database' => [], + ]); } /** @@ -2104,17 +2104,17 @@ class OptionsResolverTest extends TestCase */ public function testFailsIfInvalidTypeNestedOption() { - $this->resolver->setDefaults(array( + $this->resolver->setDefaults([ 'name' => 'default', 'database' => function (OptionsResolver $resolver) { $resolver ->setDefined('logging') ->setAllowedTypes('logging', 'bool'); }, - )); - $this->resolver->resolve(array( - 'database' => array('logging' => null), - )); + ]); + $this->resolver->resolve([ + 'database' => ['logging' => null], + ]); } /** @@ -2123,135 +2123,135 @@ class OptionsResolverTest extends TestCase */ public function testFailsIfNotArrayIsGivenForNestedOptions() { - $this->resolver->setDefaults(array( + $this->resolver->setDefaults([ 'name' => 'default', 'database' => function (OptionsResolver $resolver) { $resolver->setDefined('host'); }, - )); - $this->resolver->resolve(array( + ]); + $this->resolver->resolve([ 'database' => null, - )); + ]); } public function testResolveNestedOptionsWithoutDefault() { - $this->resolver->setDefaults(array( + $this->resolver->setDefaults([ 'name' => 'default', 'database' => function (OptionsResolver $resolver) { - $resolver->setDefined(array('host', 'port')); + $resolver->setDefined(['host', 'port']); }, - )); + ]); $actualOptions = $this->resolver->resolve(); - $expectedOptions = array( + $expectedOptions = [ 'name' => 'default', - 'database' => array(), - ); + 'database' => [], + ]; $this->assertSame($expectedOptions, $actualOptions); } public function testResolveNestedOptionsWithDefault() { - $this->resolver->setDefaults(array( + $this->resolver->setDefaults([ 'name' => 'default', 'database' => function (OptionsResolver $resolver) { - $resolver->setDefaults(array( + $resolver->setDefaults([ 'host' => 'localhost', 'port' => 3306, - )); + ]); }, - )); + ]); $actualOptions = $this->resolver->resolve(); - $expectedOptions = array( + $expectedOptions = [ 'name' => 'default', - 'database' => array( + 'database' => [ 'host' => 'localhost', 'port' => 3306, - ), - ); + ], + ]; $this->assertSame($expectedOptions, $actualOptions); } public function testResolveMultipleNestedOptions() { - $this->resolver->setDefaults(array( + $this->resolver->setDefaults([ 'name' => 'default', 'database' => function (OptionsResolver $resolver) { $resolver - ->setRequired(array('dbname', 'host')) - ->setDefaults(array( + ->setRequired(['dbname', 'host']) + ->setDefaults([ 'port' => 3306, 'replicas' => function (OptionsResolver $resolver) { - $resolver->setDefaults(array( + $resolver->setDefaults([ 'host' => 'replica1', 'port' => 3306, - )); + ]); }, - )); + ]); }, - )); - $actualOptions = $this->resolver->resolve(array( + ]); + $actualOptions = $this->resolver->resolve([ 'name' => 'custom', - 'database' => array( + 'database' => [ 'dbname' => 'test', 'host' => 'localhost', 'port' => null, - 'replicas' => array('host' => 'replica2'), - ), - )); - $expectedOptions = array( + 'replicas' => ['host' => 'replica2'], + ], + ]); + $expectedOptions = [ 'name' => 'custom', - 'database' => array( + 'database' => [ 'port' => null, - 'replicas' => array('port' => 3306, 'host' => 'replica2'), + 'replicas' => ['port' => 3306, 'host' => 'replica2'], 'dbname' => 'test', 'host' => 'localhost', - ), - ); + ], + ]; $this->assertSame($expectedOptions, $actualOptions); } public function testResolveLazyOptionUsingNestedOption() { - $this->resolver->setDefaults(array( + $this->resolver->setDefaults([ 'version' => function (Options $options) { return $options['database']['server_version']; }, 'database' => function (OptionsResolver $resolver) { $resolver->setDefault('server_version', '3.15'); }, - )); + ]); $actualOptions = $this->resolver->resolve(); - $expectedOptions = array( - 'database' => array('server_version' => '3.15'), + $expectedOptions = [ + 'database' => ['server_version' => '3.15'], 'version' => '3.15', - ); + ]; $this->assertSame($expectedOptions, $actualOptions); } public function testNormalizeNestedOptionValue() { $this->resolver - ->setDefaults(array( + ->setDefaults([ 'database' => function (OptionsResolver $resolver) { - $resolver->setDefaults(array( + $resolver->setDefaults([ 'port' => 3306, 'host' => 'localhost', 'dbname' => 'demo', - )); + ]); }, - )) + ]) ->setNormalizer('database', function (Options $options, $value) { ksort($value); return $value; }); - $actualOptions = $this->resolver->resolve(array( - 'database' => array('dbname' => 'test'), - )); - $expectedOptions = array( - 'database' => array('dbname' => 'test', 'host' => 'localhost', 'port' => 3306), - ); + $actualOptions = $this->resolver->resolve([ + 'database' => ['dbname' => 'test'], + ]); + $expectedOptions = [ + 'database' => ['dbname' => 'test', 'host' => 'localhost', 'port' => 3306], + ]; $this->assertSame($expectedOptions, $actualOptions); } @@ -2265,7 +2265,7 @@ class OptionsResolverTest extends TestCase $this->resolver->setDefault('foo', function (Options $options) { return 'lazy'; }); - $this->assertSame(array('foo' => 'lazy'), $this->resolver->resolve()); + $this->assertSame(['foo' => 'lazy'], $this->resolver->resolve()); } public function testOverwrittenNestedOptionNotEvaluatedIfScalarDefault() @@ -2276,7 +2276,7 @@ class OptionsResolverTest extends TestCase }); // defined by subclass $this->resolver->setDefault('foo', 'bar'); - $this->assertSame(array('foo' => 'bar'), $this->resolver->resolve()); + $this->assertSame(['foo' => 'bar'], $this->resolver->resolve()); } public function testOverwrittenLazyOptionNotEvaluatedIfNestedOption() @@ -2289,7 +2289,7 @@ class OptionsResolverTest extends TestCase $this->resolver->setDefault('foo', function (OptionsResolver $resolver) { $resolver->setDefault('bar', 'baz'); }); - $this->assertSame(array('foo' => array('bar' => 'baz')), $this->resolver->resolve()); + $this->assertSame(['foo' => ['bar' => 'baz']], $this->resolver->resolve()); } public function testResolveAllNestedOptionDefinitions() @@ -2306,7 +2306,7 @@ class OptionsResolverTest extends TestCase $this->resolver->setDefault('foo', function (OptionsResolver $resolver) { $resolver->setDefault('ping', 'pong'); }); - $this->assertSame(array('foo' => array('ping' => 'pong', 'bar' => 'baz')), $this->resolver->resolve()); + $this->assertSame(['foo' => ['ping' => 'pong', 'bar' => 'baz']], $this->resolver->resolve()); } public function testNormalizeNestedValue() @@ -2323,7 +2323,7 @@ class OptionsResolverTest extends TestCase return $resolvedValue; }); - $this->assertSame(array('foo' => array('bar' => 'baz')), $this->resolver->resolve()); + $this->assertSame(['foo' => ['bar' => 'baz']], $this->resolver->resolve()); } /** @@ -2342,14 +2342,14 @@ class OptionsResolverTest extends TestCase */ public function testFailsIfCyclicDependencyBetweenNestedOptionAndParentLazyOption() { - $this->resolver->setDefaults(array( + $this->resolver->setDefaults([ 'version' => function (Options $options) { return $options['database']['server_version']; }, 'database' => function (OptionsResolver $resolver, Options $parent) { $resolver->setDefault('server_version', $parent['version']); }, - )); + ]); $this->resolver->resolve(); } @@ -2385,13 +2385,13 @@ class OptionsResolverTest extends TestCase public function testGetAccessToParentOptionFromNestedOption() { - $this->resolver->setDefaults(array( + $this->resolver->setDefaults([ 'version' => 3.15, 'database' => function (OptionsResolver $resolver, Options $parent) { $resolver->setDefault('server_version', $parent['version']); }, - )); - $this->assertSame(array('version' => 3.15, 'database' => array('server_version' => 3.15)), $this->resolver->resolve()); + ]); + $this->assertSame(['version' => 3.15, 'database' => ['server_version' => 3.15]], $this->resolver->resolve()); } public function testNestedClosureWithoutTypeHintNotInvoked() @@ -2400,7 +2400,7 @@ class OptionsResolverTest extends TestCase Assert::fail('Should not be called'); }; $this->resolver->setDefault('foo', $closure); - $this->assertSame(array('foo' => $closure), $this->resolver->resolve()); + $this->assertSame(['foo' => $closure], $this->resolver->resolve()); } public function testNestedClosureWithoutTypeHint2ndArgumentNotInvoked() @@ -2409,12 +2409,12 @@ class OptionsResolverTest extends TestCase Assert::fail('Should not be called'); }; $this->resolver->setDefault('foo', $closure); - $this->assertSame(array('foo' => $closure), $this->resolver->resolve()); + $this->assertSame(['foo' => $closure], $this->resolver->resolve()); } public function testResolveLazyOptionWithTransitiveDefaultDependency() { - $this->resolver->setDefaults(array( + $this->resolver->setDefaults([ 'ip' => null, 'database' => function (OptionsResolver $resolver, Options $parent) { $resolver->setDefault('host', $parent['ip']); @@ -2425,22 +2425,22 @@ class OptionsResolverTest extends TestCase 'secondary_replica' => function (Options $options) { return $options['database']['primary_replica']['host']; }, - )); - $actualOptions = $this->resolver->resolve(array('ip' => '127.0.0.1')); - $expectedOptions = array( + ]); + $actualOptions = $this->resolver->resolve(['ip' => '127.0.0.1']); + $expectedOptions = [ 'ip' => '127.0.0.1', - 'database' => array( + 'database' => [ 'host' => '127.0.0.1', - 'primary_replica' => array('host' => '127.0.0.1'), - ), + 'primary_replica' => ['host' => '127.0.0.1'], + ], 'secondary_replica' => '127.0.0.1', - ); + ]; $this->assertSame($expectedOptions, $actualOptions); } public function testAccessToParentOptionFromNestedNormalizerAndLazyOption() { - $this->resolver->setDefaults(array( + $this->resolver->setDefaults([ 'debug' => true, 'database' => function (OptionsResolver $resolver, Options $parent) { $resolver @@ -2452,15 +2452,15 @@ class OptionsResolverTest extends TestCase return false === $parent['debug'] ? true : $value; }); }, - )); - $actualOptions = $this->resolver->resolve(array( + ]); + $actualOptions = $this->resolver->resolve([ 'debug' => false, - 'database' => array('logging' => false), - )); - $expectedOptions = array( + 'database' => ['logging' => false], + ]); + $expectedOptions = [ 'debug' => false, - 'database' => array('profiling' => false, 'logging' => true), - ); + 'database' => ['profiling' => false, 'logging' => true], + ]; $this->assertSame($expectedOptions, $actualOptions); } } diff --git a/src/Symfony/Component/Process/Process.php b/src/Symfony/Component/Process/Process.php index 49286c1a9b..8b7f539e0f 100644 --- a/src/Symfony/Component/Process/Process.php +++ b/src/Symfony/Component/Process/Process.php @@ -190,7 +190,7 @@ class Process implements \IteratorAggregate */ public static function fromShellCommandline(string $command, string $cwd = null, array $env = null, $input = null, ?float $timeout = 60) { - $process = new static(array(), $cwd, $env, $input, $timeout); + $process = new static([], $cwd, $env, $input, $timeout); $process->commandline = $command; return $process; diff --git a/src/Symfony/Component/Process/Tests/KillableProcessWithOutput.php b/src/Symfony/Component/Process/Tests/KillableProcessWithOutput.php index 2bbc386d0f..28a6a271bb 100644 --- a/src/Symfony/Component/Process/Tests/KillableProcessWithOutput.php +++ b/src/Symfony/Component/Process/Tests/KillableProcessWithOutput.php @@ -9,12 +9,12 @@ * file that was distributed with this source code. */ -$outputs = array( +$outputs = [ 'First iteration output', 'Second iteration output', 'One more iteration output', 'This took more time', -); +]; $iterationTime = 10000; diff --git a/src/Symfony/Component/Process/Tests/ProcessFailedExceptionTest.php b/src/Symfony/Component/Process/Tests/ProcessFailedExceptionTest.php index d8fdb5c1f0..2467c960e8 100644 --- a/src/Symfony/Component/Process/Tests/ProcessFailedExceptionTest.php +++ b/src/Symfony/Component/Process/Tests/ProcessFailedExceptionTest.php @@ -24,7 +24,7 @@ class ProcessFailedExceptionTest extends TestCase */ public function testProcessFailedExceptionThrowsException() { - $process = $this->getMockBuilder('Symfony\Component\Process\Process')->setMethods(array('isSuccessful'))->setConstructorArgs(array(array('php')))->getMock(); + $process = $this->getMockBuilder('Symfony\Component\Process\Process')->setMethods(['isSuccessful'])->setConstructorArgs([['php']])->getMock(); $process->expects($this->once()) ->method('isSuccessful') ->will($this->returnValue(true)); @@ -52,7 +52,7 @@ class ProcessFailedExceptionTest extends TestCase $errorOutput = 'FATAL: Unexpected error'; $workingDirectory = getcwd(); - $process = $this->getMockBuilder('Symfony\Component\Process\Process')->setMethods(array('isSuccessful', 'getOutput', 'getErrorOutput', 'getExitCode', 'getExitCodeText', 'isOutputDisabled', 'getWorkingDirectory'))->setConstructorArgs(array(array($cmd)))->getMock(); + $process = $this->getMockBuilder('Symfony\Component\Process\Process')->setMethods(['isSuccessful', 'getOutput', 'getErrorOutput', 'getExitCode', 'getExitCodeText', 'isOutputDisabled', 'getWorkingDirectory'])->setConstructorArgs([[$cmd]])->getMock(); $process->expects($this->once()) ->method('isSuccessful') ->will($this->returnValue(false)); @@ -100,7 +100,7 @@ class ProcessFailedExceptionTest extends TestCase $exitText = 'General error'; $workingDirectory = getcwd(); - $process = $this->getMockBuilder('Symfony\Component\Process\Process')->setMethods(array('isSuccessful', 'isOutputDisabled', 'getExitCode', 'getExitCodeText', 'getOutput', 'getErrorOutput', 'getWorkingDirectory'))->setConstructorArgs(array(array($cmd)))->getMock(); + $process = $this->getMockBuilder('Symfony\Component\Process\Process')->setMethods(['isSuccessful', 'isOutputDisabled', 'getExitCode', 'getExitCodeText', 'getOutput', 'getErrorOutput', 'getWorkingDirectory'])->setConstructorArgs([[$cmd]])->getMock(); $process->expects($this->once()) ->method('isSuccessful') ->will($this->returnValue(false)); diff --git a/src/Symfony/Component/Process/Tests/ProcessTest.php b/src/Symfony/Component/Process/Tests/ProcessTest.php index 60162975fd..cf5685994c 100644 --- a/src/Symfony/Component/Process/Tests/ProcessTest.php +++ b/src/Symfony/Component/Process/Tests/ProcessTest.php @@ -55,13 +55,13 @@ class ProcessTest extends TestCase { try { // Check that it works fine if the CWD exists - $cmd = new Process(array('echo', 'test'), __DIR__); + $cmd = new Process(['echo', 'test'], __DIR__); $cmd->run(); } catch (\Exception $e) { $this->fail($e); } - $cmd = new Process(array('echo', 'test'), __DIR__.'/notfound/'); + $cmd = new Process(['echo', 'test'], __DIR__.'/notfound/'); $cmd->run(); } @@ -114,7 +114,7 @@ class ProcessTest extends TestCase */ public function testStopWithTimeoutIsActuallyWorking() { - $p = $this->getProcess(array(self::$phpBin, __DIR__.'/NonStopableProcess.php', 30)); + $p = $this->getProcess([self::$phpBin, __DIR__.'/NonStopableProcess.php', 30]); $p->start(); while ($p->isRunning() && false === strpos($p->getOutput(), 'received')) { @@ -135,7 +135,7 @@ class ProcessTest extends TestCase public function testWaitUntilSpecificOutput() { - $p = $this->getProcess(array(self::$phpBin, __DIR__.'/KillableProcessWithOutput.php')); + $p = $this->getProcess([self::$phpBin, __DIR__.'/KillableProcessWithOutput.php']); $p->start(); $start = microtime(true); @@ -304,10 +304,10 @@ class ProcessTest extends TestCase public function provideInvalidInputValues() { - return array( - array(array()), - array(new NonStringifiable()), - ); + return [ + [[]], + [new NonStringifiable()], + ]; } /** @@ -322,25 +322,25 @@ class ProcessTest extends TestCase public function provideInputValues() { - return array( - array(null, null), - array('24.5', 24.5), - array('input data', 'input data'), - ); + return [ + [null, null], + ['24.5', 24.5], + ['input data', 'input data'], + ]; } public function chainedCommandsOutputProvider() { if ('\\' === \DIRECTORY_SEPARATOR) { - return array( - array("2 \r\n2\r\n", '&&', '2'), - ); + return [ + ["2 \r\n2\r\n", '&&', '2'], + ]; } - return array( - array("1\n1\n", ';', '1'), - array("2\n2\n", '&&', '2'), - ); + return [ + ["1\n1\n", ';', '1'], + ["2\n2\n", '&&', '2'], + ]; } /** @@ -409,7 +409,7 @@ class ProcessTest extends TestCase $p->start(); - foreach (array('foo', 'bar') as $s) { + foreach (['foo', 'bar'] as $s) { while (false === strpos($p->$getOutput(), $s)) { usleep(1000); } @@ -425,10 +425,10 @@ class ProcessTest extends TestCase public function provideIncrementalOutput() { - return array( - array('getOutput', 'getIncrementalOutput', 'php://stdout'), - array('getErrorOutput', 'getIncrementalErrorOutput', 'php://stderr'), - ); + return [ + ['getOutput', 'getIncrementalOutput', 'php://stdout'], + ['getErrorOutput', 'getIncrementalErrorOutput', 'php://stderr'], + ]; } public function testGetOutput() @@ -911,7 +911,7 @@ class ProcessTest extends TestCase */ public function testSignal() { - $process = $this->getProcess(array(self::$phpBin, __DIR__.'/SignalListener.php')); + $process = $this->getProcess([self::$phpBin, __DIR__.'/SignalListener.php']); $process->start(); while (false === strpos($process->getOutput(), 'Caught')) { @@ -971,13 +971,13 @@ class ProcessTest extends TestCase public function provideMethodsThatNeedARunningProcess() { - return array( - array('getOutput'), - array('getIncrementalOutput'), - array('getErrorOutput'), - array('getIncrementalErrorOutput'), - array('wait'), - ); + return [ + ['getOutput'], + ['getIncrementalOutput'], + ['getErrorOutput'], + ['getIncrementalErrorOutput'], + ['wait'], + ]; } /** @@ -1002,12 +1002,12 @@ class ProcessTest extends TestCase public function provideMethodsThatNeedATerminatedProcess() { - return array( - array('hasBeenSignaled'), - array('getTermSignal'), - array('hasBeenStopped'), - array('getStopSignal'), - ); + return [ + ['hasBeenSignaled'], + ['getTermSignal'], + ['hasBeenStopped'], + ['getStopSignal'], + ]; } /** @@ -1118,12 +1118,12 @@ class ProcessTest extends TestCase public function provideOutputFetchingMethods() { - return array( - array('getOutput'), - array('getIncrementalOutput'), - array('getErrorOutput'), - array('getIncrementalErrorOutput'), - ); + return [ + ['getOutput'], + ['getIncrementalOutput'], + ['getErrorOutput'], + ['getIncrementalErrorOutput'], + ]; } public function testStopTerminatesProcessCleanly() @@ -1155,32 +1155,32 @@ class ProcessTest extends TestCase public function responsesCodeProvider() { - return array( + return [ //expected output / getter / code to execute //array(1,'getExitCode','exit(1);'), //array(true,'isSuccessful','exit();'), - array('output', 'getOutput', 'echo \'output\';'), - ); + ['output', 'getOutput', 'echo \'output\';'], + ]; } public function pipesCodeProvider() { - $variations = array( + $variations = [ 'fwrite(STDOUT, $in = file_get_contents(\'php://stdin\')); fwrite(STDERR, $in);', 'include \''.__DIR__.'/PipeStdinInStdoutStdErrStreamSelect.php\';', - ); + ]; if ('\\' === \DIRECTORY_SEPARATOR) { // Avoid XL buffers on Windows because of https://bugs.php.net/bug.php?id=65650 - $sizes = array(1, 2, 4, 8); + $sizes = [1, 2, 4, 8]; } else { - $sizes = array(1, 16, 64, 1024, 4096); + $sizes = [1, 16, 64, 1024, 4096]; } - $codes = array(); + $codes = []; foreach ($sizes as $size) { foreach ($variations as $code) { - $codes[] = array($code, $size); + $codes[] = [$code, $size]; } } @@ -1208,10 +1208,10 @@ class ProcessTest extends TestCase public function provideVariousIncrementals() { - return array( - array('php://stdout', 'getIncrementalOutput'), - array('php://stderr', 'getIncrementalErrorOutput'), - ); + return [ + ['php://stdout', 'getIncrementalOutput'], + ['php://stderr', 'getIncrementalErrorOutput'], + ]; } public function testIteratorInput() @@ -1316,32 +1316,32 @@ class ProcessTest extends TestCase $process = $this->getProcessForCode('fwrite(STDOUT, 123); fwrite(STDERR, 234); flush(); usleep(10000); fwrite(STDOUT, fread(STDIN, 3)); fwrite(STDERR, 456);'); $process->setInput($input); $process->start(); - $output = array(); + $output = []; foreach ($process as $type => $data) { - $output[] = array($type, $data); + $output[] = [$type, $data]; break; } - $expectedOutput = array( - array($process::OUT, '123'), - ); + $expectedOutput = [ + [$process::OUT, '123'], + ]; $this->assertSame($expectedOutput, $output); $input->write(345); foreach ($process as $type => $data) { - $output[] = array($type, $data); + $output[] = [$type, $data]; } $this->assertSame('', $process->getOutput()); $this->assertFalse($process->isRunning()); - $expectedOutput = array( - array($process::OUT, '123'), - array($process::ERR, '234'), - array($process::OUT, '345'), - array($process::ERR, '456'), - ); + $expectedOutput = [ + [$process::OUT, '123'], + [$process::ERR, '234'], + [$process::OUT, '345'], + [$process::ERR, '456'], + ]; $this->assertSame($expectedOutput, $output); } @@ -1352,32 +1352,32 @@ class ProcessTest extends TestCase $process = $this->getProcessForCode('fwrite(STDOUT, fread(STDIN, 3));'); $process->setInput($input); $process->start(); - $output = array(); + $output = []; foreach ($process->getIterator($process::ITER_NON_BLOCKING | $process::ITER_KEEP_OUTPUT) as $type => $data) { - $output[] = array($type, $data); + $output[] = [$type, $data]; break; } - $expectedOutput = array( - array($process::OUT, ''), - ); + $expectedOutput = [ + [$process::OUT, ''], + ]; $this->assertSame($expectedOutput, $output); $input->write(123); foreach ($process->getIterator($process::ITER_NON_BLOCKING | $process::ITER_KEEP_OUTPUT) as $type => $data) { if ('' !== $data) { - $output[] = array($type, $data); + $output[] = [$type, $data]; } } $this->assertSame('123', $process->getOutput()); $this->assertFalse($process->isRunning()); - $expectedOutput = array( - array($process::OUT, ''), - array($process::OUT, '123'), - ); + $expectedOutput = [ + [$process::OUT, ''], + [$process::OUT, '123'], + ]; $this->assertSame($expectedOutput, $output); } @@ -1399,7 +1399,7 @@ class ProcessTest extends TestCase public function testSetBadEnv() { $process = $this->getProcess('echo hello'); - $process->setEnv(array('bad%%' => '123')); + $process->setEnv(['bad%%' => '123']); $process->inheritEnvironmentVariables(true); $process->run(); @@ -1413,7 +1413,7 @@ class ProcessTest extends TestCase putenv('existing_var=foo'); $_ENV['existing_var'] = 'foo'; $process = $this->getProcess('php -r "echo getenv(\'new_test_var\');"'); - $process->setEnv(array('existing_var' => 'bar', 'new_test_var' => 'foo')); + $process->setEnv(['existing_var' => 'bar', 'new_test_var' => 'foo']); $process->inheritEnvironmentVariables(); $process->run(); @@ -1428,14 +1428,14 @@ class ProcessTest extends TestCase public function testEnvIsInherited() { - $process = $this->getProcessForCode('echo serialize($_SERVER);', null, array('BAR' => 'BAZ', 'EMPTY' => '')); + $process = $this->getProcessForCode('echo serialize($_SERVER);', null, ['BAR' => 'BAZ', 'EMPTY' => '']); putenv('FOO=BAR'); $_ENV['FOO'] = 'BAR'; $process->run(); - $expected = array('BAR' => 'BAZ', 'EMPTY' => '', 'FOO' => 'BAR'); + $expected = ['BAR' => 'BAZ', 'EMPTY' => '', 'FOO' => 'BAR']; $env = array_intersect_key(unserialize($process->getOutput()), $expected); $this->assertEquals($expected, $env); @@ -1446,7 +1446,7 @@ class ProcessTest extends TestCase public function testGetCommandLine() { - $p = new Process(array('/usr/bin/php')); + $p = new Process(['/usr/bin/php']); $expected = '\\' === \DIRECTORY_SEPARATOR ? '"/usr/bin/php"' : "'/usr/bin/php'"; $this->assertSame($expected, $p->getCommandLine()); @@ -1457,7 +1457,7 @@ class ProcessTest extends TestCase */ public function testEscapeArgument($arg) { - $p = new Process(array(self::$phpBin, '-r', 'echo $argv[1];', $arg)); + $p = new Process([self::$phpBin, '-r', 'echo $argv[1];', $arg]); $p->run(); $this->assertSame((string) $arg, $p->getOutput()); @@ -1483,24 +1483,24 @@ EOTXT; public function provideEscapeArgument() { - yield array('a"b%c%'); - yield array('a"b^c^'); - yield array("a\nb'c"); - yield array('a^b c!'); - yield array("a!b\tc"); - yield array('a\\\\"\\"'); - yield array('éÉèÈàÀöä'); - yield array(null); - yield array(1); - yield array(1.1); + yield ['a"b%c%']; + yield ['a"b^c^']; + yield ["a\nb'c"]; + yield ['a^b c!']; + yield ["a!b\tc"]; + yield ['a\\\\"\\"']; + yield ['éÉèÈàÀöä']; + yield [null]; + yield [1]; + yield [1.1]; } public function testEnvArgument() { - $env = array('FOO' => 'Foo', 'BAR' => 'Bar'); + $env = ['FOO' => 'Foo', 'BAR' => 'Bar']; $cmd = '\\' === \DIRECTORY_SEPARATOR ? 'echo !FOO! !BAR! !BAZ!' : 'echo $FOO $BAR $BAZ'; $p = Process::fromShellCommandline($cmd, null, $env); - $p->run(null, array('BAR' => 'baR', 'BAZ' => 'baZ')); + $p->run(null, ['BAR' => 'baR', 'BAZ' => 'baZ']); $this->assertSame('Foo baR baZ', rtrim($p->getOutput())); $this->assertSame($env, $p->getEnv()); @@ -1524,7 +1524,7 @@ EOTXT; private function getProcessForCode(string $code, string $cwd = null, array $env = null, $input = null, ?int $timeout = 60): Process { - return $this->getProcess(array(self::$phpBin, '-r', $code), $cwd, $env, $input, $timeout); + return $this->getProcess([self::$phpBin, '-r', $code], $cwd, $env, $input, $timeout); } } diff --git a/src/Symfony/Component/PropertyInfo/Extractor/ReflectionExtractor.php b/src/Symfony/Component/PropertyInfo/Extractor/ReflectionExtractor.php index 70f5cb5013..0ed1e4e2af 100644 --- a/src/Symfony/Component/PropertyInfo/Extractor/ReflectionExtractor.php +++ b/src/Symfony/Component/PropertyInfo/Extractor/ReflectionExtractor.php @@ -150,7 +150,7 @@ class ReflectionExtractor implements PropertyListExtractorInterface, PropertyTyp /** * {@inheritdoc} */ - public function isInitializable(string $class, string $property, array $context = array()): ?bool + public function isInitializable(string $class, string $property, array $context = []): ?bool { try { $reflectionClass = new \ReflectionClass($class); diff --git a/src/Symfony/Component/PropertyInfo/PropertyInfoCacheExtractor.php b/src/Symfony/Component/PropertyInfo/PropertyInfoCacheExtractor.php index 61794d3194..ac883e7c04 100644 --- a/src/Symfony/Component/PropertyInfo/PropertyInfoCacheExtractor.php +++ b/src/Symfony/Component/PropertyInfo/PropertyInfoCacheExtractor.php @@ -24,7 +24,7 @@ class PropertyInfoCacheExtractor implements PropertyInfoExtractorInterface, Prop { private $propertyInfoExtractor; private $cacheItemPool; - private $arrayCache = array(); + private $arrayCache = []; public function __construct(PropertyInfoExtractorInterface $propertyInfoExtractor, CacheItemPoolInterface $cacheItemPool) { @@ -35,57 +35,57 @@ class PropertyInfoCacheExtractor implements PropertyInfoExtractorInterface, Prop /** * {@inheritdoc} */ - public function isReadable($class, $property, array $context = array()) + public function isReadable($class, $property, array $context = []) { - return $this->extract('isReadable', array($class, $property, $context)); + return $this->extract('isReadable', [$class, $property, $context]); } /** * {@inheritdoc} */ - public function isWritable($class, $property, array $context = array()) + public function isWritable($class, $property, array $context = []) { - return $this->extract('isWritable', array($class, $property, $context)); + return $this->extract('isWritable', [$class, $property, $context]); } /** * {@inheritdoc} */ - public function getShortDescription($class, $property, array $context = array()) + public function getShortDescription($class, $property, array $context = []) { - return $this->extract('getShortDescription', array($class, $property, $context)); + return $this->extract('getShortDescription', [$class, $property, $context]); } /** * {@inheritdoc} */ - public function getLongDescription($class, $property, array $context = array()) + public function getLongDescription($class, $property, array $context = []) { - return $this->extract('getLongDescription', array($class, $property, $context)); + return $this->extract('getLongDescription', [$class, $property, $context]); } /** * {@inheritdoc} */ - public function getProperties($class, array $context = array()) + public function getProperties($class, array $context = []) { - return $this->extract('getProperties', array($class, $context)); + return $this->extract('getProperties', [$class, $context]); } /** * {@inheritdoc} */ - public function getTypes($class, $property, array $context = array()) + public function getTypes($class, $property, array $context = []) { - return $this->extract('getTypes', array($class, $property, $context)); + return $this->extract('getTypes', [$class, $property, $context]); } /** * {@inheritdoc} */ - public function isInitializable(string $class, string $property, array $context = array()): ?bool + public function isInitializable(string $class, string $property, array $context = []): ?bool { - return $this->extract('isInitializable', array($class, $property, $context)); + return $this->extract('isInitializable', [$class, $property, $context]); } /** diff --git a/src/Symfony/Component/PropertyInfo/PropertyInfoExtractor.php b/src/Symfony/Component/PropertyInfo/PropertyInfoExtractor.php index a31278cfde..d7de8d2644 100644 --- a/src/Symfony/Component/PropertyInfo/PropertyInfoExtractor.php +++ b/src/Symfony/Component/PropertyInfo/PropertyInfoExtractor.php @@ -33,7 +33,7 @@ class PropertyInfoExtractor implements PropertyInfoExtractorInterface, PropertyI * @param iterable|PropertyAccessExtractorInterface[] $accessExtractors * @param iterable|PropertyInitializableExtractorInterface[] $initializableExtractors */ - public function __construct(iterable $listExtractors = array(), iterable $typeExtractors = array(), iterable $descriptionExtractors = array(), iterable $accessExtractors = array(), iterable $initializableExtractors = array()) + public function __construct(iterable $listExtractors = [], iterable $typeExtractors = [], iterable $descriptionExtractors = [], iterable $accessExtractors = [], iterable $initializableExtractors = []) { $this->listExtractors = $listExtractors; $this->typeExtractors = $typeExtractors; @@ -45,57 +45,57 @@ class PropertyInfoExtractor implements PropertyInfoExtractorInterface, PropertyI /** * {@inheritdoc} */ - public function getProperties($class, array $context = array()) + public function getProperties($class, array $context = []) { - return $this->extract($this->listExtractors, 'getProperties', array($class, $context)); + return $this->extract($this->listExtractors, 'getProperties', [$class, $context]); } /** * {@inheritdoc} */ - public function getShortDescription($class, $property, array $context = array()) + public function getShortDescription($class, $property, array $context = []) { - return $this->extract($this->descriptionExtractors, 'getShortDescription', array($class, $property, $context)); + return $this->extract($this->descriptionExtractors, 'getShortDescription', [$class, $property, $context]); } /** * {@inheritdoc} */ - public function getLongDescription($class, $property, array $context = array()) + public function getLongDescription($class, $property, array $context = []) { - return $this->extract($this->descriptionExtractors, 'getLongDescription', array($class, $property, $context)); + return $this->extract($this->descriptionExtractors, 'getLongDescription', [$class, $property, $context]); } /** * {@inheritdoc} */ - public function getTypes($class, $property, array $context = array()) + public function getTypes($class, $property, array $context = []) { - return $this->extract($this->typeExtractors, 'getTypes', array($class, $property, $context)); + return $this->extract($this->typeExtractors, 'getTypes', [$class, $property, $context]); } /** * {@inheritdoc} */ - public function isReadable($class, $property, array $context = array()) + public function isReadable($class, $property, array $context = []) { - return $this->extract($this->accessExtractors, 'isReadable', array($class, $property, $context)); + return $this->extract($this->accessExtractors, 'isReadable', [$class, $property, $context]); } /** * {@inheritdoc} */ - public function isWritable($class, $property, array $context = array()) + public function isWritable($class, $property, array $context = []) { - return $this->extract($this->accessExtractors, 'isWritable', array($class, $property, $context)); + return $this->extract($this->accessExtractors, 'isWritable', [$class, $property, $context]); } /** * {@inheritdoc} */ - public function isInitializable(string $class, string $property, array $context = array()): ?bool + public function isInitializable(string $class, string $property, array $context = []): ?bool { - return $this->extract($this->initializableExtractors, 'isInitializable', array($class, $property, $context)); + return $this->extract($this->initializableExtractors, 'isInitializable', [$class, $property, $context]); } /** diff --git a/src/Symfony/Component/PropertyInfo/PropertyInitializableExtractorInterface.php b/src/Symfony/Component/PropertyInfo/PropertyInitializableExtractorInterface.php index c00ca35c23..13248fc194 100644 --- a/src/Symfony/Component/PropertyInfo/PropertyInitializableExtractorInterface.php +++ b/src/Symfony/Component/PropertyInfo/PropertyInitializableExtractorInterface.php @@ -21,5 +21,5 @@ interface PropertyInitializableExtractorInterface /** * Is the property initializable? Returns true if a constructor's parameter matches the given property name. */ - public function isInitializable(string $class, string $property, array $context = array()): ?bool; + public function isInitializable(string $class, string $property, array $context = []): ?bool; } diff --git a/src/Symfony/Component/PropertyInfo/Tests/AbstractPropertyInfoExtractorTest.php b/src/Symfony/Component/PropertyInfo/Tests/AbstractPropertyInfoExtractorTest.php index 6006798020..928e867dec 100644 --- a/src/Symfony/Component/PropertyInfo/Tests/AbstractPropertyInfoExtractorTest.php +++ b/src/Symfony/Component/PropertyInfo/Tests/AbstractPropertyInfoExtractorTest.php @@ -30,7 +30,7 @@ class AbstractPropertyInfoExtractorTest extends TestCase protected function setUp() { - $extractors = array(new NullExtractor(), new DummyExtractor()); + $extractors = [new NullExtractor(), new DummyExtractor()]; $this->propertyInfo = new PropertyInfoExtractor($extractors, $extractors, $extractors, $extractors, $extractors); } @@ -45,36 +45,36 @@ class AbstractPropertyInfoExtractorTest extends TestCase public function testGetShortDescription() { - $this->assertSame('short', $this->propertyInfo->getShortDescription('Foo', 'bar', array())); + $this->assertSame('short', $this->propertyInfo->getShortDescription('Foo', 'bar', [])); } public function testGetLongDescription() { - $this->assertSame('long', $this->propertyInfo->getLongDescription('Foo', 'bar', array())); + $this->assertSame('long', $this->propertyInfo->getLongDescription('Foo', 'bar', [])); } public function testGetTypes() { - $this->assertEquals(array(new Type(Type::BUILTIN_TYPE_INT)), $this->propertyInfo->getTypes('Foo', 'bar', array())); + $this->assertEquals([new Type(Type::BUILTIN_TYPE_INT)], $this->propertyInfo->getTypes('Foo', 'bar', [])); } public function testIsReadable() { - $this->assertTrue($this->propertyInfo->isReadable('Foo', 'bar', array())); + $this->assertTrue($this->propertyInfo->isReadable('Foo', 'bar', [])); } public function testIsWritable() { - $this->assertTrue($this->propertyInfo->isWritable('Foo', 'bar', array())); + $this->assertTrue($this->propertyInfo->isWritable('Foo', 'bar', [])); } public function testGetProperties() { - $this->assertEquals(array('a', 'b'), $this->propertyInfo->getProperties('Foo')); + $this->assertEquals(['a', 'b'], $this->propertyInfo->getProperties('Foo')); } public function testIsInitializable() { - $this->assertTrue($this->propertyInfo->isInitializable('Foo', 'bar', array())); + $this->assertTrue($this->propertyInfo->isInitializable('Foo', 'bar', [])); } } diff --git a/src/Symfony/Component/PropertyInfo/Tests/DependencyInjection/PropertyInfoPassTest.php b/src/Symfony/Component/PropertyInfo/Tests/DependencyInjection/PropertyInfoPassTest.php index 29feddce55..aea826e210 100644 --- a/src/Symfony/Component/PropertyInfo/Tests/DependencyInjection/PropertyInfoPassTest.php +++ b/src/Symfony/Component/PropertyInfo/Tests/DependencyInjection/PropertyInfoPassTest.php @@ -26,46 +26,46 @@ class PropertyInfoPassTest extends TestCase { $container = new ContainerBuilder(); - $definition = $container->register('property_info')->setArguments(array(null, null, null, null, null)); - $container->register('n2')->addTag($tag, array('priority' => 100)); - $container->register('n1')->addTag($tag, array('priority' => 200)); + $definition = $container->register('property_info')->setArguments([null, null, null, null, null]); + $container->register('n2')->addTag($tag, ['priority' => 100]); + $container->register('n1')->addTag($tag, ['priority' => 200]); $container->register('n3')->addTag($tag); $propertyInfoPass = new PropertyInfoPass(); $propertyInfoPass->process($container); - $expected = new IteratorArgument(array( + $expected = new IteratorArgument([ new Reference('n1'), new Reference('n2'), new Reference('n3'), - )); + ]); $this->assertEquals($expected, $definition->getArgument($index)); } public function provideTags() { - return array( - array(0, 'property_info.list_extractor'), - array(1, 'property_info.type_extractor'), - array(2, 'property_info.description_extractor'), - array(3, 'property_info.access_extractor'), - array(4, 'property_info.initializable_extractor'), - ); + return [ + [0, 'property_info.list_extractor'], + [1, 'property_info.type_extractor'], + [2, 'property_info.description_extractor'], + [3, 'property_info.access_extractor'], + [4, 'property_info.initializable_extractor'], + ]; } public function testReturningEmptyArrayWhenNoService() { $container = new ContainerBuilder(); $propertyInfoExtractorDefinition = $container->register('property_info') - ->setArguments(array(array(), array(), array(), array(), array())); + ->setArguments([[], [], [], [], []]); $propertyInfoPass = new PropertyInfoPass(); $propertyInfoPass->process($container); - $this->assertEquals(new IteratorArgument(array()), $propertyInfoExtractorDefinition->getArgument(0)); - $this->assertEquals(new IteratorArgument(array()), $propertyInfoExtractorDefinition->getArgument(1)); - $this->assertEquals(new IteratorArgument(array()), $propertyInfoExtractorDefinition->getArgument(2)); - $this->assertEquals(new IteratorArgument(array()), $propertyInfoExtractorDefinition->getArgument(3)); - $this->assertEquals(new IteratorArgument(array()), $propertyInfoExtractorDefinition->getArgument(4)); + $this->assertEquals(new IteratorArgument([]), $propertyInfoExtractorDefinition->getArgument(0)); + $this->assertEquals(new IteratorArgument([]), $propertyInfoExtractorDefinition->getArgument(1)); + $this->assertEquals(new IteratorArgument([]), $propertyInfoExtractorDefinition->getArgument(2)); + $this->assertEquals(new IteratorArgument([]), $propertyInfoExtractorDefinition->getArgument(3)); + $this->assertEquals(new IteratorArgument([]), $propertyInfoExtractorDefinition->getArgument(4)); } } diff --git a/src/Symfony/Component/PropertyInfo/Tests/Extractor/PhpDocExtractorTest.php b/src/Symfony/Component/PropertyInfo/Tests/Extractor/PhpDocExtractorTest.php index d4f514bd7e..930dc6e24c 100644 --- a/src/Symfony/Component/PropertyInfo/Tests/Extractor/PhpDocExtractorTest.php +++ b/src/Symfony/Component/PropertyInfo/Tests/Extractor/PhpDocExtractorTest.php @@ -51,50 +51,50 @@ class PhpDocExtractorTest extends TestCase */ public function testExtractTypesWithNoPrefixes($property, array $type = null) { - $noPrefixExtractor = new PhpDocExtractor(null, array(), array(), array()); + $noPrefixExtractor = new PhpDocExtractor(null, [], [], []); $this->assertEquals($type, $noPrefixExtractor->getTypes('Symfony\Component\PropertyInfo\Tests\Fixtures\Dummy', $property)); } public function typesProvider() { - return array( - array('foo', null, 'Short description.', 'Long description.'), - array('bar', array(new Type(Type::BUILTIN_TYPE_STRING)), 'This is bar', null), - array('baz', array(new Type(Type::BUILTIN_TYPE_INT)), 'Should be used.', null), - array('foo2', array(new Type(Type::BUILTIN_TYPE_FLOAT)), null, null), - array('foo3', array(new Type(Type::BUILTIN_TYPE_CALLABLE)), null, null), - array('foo4', array(new Type(Type::BUILTIN_TYPE_NULL)), null, null), - array('foo5', null, null, null), - array( + return [ + ['foo', null, 'Short description.', 'Long description.'], + ['bar', [new Type(Type::BUILTIN_TYPE_STRING)], 'This is bar', null], + ['baz', [new Type(Type::BUILTIN_TYPE_INT)], 'Should be used.', null], + ['foo2', [new Type(Type::BUILTIN_TYPE_FLOAT)], null, null], + ['foo3', [new Type(Type::BUILTIN_TYPE_CALLABLE)], null, null], + ['foo4', [new Type(Type::BUILTIN_TYPE_NULL)], null, null], + ['foo5', null, null, null], + [ 'files', - array( + [ new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_OBJECT, false, 'SplFileInfo')), new Type(Type::BUILTIN_TYPE_RESOURCE), - ), + ], null, null, - ), - array('bal', array(new Type(Type::BUILTIN_TYPE_OBJECT, false, 'DateTime')), null, null), - array('parent', array(new Type(Type::BUILTIN_TYPE_OBJECT, false, 'Symfony\Component\PropertyInfo\Tests\Fixtures\ParentDummy')), null, null), - array('collection', array(new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_OBJECT, false, 'DateTime'))), null, null), - array('nestedCollection', array(new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_STRING, false)))), null, null), - array('mixedCollection', array(new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, null, null)), null, null), - array('a', array(new Type(Type::BUILTIN_TYPE_INT)), 'A.', null), - array('b', array(new Type(Type::BUILTIN_TYPE_OBJECT, true, 'Symfony\Component\PropertyInfo\Tests\Fixtures\ParentDummy')), 'B.', null), - array('c', array(new Type(Type::BUILTIN_TYPE_BOOL, true)), null, null), - array('d', array(new Type(Type::BUILTIN_TYPE_BOOL)), null, null), - array('e', array(new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_RESOURCE))), null, null), - array('f', array(new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_OBJECT, false, 'DateTime'))), null, null), - array('g', array(new Type(Type::BUILTIN_TYPE_ARRAY, true, null, true)), 'Nullable array.', null), - array('h', array(new Type(Type::BUILTIN_TYPE_STRING, true)), null, null), - array('i', array(new Type(Type::BUILTIN_TYPE_STRING, true), new Type(Type::BUILTIN_TYPE_INT, true)), null, null), - array('j', array(new Type(Type::BUILTIN_TYPE_OBJECT, true, 'DateTime')), null, null), - array('donotexist', null, null, null), - array('staticGetter', null, null, null), - array('staticSetter', null, null, null), - array('emptyVar', null, null, null), - ); + ], + ['bal', [new Type(Type::BUILTIN_TYPE_OBJECT, false, 'DateTime')], null, null], + ['parent', [new Type(Type::BUILTIN_TYPE_OBJECT, false, 'Symfony\Component\PropertyInfo\Tests\Fixtures\ParentDummy')], null, null], + ['collection', [new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_OBJECT, false, 'DateTime'))], null, null], + ['nestedCollection', [new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_STRING, false)))], null, null], + ['mixedCollection', [new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, null, null)], null, null], + ['a', [new Type(Type::BUILTIN_TYPE_INT)], 'A.', null], + ['b', [new Type(Type::BUILTIN_TYPE_OBJECT, true, 'Symfony\Component\PropertyInfo\Tests\Fixtures\ParentDummy')], 'B.', null], + ['c', [new Type(Type::BUILTIN_TYPE_BOOL, true)], null, null], + ['d', [new Type(Type::BUILTIN_TYPE_BOOL)], null, null], + ['e', [new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_RESOURCE))], null, null], + ['f', [new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_OBJECT, false, 'DateTime'))], null, null], + ['g', [new Type(Type::BUILTIN_TYPE_ARRAY, true, null, true)], 'Nullable array.', null], + ['h', [new Type(Type::BUILTIN_TYPE_STRING, true)], null, null], + ['i', [new Type(Type::BUILTIN_TYPE_STRING, true), new Type(Type::BUILTIN_TYPE_INT, true)], null, null], + ['j', [new Type(Type::BUILTIN_TYPE_OBJECT, true, 'DateTime')], null, null], + ['donotexist', null, null, null], + ['staticGetter', null, null, null], + ['staticSetter', null, null, null], + ['emptyVar', null, null, null], + ]; } /** @@ -111,23 +111,23 @@ class PhpDocExtractorTest extends TestCase public function provideCollectionTypes() { - return array( - array('iteratorCollection', array(new Type(Type::BUILTIN_TYPE_OBJECT, false, 'Iterator', true, null, new Type(Type::BUILTIN_TYPE_STRING))), null, null), - array('iteratorCollectionWithKey', array(new Type(Type::BUILTIN_TYPE_OBJECT, false, 'Iterator', true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_STRING))), null, null), - array( + return [ + ['iteratorCollection', [new Type(Type::BUILTIN_TYPE_OBJECT, false, 'Iterator', true, null, new Type(Type::BUILTIN_TYPE_STRING))], null, null], + ['iteratorCollectionWithKey', [new Type(Type::BUILTIN_TYPE_OBJECT, false, 'Iterator', true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_STRING))], null, null], + [ 'nestedIterators', - array(new Type( + [new Type( Type::BUILTIN_TYPE_OBJECT, false, 'Iterator', true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_OBJECT, false, 'Iterator', true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_STRING)) - )), + )], null, null, - ), - ); + ], + ]; } /** @@ -135,89 +135,89 @@ class PhpDocExtractorTest extends TestCase */ public function testExtractTypesWithCustomPrefixes($property, array $type = null) { - $customExtractor = new PhpDocExtractor(null, array('add', 'remove'), array('is', 'can')); + $customExtractor = new PhpDocExtractor(null, ['add', 'remove'], ['is', 'can']); $this->assertEquals($type, $customExtractor->getTypes('Symfony\Component\PropertyInfo\Tests\Fixtures\Dummy', $property)); } public function typesWithCustomPrefixesProvider() { - return array( - array('foo', null, 'Short description.', 'Long description.'), - array('bar', array(new Type(Type::BUILTIN_TYPE_STRING)), 'This is bar', null), - array('baz', array(new Type(Type::BUILTIN_TYPE_INT)), 'Should be used.', null), - array('foo2', array(new Type(Type::BUILTIN_TYPE_FLOAT)), null, null), - array('foo3', array(new Type(Type::BUILTIN_TYPE_CALLABLE)), null, null), - array('foo4', array(new Type(Type::BUILTIN_TYPE_NULL)), null, null), - array('foo5', null, null, null), - array( + return [ + ['foo', null, 'Short description.', 'Long description.'], + ['bar', [new Type(Type::BUILTIN_TYPE_STRING)], 'This is bar', null], + ['baz', [new Type(Type::BUILTIN_TYPE_INT)], 'Should be used.', null], + ['foo2', [new Type(Type::BUILTIN_TYPE_FLOAT)], null, null], + ['foo3', [new Type(Type::BUILTIN_TYPE_CALLABLE)], null, null], + ['foo4', [new Type(Type::BUILTIN_TYPE_NULL)], null, null], + ['foo5', null, null, null], + [ 'files', - array( + [ new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_OBJECT, false, 'SplFileInfo')), new Type(Type::BUILTIN_TYPE_RESOURCE), - ), + ], null, null, - ), - array('bal', array(new Type(Type::BUILTIN_TYPE_OBJECT, false, 'DateTime')), null, null), - array('parent', array(new Type(Type::BUILTIN_TYPE_OBJECT, false, 'Symfony\Component\PropertyInfo\Tests\Fixtures\ParentDummy')), null, null), - array('collection', array(new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_OBJECT, false, 'DateTime'))), null, null), - array('nestedCollection', array(new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_STRING, false)))), null, null), - array('mixedCollection', array(new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, null, null)), null, null), - array('a', null, 'A.', null), - array('b', null, 'B.', null), - array('c', array(new Type(Type::BUILTIN_TYPE_BOOL, true)), null, null), - array('d', array(new Type(Type::BUILTIN_TYPE_BOOL)), null, null), - array('e', array(new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_RESOURCE))), null, null), - array('f', array(new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_OBJECT, false, 'DateTime'))), null, null), - array('g', array(new Type(Type::BUILTIN_TYPE_ARRAY, true, null, true)), 'Nullable array.', null), - array('h', array(new Type(Type::BUILTIN_TYPE_STRING, true)), null, null), - array('i', array(new Type(Type::BUILTIN_TYPE_STRING, true), new Type(Type::BUILTIN_TYPE_INT, true)), null, null), - array('j', array(new Type(Type::BUILTIN_TYPE_OBJECT, true, 'DateTime')), null, null), - array('donotexist', null, null, null), - array('staticGetter', null, null, null), - array('staticSetter', null, null, null), - ); + ], + ['bal', [new Type(Type::BUILTIN_TYPE_OBJECT, false, 'DateTime')], null, null], + ['parent', [new Type(Type::BUILTIN_TYPE_OBJECT, false, 'Symfony\Component\PropertyInfo\Tests\Fixtures\ParentDummy')], null, null], + ['collection', [new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_OBJECT, false, 'DateTime'))], null, null], + ['nestedCollection', [new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_STRING, false)))], null, null], + ['mixedCollection', [new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, null, null)], null, null], + ['a', null, 'A.', null], + ['b', null, 'B.', null], + ['c', [new Type(Type::BUILTIN_TYPE_BOOL, true)], null, null], + ['d', [new Type(Type::BUILTIN_TYPE_BOOL)], null, null], + ['e', [new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_RESOURCE))], null, null], + ['f', [new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_OBJECT, false, 'DateTime'))], null, null], + ['g', [new Type(Type::BUILTIN_TYPE_ARRAY, true, null, true)], 'Nullable array.', null], + ['h', [new Type(Type::BUILTIN_TYPE_STRING, true)], null, null], + ['i', [new Type(Type::BUILTIN_TYPE_STRING, true), new Type(Type::BUILTIN_TYPE_INT, true)], null, null], + ['j', [new Type(Type::BUILTIN_TYPE_OBJECT, true, 'DateTime')], null, null], + ['donotexist', null, null, null], + ['staticGetter', null, null, null], + ['staticSetter', null, null, null], + ]; } public function typesWithNoPrefixesProvider() { - return array( - array('foo', null, 'Short description.', 'Long description.'), - array('bar', array(new Type(Type::BUILTIN_TYPE_STRING)), 'This is bar', null), - array('baz', array(new Type(Type::BUILTIN_TYPE_INT)), 'Should be used.', null), - array('foo2', array(new Type(Type::BUILTIN_TYPE_FLOAT)), null, null), - array('foo3', array(new Type(Type::BUILTIN_TYPE_CALLABLE)), null, null), - array('foo4', array(new Type(Type::BUILTIN_TYPE_NULL)), null, null), - array('foo5', null, null, null), - array( + return [ + ['foo', null, 'Short description.', 'Long description.'], + ['bar', [new Type(Type::BUILTIN_TYPE_STRING)], 'This is bar', null], + ['baz', [new Type(Type::BUILTIN_TYPE_INT)], 'Should be used.', null], + ['foo2', [new Type(Type::BUILTIN_TYPE_FLOAT)], null, null], + ['foo3', [new Type(Type::BUILTIN_TYPE_CALLABLE)], null, null], + ['foo4', [new Type(Type::BUILTIN_TYPE_NULL)], null, null], + ['foo5', null, null, null], + [ 'files', - array( + [ new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_OBJECT, false, 'SplFileInfo')), new Type(Type::BUILTIN_TYPE_RESOURCE), - ), + ], null, null, - ), - array('bal', array(new Type(Type::BUILTIN_TYPE_OBJECT, false, 'DateTime')), null, null), - array('parent', array(new Type(Type::BUILTIN_TYPE_OBJECT, false, 'Symfony\Component\PropertyInfo\Tests\Fixtures\ParentDummy')), null, null), - array('collection', array(new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_OBJECT, false, 'DateTime'))), null, null), - array('nestedCollection', array(new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_STRING, false)))), null, null), - array('mixedCollection', array(new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, null, null)), null, null), - array('a', null, 'A.', null), - array('b', null, 'B.', null), - array('c', null, null, null), - array('d', null, null, null), - array('e', null, null, null), - array('f', null, null, null), - array('g', array(new Type(Type::BUILTIN_TYPE_ARRAY, true, null, true)), 'Nullable array.', null), - array('h', array(new Type(Type::BUILTIN_TYPE_STRING, true)), null, null), - array('i', array(new Type(Type::BUILTIN_TYPE_STRING, true), new Type(Type::BUILTIN_TYPE_INT, true)), null, null), - array('j', array(new Type(Type::BUILTIN_TYPE_OBJECT, true, 'DateTime')), null, null), - array('donotexist', null, null, null), - array('staticGetter', null, null, null), - array('staticSetter', null, null, null), - ); + ], + ['bal', [new Type(Type::BUILTIN_TYPE_OBJECT, false, 'DateTime')], null, null], + ['parent', [new Type(Type::BUILTIN_TYPE_OBJECT, false, 'Symfony\Component\PropertyInfo\Tests\Fixtures\ParentDummy')], null, null], + ['collection', [new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_OBJECT, false, 'DateTime'))], null, null], + ['nestedCollection', [new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_STRING, false)))], null, null], + ['mixedCollection', [new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, null, null)], null, null], + ['a', null, 'A.', null], + ['b', null, 'B.', null], + ['c', null, null, null], + ['d', null, null, null], + ['e', null, null, null], + ['f', null, null, null], + ['g', [new Type(Type::BUILTIN_TYPE_ARRAY, true, null, true)], 'Nullable array.', null], + ['h', [new Type(Type::BUILTIN_TYPE_STRING, true)], null, null], + ['i', [new Type(Type::BUILTIN_TYPE_STRING, true), new Type(Type::BUILTIN_TYPE_INT, true)], null, null], + ['j', [new Type(Type::BUILTIN_TYPE_OBJECT, true, 'DateTime')], null, null], + ['donotexist', null, null, null], + ['staticGetter', null, null, null], + ['staticSetter', null, null, null], + ]; } public function testReturnNullOnEmptyDocBlock() @@ -227,17 +227,17 @@ class PhpDocExtractorTest extends TestCase public function dockBlockFallbackTypesProvider() { - return array( - 'pub' => array( - 'pub', array(new Type(Type::BUILTIN_TYPE_STRING)), - ), - 'protAcc' => array( - 'protAcc', array(new Type(Type::BUILTIN_TYPE_INT)), - ), - 'protMut' => array( - 'protMut', array(new Type(Type::BUILTIN_TYPE_BOOL)), - ), - ); + return [ + 'pub' => [ + 'pub', [new Type(Type::BUILTIN_TYPE_STRING)], + ], + 'protAcc' => [ + 'protAcc', [new Type(Type::BUILTIN_TYPE_INT)], + ], + 'protMut' => [ + 'protMut', [new Type(Type::BUILTIN_TYPE_BOOL)], + ], + ]; } /** diff --git a/src/Symfony/Component/PropertyInfo/Tests/Extractor/ReflectionExtractorTest.php b/src/Symfony/Component/PropertyInfo/Tests/Extractor/ReflectionExtractorTest.php index c9e6028d87..e58c70d41d 100644 --- a/src/Symfony/Component/PropertyInfo/Tests/Extractor/ReflectionExtractorTest.php +++ b/src/Symfony/Component/PropertyInfo/Tests/Extractor/ReflectionExtractorTest.php @@ -284,13 +284,13 @@ class ReflectionExtractorTest extends TestCase public function getInitializableProperties(): array { - return array( - array(Php71Dummy::class, 'string', true), - array(Php71Dummy::class, 'intPrivate', true), - array(Php71Dummy::class, 'notExist', false), - array(Php71DummyExtended2::class, 'intWithAccessor', true), - array(Php71DummyExtended2::class, 'intPrivate', false), - array(NotInstantiable::class, 'foo', false), - ); + return [ + [Php71Dummy::class, 'string', true], + [Php71Dummy::class, 'intPrivate', true], + [Php71Dummy::class, 'notExist', false], + [Php71DummyExtended2::class, 'intWithAccessor', true], + [Php71DummyExtended2::class, 'intPrivate', false], + [NotInstantiable::class, 'foo', false], + ]; } } diff --git a/src/Symfony/Component/PropertyInfo/Tests/Fixtures/DummyExtractor.php b/src/Symfony/Component/PropertyInfo/Tests/Fixtures/DummyExtractor.php index 3877f33415..9003b2fa38 100644 --- a/src/Symfony/Component/PropertyInfo/Tests/Fixtures/DummyExtractor.php +++ b/src/Symfony/Component/PropertyInfo/Tests/Fixtures/DummyExtractor.php @@ -74,7 +74,7 @@ class DummyExtractor implements PropertyListExtractorInterface, PropertyDescript /** * {@inheritdoc} */ - public function isInitializable(string $class, string $property, array $context = array()): ?bool + public function isInitializable(string $class, string $property, array $context = []): ?bool { return true; } diff --git a/src/Symfony/Component/PropertyInfo/Tests/Fixtures/NullExtractor.php b/src/Symfony/Component/PropertyInfo/Tests/Fixtures/NullExtractor.php index 6cf31ff2b4..6878db7cf3 100644 --- a/src/Symfony/Component/PropertyInfo/Tests/Fixtures/NullExtractor.php +++ b/src/Symfony/Component/PropertyInfo/Tests/Fixtures/NullExtractor.php @@ -80,7 +80,7 @@ class NullExtractor implements PropertyListExtractorInterface, PropertyDescripti /** * {@inheritdoc} */ - public function isInitializable(string $class, string $property, array $context = array()): ?bool + public function isInitializable(string $class, string $property, array $context = []): ?bool { return null; } diff --git a/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php b/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php index bbf57cfca1..2d12dcb968 100644 --- a/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php +++ b/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherDumper.php @@ -32,7 +32,7 @@ class PhpMatcherDumper extends MatcherDumper /** * @var ExpressionFunctionProviderInterface[] */ - private $expressionLanguageProviders = array(); + private $expressionLanguageProviders = []; /** * Dumps a set of routes to a PHP class. @@ -46,12 +46,12 @@ class PhpMatcherDumper extends MatcherDumper * * @return string A PHP class representing the matcher class */ - public function dump(array $options = array()) + public function dump(array $options = []) { - $options = array_replace(array( + $options = array_replace([ 'class' => 'ProjectUrlMatcher', 'base_class' => 'Symfony\\Component\\Routing\\Matcher\\UrlMatcher', - ), $options); + ], $options); // trailing slash support is only enabled if we know how to redirect the user $interfaces = class_implements($options['base_class']); @@ -98,7 +98,7 @@ EOF; $host = '/'.strtr(strrev($host), '}.{', '(/)'); } - $routes->addRoute($host ?: '/(.*)', array($name, $route)); + $routes->addRoute($host ?: '/(.*)', [$name, $route]); } if ($matchHost) { @@ -111,7 +111,7 @@ EOF; list($staticRoutes, $dynamicRoutes) = $this->groupStaticRoutes($routes); - $conditions = array(null); + $conditions = [null]; $code .= $this->compileStaticRoutes($staticRoutes, $conditions); $chunkLimit = \count($dynamicRoutes); @@ -154,7 +154,7 @@ EOF; */ private function groupStaticRoutes(RouteCollection $collection): array { - $staticRoutes = $dynamicRegex = array(); + $staticRoutes = $dynamicRegex = []; $dynamicRoutes = new RouteCollection(); foreach ($collection->all() as $name => $route) { @@ -175,20 +175,20 @@ EOF; } foreach ($dynamicRegex as list($hostRx, $rx)) { if (preg_match($rx, $url) && (!$host || !$hostRx || preg_match($hostRx, $host))) { - $dynamicRegex[] = array($hostRegex, $regex); + $dynamicRegex[] = [$hostRegex, $regex]; $dynamicRoutes->add($name, $route); continue 2; } } - $staticRoutes[$url][$name] = array($route, $hasTrailingSlash); + $staticRoutes[$url][$name] = [$route, $hasTrailingSlash]; } else { - $dynamicRegex[] = array($hostRegex, $regex); + $dynamicRegex[] = [$hostRegex, $regex]; $dynamicRoutes->add($name, $route); } } - return array($staticRoutes, $dynamicRoutes); + return [$staticRoutes, $dynamicRoutes]; } /** @@ -245,14 +245,14 @@ EOF; return ''; } $code = ''; - $state = (object) array( + $state = (object) [ 'regex' => '', 'routes' => '', 'mark' => 0, 'markTail' => 0, - 'hostVars' => array(), - 'vars' => array(), - ); + 'hostVars' => [], + 'vars' => [], + ]; $state->getVars = static function ($m) use ($state) { if ('_route' === $m[1]) { return '?:'; @@ -265,13 +265,13 @@ EOF; $chunkSize = 0; $prev = null; - $perModifiers = array(); + $perModifiers = []; foreach ($collection->all() as $name => $route) { preg_match('#[a-zA-Z]*$#', $route->compile()->getRegex(), $rx); if ($chunkLimit < ++$chunkSize || $prev !== $rx[0] && $route->compile()->getPathVariables()) { $chunkSize = 1; $routes = new RouteCollection(); - $perModifiers[] = array($rx[0], $routes); + $perModifiers[] = [$rx[0], $routes]; $prev = $rx[0]; } $routes->add($name, $route); @@ -279,12 +279,12 @@ EOF; foreach ($perModifiers as list($modifiers, $routes)) { $prev = false; - $perHost = array(); + $perHost = []; foreach ($routes->all() as $name => $route) { $regex = $route->compile()->getHostRegex(); if ($prev !== $regex) { $routes = new RouteCollection(); - $perHost[] = array($regex, $routes); + $perHost[] = [$regex, $routes]; $prev = $regex; } $routes->add($name, $route); @@ -299,12 +299,12 @@ EOF; if ($matchHost) { if ($hostRegex) { preg_match('#^.\^(.*)\$.[a-zA-Z]*$#', $hostRegex, $rx); - $state->vars = array(); + $state->vars = []; $hostRegex = '(?i:'.preg_replace_callback('#\?P<([^>]++)>#', $state->getVars, $rx[1]).')\.'; $state->hostVars = $state->vars; } else { $hostRegex = '(?:(?:[^./]*+\.)++)'; - $state->hostVars = array(); + $state->hostVars = []; } $state->mark += \strlen($rx = ($prev ? ')' : '')."|{$hostRegex}(?"); $code .= "\n .".self::export($rx); @@ -316,14 +316,14 @@ EOF; foreach ($routes->all() as $name => $route) { preg_match('#^.\^(.*)\$.[a-zA-Z]*$#', $route->compile()->getRegex(), $rx); - $state->vars = array(); + $state->vars = []; $regex = preg_replace_callback('#\?P<([^>]++)>#', $state->getVars, $rx[1]); if ($hasTrailingSlash = '/' !== $regex && '/' === $regex[-1]) { $regex = substr($regex, 0, -1); } $hasTrailingVar = (bool) preg_match('#\{\w+\}/?$#', $route->getPath()); - $tree->addRoute($regex, array($name, $regex, $state->vars, $route, $hasTrailingSlash, $hasTrailingVar)); + $tree->addRoute($regex, [$name, $regex, $state->vars, $route, $hasTrailingSlash, $hasTrailingVar]); } $code .= $this->compileStaticPrefixCollection($tree, $state, 0, $conditions); @@ -413,7 +413,7 @@ EOF; } if ($condition = $route->getCondition()) { - $condition = $this->getExpressionLanguage()->compile($condition, array('context', 'request')); + $condition = $this->getExpressionLanguage()->compile($condition, ['context', 'request']); $condition = $conditions[$condition] ?? $conditions[$condition] = (false !== strpos($condition, '$request') ? 1 : -1) * \count($conditions); } else { $condition = 'null'; @@ -421,7 +421,7 @@ EOF; return sprintf( " array(%s, %s, %s, %s, %s, %s, %s),\n", - self::export(array('_route' => $name) + $defaults), + self::export(['_route' => $name] + $defaults), self::export($vars), self::export(array_flip($route->getMethods()) ?: null), self::export(array_flip($route->getSchemes()) ?: null), diff --git a/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherTrait.php b/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherTrait.php index 40d6badf3b..7e370b9d20 100644 --- a/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherTrait.php +++ b/src/Symfony/Component/Routing/Matcher/Dumper/PhpMatcherTrait.php @@ -24,14 +24,14 @@ use Symfony\Component\Routing\Matcher\RedirectableUrlMatcherInterface; trait PhpMatcherTrait { private $matchHost = false; - private $staticRoutes = array(); - private $regexpList = array(); - private $dynamicRoutes = array(); + private $staticRoutes = []; + private $regexpList = []; + private $dynamicRoutes = []; private $checkCondition; public function match($pathinfo) { - $allow = $allowSchemes = array(); + $allow = $allowSchemes = []; if ($ret = $this->doMatch($pathinfo, $allow, $allowSchemes)) { return $ret; } @@ -41,7 +41,7 @@ trait PhpMatcherTrait if (!$this instanceof RedirectableUrlMatcherInterface) { throw new ResourceNotFoundException(); } - if (!\in_array($this->context->getMethod(), array('HEAD', 'GET'), true)) { + if (!\in_array($this->context->getMethod(), ['HEAD', 'GET'], true)) { // no-op } elseif ($allowSchemes) { redirect_scheme: @@ -67,9 +67,9 @@ trait PhpMatcherTrait throw new ResourceNotFoundException(); } - private function doMatch(string $pathinfo, array &$allow = array(), array &$allowSchemes = array()): array + private function doMatch(string $pathinfo, array &$allow = [], array &$allowSchemes = []): array { - $allow = $allowSchemes = array(); + $allow = $allowSchemes = []; $pathinfo = rawurldecode($pathinfo) ?: '/'; $trimmedPathinfo = rtrim($pathinfo, '/') ?: '/'; $context = $this->context; @@ -84,14 +84,14 @@ trait PhpMatcherTrait } $supportsRedirections = 'GET' === $canonicalMethod && $this instanceof RedirectableUrlMatcherInterface; - foreach ($this->staticRoutes[$trimmedPathinfo] ?? array() as list($ret, $requiredHost, $requiredMethods, $requiredSchemes, $hasTrailingSlash, , $condition)) { + foreach ($this->staticRoutes[$trimmedPathinfo] ?? [] as list($ret, $requiredHost, $requiredMethods, $requiredSchemes, $hasTrailingSlash, , $condition)) { if ($condition && !($this->checkCondition)($condition, $context, 0 < $condition ? $request ?? $request = $this->request ?: $this->createRequest($pathinfo) : null)) { continue; } if ('/' !== $pathinfo && $hasTrailingSlash === ($trimmedPathinfo === $pathinfo)) { if ($supportsRedirections && (!$requiredMethods || isset($requiredMethods['GET']))) { - return $allow = $allowSchemes = array(); + return $allow = $allowSchemes = []; } continue; } @@ -140,7 +140,7 @@ trait PhpMatcherTrait if ('/' !== $pathinfo && $hasTrailingSlash === ($trimmedPathinfo === $pathinfo)) { if ($supportsRedirections && (!$requiredMethods || isset($requiredMethods['GET']))) { - return $allow = $allowSchemes = array(); + return $allow = $allowSchemes = []; } if ($trimmedPathinfo === $pathinfo || !$hasTrailingVar) { continue; @@ -177,6 +177,6 @@ trait PhpMatcherTrait throw new NoConfigurationException(); } - return array(); + return []; } } diff --git a/src/Symfony/Component/Routing/Tests/Generator/Dumper/PhpGeneratorDumperTest.php b/src/Symfony/Component/Routing/Tests/Generator/Dumper/PhpGeneratorDumperTest.php index 45464c3a90..f38e30de98 100644 --- a/src/Symfony/Component/Routing/Tests/Generator/Dumper/PhpGeneratorDumperTest.php +++ b/src/Symfony/Component/Routing/Tests/Generator/Dumper/PhpGeneratorDumperTest.php @@ -73,10 +73,10 @@ class PhpGeneratorDumperTest extends TestCase $projectUrlGenerator = new \ProjectUrlGenerator(new RequestContext('/app.php')); - $absoluteUrlWithParameter = $projectUrlGenerator->generate('Test', array('foo' => 'bar'), UrlGeneratorInterface::ABSOLUTE_URL); - $absoluteUrlWithoutParameter = $projectUrlGenerator->generate('Test2', array(), UrlGeneratorInterface::ABSOLUTE_URL); - $relativeUrlWithParameter = $projectUrlGenerator->generate('Test', array('foo' => 'bar'), UrlGeneratorInterface::ABSOLUTE_PATH); - $relativeUrlWithoutParameter = $projectUrlGenerator->generate('Test2', array(), UrlGeneratorInterface::ABSOLUTE_PATH); + $absoluteUrlWithParameter = $projectUrlGenerator->generate('Test', ['foo' => 'bar'], UrlGeneratorInterface::ABSOLUTE_URL); + $absoluteUrlWithoutParameter = $projectUrlGenerator->generate('Test2', [], UrlGeneratorInterface::ABSOLUTE_URL); + $relativeUrlWithParameter = $projectUrlGenerator->generate('Test', ['foo' => 'bar'], UrlGeneratorInterface::ABSOLUTE_PATH); + $relativeUrlWithoutParameter = $projectUrlGenerator->generate('Test2', [], UrlGeneratorInterface::ABSOLUTE_PATH); $this->assertEquals('http://localhost/app.php/testing/bar', $absoluteUrlWithParameter); $this->assertEquals('http://localhost/app.php/testing2', $absoluteUrlWithoutParameter); @@ -90,9 +90,9 @@ class PhpGeneratorDumperTest extends TestCase $this->routeCollection->add('test.en', (new Route('/testing/is/fun'))->setDefault('_locale', 'en')->setDefault('_canonical_route', 'test')); $this->routeCollection->add('test.nl', (new Route('/testen/is/leuk'))->setDefault('_locale', 'nl')->setDefault('_canonical_route', 'test')); - $code = $this->generatorDumper->dump(array( + $code = $this->generatorDumper->dump([ 'class' => 'SimpleLocalizedProjectUrlGenerator', - )); + ]); file_put_contents($this->testTmpFilepath, $code); include $this->testTmpFilepath; @@ -100,7 +100,7 @@ class PhpGeneratorDumperTest extends TestCase $projectUrlGenerator = new \SimpleLocalizedProjectUrlGenerator($context, null, 'en'); $urlWithDefaultLocale = $projectUrlGenerator->generate('test'); - $urlWithSpecifiedLocale = $projectUrlGenerator->generate('test', array('_locale' => 'nl')); + $urlWithSpecifiedLocale = $projectUrlGenerator->generate('test', ['_locale' => 'nl']); $context->setParameter('_locale', 'en'); $urlWithEnglishContext = $projectUrlGenerator->generate('test'); $context->setParameter('_locale', 'nl'); @@ -127,9 +127,9 @@ class PhpGeneratorDumperTest extends TestCase { $this->routeCollection->add('test.en', (new Route('/testing/is/fun'))->setDefault('_locale', 'en')->setDefault('_canonical_route', 'test')); - $code = $this->generatorDumper->dump(array( + $code = $this->generatorDumper->dump([ 'class' => 'RouteNotFoundLocalizedProjectUrlGenerator', - )); + ]); file_put_contents($this->testTmpFilepath, $code); include $this->testTmpFilepath; @@ -143,9 +143,9 @@ class PhpGeneratorDumperTest extends TestCase $this->routeCollection->add('test.nl', (new Route('/testen/is/leuk'))->setDefault('_canonical_route', 'test')); $this->routeCollection->add('test.fr', (new Route('/tester/est/amusant'))->setDefault('_canonical_route', 'test')); - $code = $this->generatorDumper->dump(array( + $code = $this->generatorDumper->dump([ 'class' => 'FallbackLocaleLocalizedProjectUrlGenerator', - )); + ]); file_put_contents($this->testTmpFilepath, $code); include $this->testTmpFilepath; @@ -156,7 +156,7 @@ class PhpGeneratorDumperTest extends TestCase // test with context _locale $this->assertEquals('/app.php/testing/is/fun', $projectUrlGenerator->generate('test')); // test with parameters _locale - $this->assertEquals('/app.php/testen/is/leuk', $projectUrlGenerator->generate('test', array('_locale' => 'nl_BE'))); + $this->assertEquals('/app.php/testen/is/leuk', $projectUrlGenerator->generate('test', ['_locale' => 'nl_BE'])); $projectUrlGenerator = new \FallbackLocaleLocalizedProjectUrlGenerator(new RequestContext('/app.php'), null, 'fr_CA'); // test with default locale @@ -171,18 +171,18 @@ class PhpGeneratorDumperTest extends TestCase } $this->routeCollection->add('Test2', new Route('/testing2')); - file_put_contents($this->largeTestTmpFilepath, $this->generatorDumper->dump(array( + file_put_contents($this->largeTestTmpFilepath, $this->generatorDumper->dump([ 'class' => 'ProjectLargeUrlGenerator', - ))); + ])); $this->routeCollection = $this->generatorDumper = null; include $this->largeTestTmpFilepath; $projectUrlGenerator = new \ProjectLargeUrlGenerator(new RequestContext('/app.php')); - $absoluteUrlWithParameter = $projectUrlGenerator->generate('Test', array('foo' => 'bar'), UrlGeneratorInterface::ABSOLUTE_URL); - $absoluteUrlWithoutParameter = $projectUrlGenerator->generate('Test2', array(), UrlGeneratorInterface::ABSOLUTE_URL); - $relativeUrlWithParameter = $projectUrlGenerator->generate('Test', array('foo' => 'bar'), UrlGeneratorInterface::ABSOLUTE_PATH); - $relativeUrlWithoutParameter = $projectUrlGenerator->generate('Test2', array(), UrlGeneratorInterface::ABSOLUTE_PATH); + $absoluteUrlWithParameter = $projectUrlGenerator->generate('Test', ['foo' => 'bar'], UrlGeneratorInterface::ABSOLUTE_URL); + $absoluteUrlWithoutParameter = $projectUrlGenerator->generate('Test2', [], UrlGeneratorInterface::ABSOLUTE_URL); + $relativeUrlWithParameter = $projectUrlGenerator->generate('Test', ['foo' => 'bar'], UrlGeneratorInterface::ABSOLUTE_PATH); + $relativeUrlWithoutParameter = $projectUrlGenerator->generate('Test2', [], UrlGeneratorInterface::ABSOLUTE_PATH); $this->assertEquals('http://localhost/app.php/testing/bar', $absoluteUrlWithParameter); $this->assertEquals('http://localhost/app.php/testing2', $absoluteUrlWithoutParameter); @@ -195,12 +195,12 @@ class PhpGeneratorDumperTest extends TestCase */ public function testDumpWithoutRoutes() { - file_put_contents($this->testTmpFilepath, $this->generatorDumper->dump(array('class' => 'WithoutRoutesUrlGenerator'))); + file_put_contents($this->testTmpFilepath, $this->generatorDumper->dump(['class' => 'WithoutRoutesUrlGenerator'])); include $this->testTmpFilepath; $projectUrlGenerator = new \WithoutRoutesUrlGenerator(new RequestContext('/app.php')); - $projectUrlGenerator->generate('Test', array()); + $projectUrlGenerator->generate('Test', []); } /** @@ -210,45 +210,45 @@ class PhpGeneratorDumperTest extends TestCase { $this->routeCollection->add('Test', new Route('/test')); - file_put_contents($this->testTmpFilepath, $this->generatorDumper->dump(array('class' => 'NonExistingRoutesUrlGenerator'))); + file_put_contents($this->testTmpFilepath, $this->generatorDumper->dump(['class' => 'NonExistingRoutesUrlGenerator'])); include $this->testTmpFilepath; $projectUrlGenerator = new \NonExistingRoutesUrlGenerator(new RequestContext()); - $url = $projectUrlGenerator->generate('NonExisting', array()); + $url = $projectUrlGenerator->generate('NonExisting', []); } public function testDumpForRouteWithDefaults() { - $this->routeCollection->add('Test', new Route('/testing/{foo}', array('foo' => 'bar'))); + $this->routeCollection->add('Test', new Route('/testing/{foo}', ['foo' => 'bar'])); - file_put_contents($this->testTmpFilepath, $this->generatorDumper->dump(array('class' => 'DefaultRoutesUrlGenerator'))); + file_put_contents($this->testTmpFilepath, $this->generatorDumper->dump(['class' => 'DefaultRoutesUrlGenerator'])); include $this->testTmpFilepath; $projectUrlGenerator = new \DefaultRoutesUrlGenerator(new RequestContext()); - $url = $projectUrlGenerator->generate('Test', array()); + $url = $projectUrlGenerator->generate('Test', []); $this->assertEquals('/testing', $url); } public function testDumpWithSchemeRequirement() { - $this->routeCollection->add('Test1', new Route('/testing', array(), array(), array(), '', array('ftp', 'https'))); + $this->routeCollection->add('Test1', new Route('/testing', [], [], [], '', ['ftp', 'https'])); - file_put_contents($this->testTmpFilepath, $this->generatorDumper->dump(array('class' => 'SchemeUrlGenerator'))); + file_put_contents($this->testTmpFilepath, $this->generatorDumper->dump(['class' => 'SchemeUrlGenerator'])); include $this->testTmpFilepath; $projectUrlGenerator = new \SchemeUrlGenerator(new RequestContext('/app.php')); - $absoluteUrl = $projectUrlGenerator->generate('Test1', array(), UrlGeneratorInterface::ABSOLUTE_URL); - $relativeUrl = $projectUrlGenerator->generate('Test1', array(), UrlGeneratorInterface::ABSOLUTE_PATH); + $absoluteUrl = $projectUrlGenerator->generate('Test1', [], UrlGeneratorInterface::ABSOLUTE_URL); + $relativeUrl = $projectUrlGenerator->generate('Test1', [], UrlGeneratorInterface::ABSOLUTE_PATH); $this->assertEquals('ftp://localhost/app.php/testing', $absoluteUrl); $this->assertEquals('ftp://localhost/app.php/testing', $relativeUrl); $projectUrlGenerator = new \SchemeUrlGenerator(new RequestContext('/app.php', 'GET', 'localhost', 'https')); - $absoluteUrl = $projectUrlGenerator->generate('Test1', array(), UrlGeneratorInterface::ABSOLUTE_URL); - $relativeUrl = $projectUrlGenerator->generate('Test1', array(), UrlGeneratorInterface::ABSOLUTE_PATH); + $absoluteUrl = $projectUrlGenerator->generate('Test1', [], UrlGeneratorInterface::ABSOLUTE_URL); + $relativeUrl = $projectUrlGenerator->generate('Test1', [], UrlGeneratorInterface::ABSOLUTE_PATH); $this->assertEquals('https://localhost/app.php/testing', $absoluteUrl); $this->assertEquals('/app.php/testing', $relativeUrl); diff --git a/src/Symfony/Component/Routing/Tests/Loader/YamlFileLoaderTest.php b/src/Symfony/Component/Routing/Tests/Loader/YamlFileLoaderTest.php index f51d48ea18..296bbe4226 100644 --- a/src/Symfony/Component/Routing/Tests/Loader/YamlFileLoaderTest.php +++ b/src/Symfony/Component/Routing/Tests/Loader/YamlFileLoaderTest.php @@ -311,7 +311,7 @@ class YamlFileLoaderTest extends TestCase */ public function testRequirementsWithoutPlaceholderName() { - $loader = new YamlFileLoader(new FileLocator(array(__DIR__.'/../Fixtures'))); + $loader = new YamlFileLoader(new FileLocator([__DIR__.'/../Fixtures'])); $loader->load('requirements_without_placeholder_name.yml'); } } diff --git a/src/Symfony/Component/Security/Core/Authorization/TraceableAccessDecisionManager.php b/src/Symfony/Component/Security/Core/Authorization/TraceableAccessDecisionManager.php index e435ba3d1a..319d2d866c 100644 --- a/src/Symfony/Component/Security/Core/Authorization/TraceableAccessDecisionManager.php +++ b/src/Symfony/Component/Security/Core/Authorization/TraceableAccessDecisionManager.php @@ -26,9 +26,9 @@ class TraceableAccessDecisionManager implements AccessDecisionManagerInterface { private $manager; private $strategy; - private $voters = array(); - private $decisionLog = array(); // All decision logs - private $currentLog = array(); // Logs being filled in + private $voters = []; + private $decisionLog = []; // All decision logs + private $currentLog = []; // Logs being filled in public function __construct(AccessDecisionManagerInterface $manager) { @@ -50,11 +50,11 @@ class TraceableAccessDecisionManager implements AccessDecisionManagerInterface */ public function decide(TokenInterface $token, array $attributes, $object = null) { - $currentDecisionLog = array( + $currentDecisionLog = [ 'attributes' => $attributes, 'object' => $object, - 'voterDetails' => array(), - ); + 'voterDetails' => [], + ]; $this->currentLog[] = &$currentDecisionLog; @@ -77,11 +77,11 @@ class TraceableAccessDecisionManager implements AccessDecisionManagerInterface public function addVoterVote(VoterInterface $voter, array $attributes, int $vote) { $currentLogIndex = \count($this->currentLog) - 1; - $this->currentLog[$currentLogIndex]['voterDetails'][] = array( + $this->currentLog[$currentLogIndex]['voterDetails'][] = [ 'voter' => $voter, 'attributes' => $attributes, 'vote' => $vote, - ); + ]; } /** diff --git a/src/Symfony/Component/Security/Core/Authorization/Voter/ExpressionVoter.php b/src/Symfony/Component/Security/Core/Authorization/Voter/ExpressionVoter.php index 131f5efe20..d9530e071c 100644 --- a/src/Symfony/Component/Security/Core/Authorization/Voter/ExpressionVoter.php +++ b/src/Symfony/Component/Security/Core/Authorization/Voter/ExpressionVoter.php @@ -96,7 +96,7 @@ class ExpressionVoter implements VoterInterface $roles = $token->getRoles(); } - $variables = array( + $variables = [ 'token' => $token, 'user' => $token->getUser(), 'object' => $subject, @@ -104,7 +104,7 @@ class ExpressionVoter implements VoterInterface 'roles' => array_map(function ($role) { return $role->getRole(); }, $roles), 'trust_resolver' => $this->trustResolver, 'auth_checker' => $this->authChecker, - ); + ]; // this is mainly to propose a better experience when the expression is used // in an access control rule, as the developer does not know that it's going diff --git a/src/Symfony/Component/Security/Core/Tests/Authorization/ExpressionLanguageTest.php b/src/Symfony/Component/Security/Core/Tests/Authorization/ExpressionLanguageTest.php index 59eb1ab5cb..2950d3feff 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authorization/ExpressionLanguageTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authorization/ExpressionLanguageTest.php @@ -35,10 +35,10 @@ class ExpressionLanguageTest extends TestCase $trustResolver = new AuthenticationTrustResolver(); $tokenStorage = new TokenStorage(); $tokenStorage->setToken($token); - $accessDecisionManager = new AccessDecisionManager(array(new RoleVoter())); + $accessDecisionManager = new AccessDecisionManager([new RoleVoter()]); $authChecker = new AuthorizationChecker($tokenStorage, $this->getMockBuilder(AuthenticationManagerInterface::class)->getMock(), $accessDecisionManager); - $context = array(); + $context = []; $context['trust_resolver'] = $trustResolver; $context['auth_checker'] = $authChecker; $context['token'] = $token; @@ -48,7 +48,7 @@ class ExpressionLanguageTest extends TestCase public function provider() { - $roles = array('ROLE_USER', 'ROLE_ADMIN'); + $roles = ['ROLE_USER', 'ROLE_ADMIN']; $user = new User('username', 'password', $roles); $noToken = null; @@ -56,57 +56,57 @@ class ExpressionLanguageTest extends TestCase $rememberMeToken = new RememberMeToken($user, 'providerkey', 'firewall'); $usernamePasswordToken = new UsernamePasswordToken('username', 'password', 'providerkey', $roles); - return array( - array($noToken, 'is_anonymous()', false), - array($noToken, 'is_authenticated()', false), - array($noToken, 'is_fully_authenticated()', false), - array($noToken, 'is_remember_me()', false), + return [ + [$noToken, 'is_anonymous()', false], + [$noToken, 'is_authenticated()', false], + [$noToken, 'is_fully_authenticated()', false], + [$noToken, 'is_remember_me()', false], - array($anonymousToken, 'is_anonymous()', true), - array($anonymousToken, 'is_authenticated()', false), - array($anonymousToken, 'is_fully_authenticated()', false), - array($anonymousToken, 'is_remember_me()', false), - array($anonymousToken, "is_granted('ROLE_USER')", false), + [$anonymousToken, 'is_anonymous()', true], + [$anonymousToken, 'is_authenticated()', false], + [$anonymousToken, 'is_fully_authenticated()', false], + [$anonymousToken, 'is_remember_me()', false], + [$anonymousToken, "is_granted('ROLE_USER')", false], - array($rememberMeToken, 'is_anonymous()', false), - array($rememberMeToken, 'is_authenticated()', true), - array($rememberMeToken, 'is_fully_authenticated()', false), - array($rememberMeToken, 'is_remember_me()', true), - array($rememberMeToken, "is_granted('ROLE_FOO')", false), - array($rememberMeToken, "is_granted('ROLE_USER')", true), + [$rememberMeToken, 'is_anonymous()', false], + [$rememberMeToken, 'is_authenticated()', true], + [$rememberMeToken, 'is_fully_authenticated()', false], + [$rememberMeToken, 'is_remember_me()', true], + [$rememberMeToken, "is_granted('ROLE_FOO')", false], + [$rememberMeToken, "is_granted('ROLE_USER')", true], - array($usernamePasswordToken, 'is_anonymous()', false), - array($usernamePasswordToken, 'is_authenticated()', true), - array($usernamePasswordToken, 'is_fully_authenticated()', true), - array($usernamePasswordToken, 'is_remember_me()', false), - array($usernamePasswordToken, "is_granted('ROLE_FOO')", false), - array($usernamePasswordToken, "is_granted('ROLE_USER')", true), - ); + [$usernamePasswordToken, 'is_anonymous()', false], + [$usernamePasswordToken, 'is_authenticated()', true], + [$usernamePasswordToken, 'is_fully_authenticated()', true], + [$usernamePasswordToken, 'is_remember_me()', false], + [$usernamePasswordToken, "is_granted('ROLE_FOO')", false], + [$usernamePasswordToken, "is_granted('ROLE_USER')", true], + ]; } /** * @dataProvider provideLegacyHasRole * @group legacy */ - public function testLegacyHasRole($expression, $result, $roles = array()) + public function testLegacyHasRole($expression, $result, $roles = []) { $expressionLanguage = new ExpressionLanguage(); - $context = array('roles' => $roles); + $context = ['roles' => $roles]; $this->assertEquals($result, $expressionLanguage->evaluate($expression, $context)); } public function provideLegacyHasRole() { - $roles = array('ROLE_USER', 'ROLE_ADMIN'); + $roles = ['ROLE_USER', 'ROLE_ADMIN']; - return array( - array("has_role('ROLE_FOO')", false), - array("has_role('ROLE_USER')", false), - array("has_role('ROLE_ADMIN')", false), - array("has_role('ROLE_FOO')", false, $roles), - array("has_role('ROLE_USER')", true, $roles), - array("has_role('ROLE_ADMIN')", true, $roles), - ); + return [ + ["has_role('ROLE_FOO')", false], + ["has_role('ROLE_USER')", false], + ["has_role('ROLE_ADMIN')", false], + ["has_role('ROLE_FOO')", false, $roles], + ["has_role('ROLE_USER')", true, $roles], + ["has_role('ROLE_ADMIN')", true, $roles], + ]; } } diff --git a/src/Symfony/Component/Security/Core/Tests/Authorization/TraceableAccessDecisionManagerTest.php b/src/Symfony/Component/Security/Core/Tests/Authorization/TraceableAccessDecisionManagerTest.php index c8875701b8..5df07a2248 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authorization/TraceableAccessDecisionManagerTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authorization/TraceableAccessDecisionManagerTest.php @@ -29,7 +29,7 @@ class TraceableAccessDecisionManagerTest extends TestCase $admMock = $this ->getMockBuilder(AccessDecisionManager::class) - ->setMethods(array('decide')) + ->setMethods(['decide']) ->getMock(); $adm = new TraceableAccessDecisionManager($admMock); @@ -58,120 +58,120 @@ class TraceableAccessDecisionManagerTest extends TestCase $voter1 = $this->getMockForAbstractClass(VoterInterface::class); $voter2 = $this->getMockForAbstractClass(VoterInterface::class); - yield array( - array(array( - 'attributes' => array('ATTRIBUTE_1'), + yield [ + [[ + 'attributes' => ['ATTRIBUTE_1'], 'object' => null, 'result' => true, - 'voterDetails' => array( - array('voter' => $voter1, 'attributes' => array('ATTRIBUTE_1'), 'vote' => VoterInterface::ACCESS_GRANTED), - array('voter' => $voter2, 'attributes' => array('ATTRIBUTE_1'), 'vote' => VoterInterface::ACCESS_GRANTED), - ), - )), - array('ATTRIBUTE_1'), + 'voterDetails' => [ + ['voter' => $voter1, 'attributes' => ['ATTRIBUTE_1'], 'vote' => VoterInterface::ACCESS_GRANTED], + ['voter' => $voter2, 'attributes' => ['ATTRIBUTE_1'], 'vote' => VoterInterface::ACCESS_GRANTED], + ], + ]], + ['ATTRIBUTE_1'], null, - array( - array($voter1, VoterInterface::ACCESS_GRANTED), - array($voter2, VoterInterface::ACCESS_GRANTED), - ), + [ + [$voter1, VoterInterface::ACCESS_GRANTED], + [$voter2, VoterInterface::ACCESS_GRANTED], + ], true, - ); - yield array( - array(array( - 'attributes' => array('ATTRIBUTE_1', 'ATTRIBUTE_2'), + ]; + yield [ + [[ + 'attributes' => ['ATTRIBUTE_1', 'ATTRIBUTE_2'], 'object' => true, 'result' => false, - 'voterDetails' => array( - array('voter' => $voter1, 'attributes' => array('ATTRIBUTE_1', 'ATTRIBUTE_2'), 'vote' => VoterInterface::ACCESS_ABSTAIN), - array('voter' => $voter2, 'attributes' => array('ATTRIBUTE_1', 'ATTRIBUTE_2'), 'vote' => VoterInterface::ACCESS_GRANTED), - ), - )), - array('ATTRIBUTE_1', 'ATTRIBUTE_2'), + 'voterDetails' => [ + ['voter' => $voter1, 'attributes' => ['ATTRIBUTE_1', 'ATTRIBUTE_2'], 'vote' => VoterInterface::ACCESS_ABSTAIN], + ['voter' => $voter2, 'attributes' => ['ATTRIBUTE_1', 'ATTRIBUTE_2'], 'vote' => VoterInterface::ACCESS_GRANTED], + ], + ]], + ['ATTRIBUTE_1', 'ATTRIBUTE_2'], true, - array( - array($voter1, VoterInterface::ACCESS_ABSTAIN), - array($voter2, VoterInterface::ACCESS_GRANTED), - ), + [ + [$voter1, VoterInterface::ACCESS_ABSTAIN], + [$voter2, VoterInterface::ACCESS_GRANTED], + ], false, - ); - yield array( - array(array( - 'attributes' => array(null), + ]; + yield [ + [[ + 'attributes' => [null], 'object' => 'jolie string', 'result' => false, - 'voterDetails' => array( - array('voter' => $voter1, 'attributes' => array(null), 'vote' => VoterInterface::ACCESS_ABSTAIN), - array('voter' => $voter2, 'attributes' => array(null), 'vote' => VoterInterface::ACCESS_DENIED), - ), - )), - array(null), + 'voterDetails' => [ + ['voter' => $voter1, 'attributes' => [null], 'vote' => VoterInterface::ACCESS_ABSTAIN], + ['voter' => $voter2, 'attributes' => [null], 'vote' => VoterInterface::ACCESS_DENIED], + ], + ]], + [null], 'jolie string', - array( - array($voter1, VoterInterface::ACCESS_ABSTAIN), - array($voter2, VoterInterface::ACCESS_DENIED), - ), + [ + [$voter1, VoterInterface::ACCESS_ABSTAIN], + [$voter2, VoterInterface::ACCESS_DENIED], + ], false, - ); - yield array( - array(array( - 'attributes' => array(12), + ]; + yield [ + [[ + 'attributes' => [12], 'object' => 12345, 'result' => true, - 'voterDetails' => array(), - )), - 'attributes' => array(12), + 'voterDetails' => [], + ]], + 'attributes' => [12], 12345, - array(), + [], true, - ); - yield array( - array(array( - 'attributes' => array(new \stdClass()), + ]; + yield [ + [[ + 'attributes' => [new \stdClass()], 'object' => $x = fopen(__FILE__, 'rb'), 'result' => true, - 'voterDetails' => array(), - )), - array(new \stdClass()), + 'voterDetails' => [], + ]], + [new \stdClass()], $x, - array(), + [], true, - ); - yield array( - array(array( - 'attributes' => array('ATTRIBUTE_2'), - 'object' => $x = array(), + ]; + yield [ + [[ + 'attributes' => ['ATTRIBUTE_2'], + 'object' => $x = [], 'result' => false, - 'voterDetails' => array( - array('voter' => $voter1, 'attributes' => array('ATTRIBUTE_2'), 'vote' => VoterInterface::ACCESS_ABSTAIN), - array('voter' => $voter2, 'attributes' => array('ATTRIBUTE_2'), 'vote' => VoterInterface::ACCESS_ABSTAIN), - ), - )), - array('ATTRIBUTE_2'), + 'voterDetails' => [ + ['voter' => $voter1, 'attributes' => ['ATTRIBUTE_2'], 'vote' => VoterInterface::ACCESS_ABSTAIN], + ['voter' => $voter2, 'attributes' => ['ATTRIBUTE_2'], 'vote' => VoterInterface::ACCESS_ABSTAIN], + ], + ]], + ['ATTRIBUTE_2'], $x, - array( - array($voter1, VoterInterface::ACCESS_ABSTAIN), - array($voter2, VoterInterface::ACCESS_ABSTAIN), - ), + [ + [$voter1, VoterInterface::ACCESS_ABSTAIN], + [$voter2, VoterInterface::ACCESS_ABSTAIN], + ], false, - ); - yield array( - array(array( - 'attributes' => array(12.13), + ]; + yield [ + [[ + 'attributes' => [12.13], 'object' => new \stdClass(), 'result' => false, - 'voterDetails' => array( - array('voter' => $voter1, 'attributes' => array(12.13), 'vote' => VoterInterface::ACCESS_DENIED), - array('voter' => $voter2, 'attributes' => array(12.13), 'vote' => VoterInterface::ACCESS_DENIED), - ), - )), - array(12.13), + 'voterDetails' => [ + ['voter' => $voter1, 'attributes' => [12.13], 'vote' => VoterInterface::ACCESS_DENIED], + ['voter' => $voter2, 'attributes' => [12.13], 'vote' => VoterInterface::ACCESS_DENIED], + ], + ]], + [12.13], new \stdClass(), - array( - array($voter1, VoterInterface::ACCESS_DENIED), - array($voter2, VoterInterface::ACCESS_DENIED), - ), + [ + [$voter1, VoterInterface::ACCESS_DENIED], + [$voter2, VoterInterface::ACCESS_DENIED], + ], false, - ); + ]; } public function testDebugAccessDecisionManagerAliasExistsForBC() @@ -188,20 +188,20 @@ class TraceableAccessDecisionManagerTest extends TestCase { $voter1 = $this ->getMockBuilder(VoterInterface::class) - ->setMethods(array('vote')) + ->setMethods(['vote']) ->getMock(); $voter2 = $this ->getMockBuilder(VoterInterface::class) - ->setMethods(array('vote')) + ->setMethods(['vote']) ->getMock(); $voter3 = $this ->getMockBuilder(VoterInterface::class) - ->setMethods(array('vote')) + ->setMethods(['vote']) ->getMock(); - $sut = new TraceableAccessDecisionManager(new AccessDecisionManager(array($voter1, $voter2, $voter3))); + $sut = new TraceableAccessDecisionManager(new AccessDecisionManager([$voter1, $voter2, $voter3])); $voter1 ->expects($this->any()) @@ -244,37 +244,37 @@ class TraceableAccessDecisionManagerTest extends TestCase }); $token = $this->getMockBuilder(TokenInterface::class)->getMock(); - $sut->decide($token, array('attr1'), null); - $sut->decide($token, array('attr2'), $obj = new \stdClass()); + $sut->decide($token, ['attr1'], null); + $sut->decide($token, ['attr2'], $obj = new \stdClass()); - $this->assertEquals(array( - array( - 'attributes' => array('attr1'), + $this->assertEquals([ + [ + 'attributes' => ['attr1'], 'object' => null, - 'voterDetails' => array( - array('voter' => $voter1, 'attributes' => array('attr1'), 'vote' => VoterInterface::ACCESS_GRANTED), - ), + 'voterDetails' => [ + ['voter' => $voter1, 'attributes' => ['attr1'], 'vote' => VoterInterface::ACCESS_GRANTED], + ], 'result' => true, - ), - array( - 'attributes' => array('attr2'), + ], + [ + 'attributes' => ['attr2'], 'object' => null, - 'voterDetails' => array( - array('voter' => $voter1, 'attributes' => array('attr2'), 'vote' => VoterInterface::ACCESS_ABSTAIN), - array('voter' => $voter2, 'attributes' => array('attr2'), 'vote' => VoterInterface::ACCESS_GRANTED), - ), + 'voterDetails' => [ + ['voter' => $voter1, 'attributes' => ['attr2'], 'vote' => VoterInterface::ACCESS_ABSTAIN], + ['voter' => $voter2, 'attributes' => ['attr2'], 'vote' => VoterInterface::ACCESS_GRANTED], + ], 'result' => true, - ), - array( - 'attributes' => array('attr2'), + ], + [ + 'attributes' => ['attr2'], 'object' => $obj, - 'voterDetails' => array( - array('voter' => $voter1, 'attributes' => array('attr2'), 'vote' => VoterInterface::ACCESS_ABSTAIN), - array('voter' => $voter2, 'attributes' => array('attr2'), 'vote' => VoterInterface::ACCESS_DENIED), - array('voter' => $voter3, 'attributes' => array('attr2'), 'vote' => VoterInterface::ACCESS_GRANTED), - ), + 'voterDetails' => [ + ['voter' => $voter1, 'attributes' => ['attr2'], 'vote' => VoterInterface::ACCESS_ABSTAIN], + ['voter' => $voter2, 'attributes' => ['attr2'], 'vote' => VoterInterface::ACCESS_DENIED], + ['voter' => $voter3, 'attributes' => ['attr2'], 'vote' => VoterInterface::ACCESS_GRANTED], + ], 'result' => true, - ), - ), $sut->getDecisionLog()); + ], + ], $sut->getDecisionLog()); } } diff --git a/src/Symfony/Component/Security/Core/Tests/Authorization/Voter/TraceableVoterTest.php b/src/Symfony/Component/Security/Core/Tests/Authorization/Voter/TraceableVoterTest.php index 8d8ba18151..99bf1f6eff 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authorization/Voter/TraceableVoterTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authorization/Voter/TraceableVoterTest.php @@ -38,16 +38,16 @@ class TraceableVoterTest extends TestCase $voter ->expects($this->once()) ->method('vote') - ->with($token, 'anysubject', array('attr1')) + ->with($token, 'anysubject', ['attr1']) ->willReturn(VoterInterface::ACCESS_DENIED); $eventDispatcher ->expects($this->once()) ->method('dispatch') - ->with('debug.security.authorization.vote', new VoteEvent($voter, 'anysubject', array('attr1'), VoterInterface::ACCESS_DENIED)); + ->with('debug.security.authorization.vote', new VoteEvent($voter, 'anysubject', ['attr1'], VoterInterface::ACCESS_DENIED)); $sut = new TraceableVoter($voter, $eventDispatcher); - $result = $sut->vote($token, 'anysubject', array('attr1')); + $result = $sut->vote($token, 'anysubject', ['attr1']); $this->assertSame(VoterInterface::ACCESS_DENIED, $result); } diff --git a/src/Symfony/Component/Security/Core/User/LdapUserProvider.php b/src/Symfony/Component/Security/Core/User/LdapUserProvider.php index 01b6b6d3d3..adb820fcca 100644 --- a/src/Symfony/Component/Security/Core/User/LdapUserProvider.php +++ b/src/Symfony/Component/Security/Core/User/LdapUserProvider.php @@ -35,7 +35,7 @@ class LdapUserProvider implements UserProviderInterface private $defaultSearch; private $passwordAttribute; - public function __construct(LdapInterface $ldap, string $baseDn, string $searchDn = null, string $searchPassword = null, array $defaultRoles = array(), string $uidKey = null, string $filter = null, string $passwordAttribute = null) + public function __construct(LdapInterface $ldap, string $baseDn, string $searchDn = null, string $searchPassword = null, array $defaultRoles = [], string $uidKey = null, string $filter = null, string $passwordAttribute = null) { if (null === $uidKey) { $uidKey = 'sAMAccountName'; diff --git a/src/Symfony/Component/Security/Http/Tests/FirewallTest.php b/src/Symfony/Component/Security/Http/Tests/FirewallTest.php index bc7db4d506..7a601f6050 100644 --- a/src/Symfony/Component/Security/Http/Tests/FirewallTest.php +++ b/src/Symfony/Component/Security/Http/Tests/FirewallTest.php @@ -41,7 +41,7 @@ class FirewallTest extends TestCase ->expects($this->once()) ->method('getListeners') ->with($this->equalTo($request)) - ->will($this->returnValue(array(array(), $listener, null))) + ->will($this->returnValue([[], $listener, null])) ; $event = new GetResponseEvent($this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(), $request, HttpKernelInterface::MASTER_REQUEST); @@ -70,16 +70,16 @@ class FirewallTest extends TestCase $map ->expects($this->once()) ->method('getListeners') - ->will($this->returnValue(array(array($first, $second), null, null))) + ->will($this->returnValue([[$first, $second], null, null])) ; $event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent') - ->setMethods(array('hasResponse')) - ->setConstructorArgs(array( + ->setMethods(['hasResponse']) + ->setConstructorArgs([ $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(), $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->disableOriginalConstructor()->disableOriginalClone()->getMock(), HttpKernelInterface::MASTER_REQUEST, - )) + ]) ->getMock() ; $event @@ -134,7 +134,7 @@ class FirewallTest extends TestCase ->expects($this->once()) ->method('getListeners') ->with($this->equalTo($request)) - ->willReturn(array(array(), $listener)) + ->willReturn([[], $listener]) ; $firewall = new Firewall($map, $dispatcher); diff --git a/src/Symfony/Component/Security/Http/Tests/RememberMe/PersistentTokenBasedRememberMeServicesTest.php b/src/Symfony/Component/Security/Http/Tests/RememberMe/PersistentTokenBasedRememberMeServicesTest.php index 5405bc1b04..506cfea61c 100644 --- a/src/Symfony/Component/Security/Http/Tests/RememberMe/PersistentTokenBasedRememberMeServicesTest.php +++ b/src/Symfony/Component/Security/Http/Tests/RememberMe/PersistentTokenBasedRememberMeServicesTest.php @@ -36,14 +36,14 @@ class PersistentTokenBasedRememberMeServicesTest extends TestCase public function testAutoLoginReturnsNullWhenNoCookie() { - $service = $this->getService(null, array('name' => 'foo')); + $service = $this->getService(null, ['name' => 'foo']); $this->assertNull($service->autoLogin(new Request())); } public function testAutoLoginThrowsExceptionOnInvalidCookie() { - $service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => false, 'remember_me_parameter' => 'foo')); + $service = $this->getService(null, ['name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => false, 'remember_me_parameter' => 'foo']); $request = new Request(); $request->request->set('foo', 'true'); $request->cookies->set('foo', 'foo'); @@ -54,13 +54,13 @@ class PersistentTokenBasedRememberMeServicesTest extends TestCase public function testAutoLoginThrowsExceptionOnNonExistentToken() { - $service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => false, 'remember_me_parameter' => 'foo')); + $service = $this->getService(null, ['name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => false, 'remember_me_parameter' => 'foo']); $request = new Request(); $request->request->set('foo', 'true'); - $request->cookies->set('foo', $this->encodeCookie(array( + $request->cookies->set('foo', $this->encodeCookie([ $series = 'fooseries', $tokenValue = 'foovalue', - ))); + ])); $tokenProvider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface')->getMock(); $tokenProvider @@ -77,9 +77,9 @@ class PersistentTokenBasedRememberMeServicesTest extends TestCase public function testAutoLoginReturnsNullOnNonExistentUser() { $userProvider = $this->getProvider(); - $service = $this->getService($userProvider, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true, 'lifetime' => 3600, 'secure' => false, 'httponly' => false)); + $service = $this->getService($userProvider, ['name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true, 'lifetime' => 3600, 'secure' => false, 'httponly' => false]); $request = new Request(); - $request->cookies->set('foo', $this->encodeCookie(array('fooseries', 'foovalue'))); + $request->cookies->set('foo', $this->encodeCookie(['fooseries', 'foovalue'])); $tokenProvider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface')->getMock(); $tokenProvider @@ -102,9 +102,9 @@ class PersistentTokenBasedRememberMeServicesTest extends TestCase public function testAutoLoginThrowsExceptionOnStolenCookieAndRemovesItFromThePersistentBackend() { $userProvider = $this->getProvider(); - $service = $this->getService($userProvider, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true)); + $service = $this->getService($userProvider, ['name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true]); $request = new Request(); - $request->cookies->set('foo', $this->encodeCookie(array('fooseries', 'foovalue'))); + $request->cookies->set('foo', $this->encodeCookie(['fooseries', 'foovalue'])); $tokenProvider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface')->getMock(); $service->setTokenProvider($tokenProvider); @@ -133,9 +133,9 @@ class PersistentTokenBasedRememberMeServicesTest extends TestCase public function testAutoLoginDoesNotAcceptAnExpiredCookie() { - $service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true, 'lifetime' => 3600)); + $service = $this->getService(null, ['name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true, 'lifetime' => 3600]); $request = new Request(); - $request->cookies->set('foo', $this->encodeCookie(array('fooseries', 'foovalue'))); + $request->cookies->set('foo', $this->encodeCookie(['fooseries', 'foovalue'])); $tokenProvider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface')->getMock(); $tokenProvider @@ -156,7 +156,7 @@ class PersistentTokenBasedRememberMeServicesTest extends TestCase $user ->expects($this->once()) ->method('getRoles') - ->will($this->returnValue(array('ROLE_FOO'))) + ->will($this->returnValue(['ROLE_FOO'])) ; $userProvider = $this->getProvider(); @@ -167,9 +167,9 @@ class PersistentTokenBasedRememberMeServicesTest extends TestCase ->will($this->returnValue($user)) ; - $service = $this->getService($userProvider, array('name' => 'foo', 'path' => null, 'domain' => null, 'secure' => false, 'httponly' => false, 'always_remember_me' => true, 'lifetime' => 3600)); + $service = $this->getService($userProvider, ['name' => 'foo', 'path' => null, 'domain' => null, 'secure' => false, 'httponly' => false, 'always_remember_me' => true, 'lifetime' => 3600]); $request = new Request(); - $request->cookies->set('foo', $this->encodeCookie(array('fooseries', 'foovalue'))); + $request->cookies->set('foo', $this->encodeCookie(['fooseries', 'foovalue'])); $tokenProvider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface')->getMock(); $tokenProvider @@ -190,9 +190,9 @@ class PersistentTokenBasedRememberMeServicesTest extends TestCase public function testLogout() { - $service = $this->getService(null, array('name' => 'foo', 'path' => '/foo', 'domain' => 'foodomain.foo', 'secure' => true, 'httponly' => false)); + $service = $this->getService(null, ['name' => 'foo', 'path' => '/foo', 'domain' => 'foodomain.foo', 'secure' => true, 'httponly' => false]); $request = new Request(); - $request->cookies->set('foo', $this->encodeCookie(array('fooseries', 'foovalue'))); + $request->cookies->set('foo', $this->encodeCookie(['fooseries', 'foovalue'])); $response = new Response(); $token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock(); @@ -217,7 +217,7 @@ class PersistentTokenBasedRememberMeServicesTest extends TestCase public function testLogoutSimplyIgnoresNonSetRequestCookie() { - $service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null)); + $service = $this->getService(null, ['name' => 'foo', 'path' => null, 'domain' => null]); $request = new Request(); $response = new Response(); $token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock(); @@ -239,7 +239,7 @@ class PersistentTokenBasedRememberMeServicesTest extends TestCase public function testLogoutSimplyIgnoresInvalidCookie() { - $service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null)); + $service = $this->getService(null, ['name' => 'foo', 'path' => null, 'domain' => null]); $request = new Request(); $request->cookies->set('foo', 'somefoovalue'); $response = new Response(); @@ -259,7 +259,7 @@ class PersistentTokenBasedRememberMeServicesTest extends TestCase public function testLoginFail() { - $service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null)); + $service = $this->getService(null, ['name' => 'foo', 'path' => null, 'domain' => null]); $request = new Request(); $this->assertFalse($request->attributes->has(RememberMeServicesInterface::COOKIE_ATTR_NAME)); @@ -269,7 +269,7 @@ class PersistentTokenBasedRememberMeServicesTest extends TestCase public function testLoginSuccessSetsCookieWhenLoggedInWithNonRememberMeTokenInterfaceImplementation() { - $service = $this->getService(null, array('name' => 'foo', 'domain' => 'myfoodomain.foo', 'path' => '/foo/path', 'secure' => true, 'httponly' => true, 'samesite' => Cookie::SAMESITE_STRICT, 'lifetime' => 3600, 'always_remember_me' => true)); + $service = $this->getService(null, ['name' => 'foo', 'domain' => 'myfoodomain.foo', 'path' => '/foo/path', 'secure' => true, 'httponly' => true, 'samesite' => Cookie::SAMESITE_STRICT, 'lifetime' => 3600, 'always_remember_me' => true]); $request = new Request(); $response = new Response(); @@ -318,13 +318,13 @@ class PersistentTokenBasedRememberMeServicesTest extends TestCase return $r->invoke($service, $parts); } - protected function getService($userProvider = null, $options = array(), $logger = null) + protected function getService($userProvider = null, $options = [], $logger = null) { if (null === $userProvider) { $userProvider = $this->getProvider(); } - return new PersistentTokenBasedRememberMeServices(array($userProvider), 'foosecret', 'fookey', $options, $logger); + return new PersistentTokenBasedRememberMeServices([$userProvider], 'foosecret', 'fookey', $options, $logger); } protected function getProvider() diff --git a/src/Symfony/Component/Security/Http/Tests/RememberMe/TokenBasedRememberMeServicesTest.php b/src/Symfony/Component/Security/Http/Tests/RememberMe/TokenBasedRememberMeServicesTest.php index de25e3a6d5..e71e650a4d 100644 --- a/src/Symfony/Component/Security/Http/Tests/RememberMe/TokenBasedRememberMeServicesTest.php +++ b/src/Symfony/Component/Security/Http/Tests/RememberMe/TokenBasedRememberMeServicesTest.php @@ -24,14 +24,14 @@ class TokenBasedRememberMeServicesTest extends TestCase { public function testAutoLoginReturnsNullWhenNoCookie() { - $service = $this->getService(null, array('name' => 'foo')); + $service = $this->getService(null, ['name' => 'foo']); $this->assertNull($service->autoLogin(new Request())); } public function testAutoLoginThrowsExceptionOnInvalidCookie() { - $service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => false, 'remember_me_parameter' => 'foo')); + $service = $this->getService(null, ['name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => false, 'remember_me_parameter' => 'foo']); $request = new Request(); $request->request->set('foo', 'true'); $request->cookies->set('foo', 'foo'); @@ -43,7 +43,7 @@ class TokenBasedRememberMeServicesTest extends TestCase public function testAutoLoginThrowsExceptionOnNonExistentUser() { $userProvider = $this->getProvider(); - $service = $this->getService($userProvider, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true, 'lifetime' => 3600)); + $service = $this->getService($userProvider, ['name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true, 'lifetime' => 3600]); $request = new Request(); $request->cookies->set('foo', $this->getCookie('fooclass', 'foouser', time() + 3600, 'foopass')); @@ -60,7 +60,7 @@ class TokenBasedRememberMeServicesTest extends TestCase public function testAutoLoginDoesNotAcceptCookieWithInvalidHash() { $userProvider = $this->getProvider(); - $service = $this->getService($userProvider, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true, 'lifetime' => 3600)); + $service = $this->getService($userProvider, ['name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true, 'lifetime' => 3600]); $request = new Request(); $request->cookies->set('foo', base64_encode('class:'.base64_encode('foouser').':123456789:fooHash')); @@ -85,7 +85,7 @@ class TokenBasedRememberMeServicesTest extends TestCase public function testAutoLoginDoesNotAcceptAnExpiredCookie() { $userProvider = $this->getProvider(); - $service = $this->getService($userProvider, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true, 'lifetime' => 3600)); + $service = $this->getService($userProvider, ['name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true, 'lifetime' => 3600]); $request = new Request(); $request->cookies->set('foo', $this->getCookie('fooclass', 'foouser', time() - 1, 'foopass')); @@ -118,7 +118,7 @@ class TokenBasedRememberMeServicesTest extends TestCase $user ->expects($this->once()) ->method('getRoles') - ->will($this->returnValue(array('ROLE_FOO'))) + ->will($this->returnValue(['ROLE_FOO'])) ; $user ->expects($this->once()) @@ -134,7 +134,7 @@ class TokenBasedRememberMeServicesTest extends TestCase ->will($this->returnValue($user)) ; - $service = $this->getService($userProvider, array('name' => 'foo', 'always_remember_me' => true, 'lifetime' => 3600)); + $service = $this->getService($userProvider, ['name' => 'foo', 'always_remember_me' => true, 'lifetime' => 3600]); $request = new Request(); $request->cookies->set('foo', $this->getCookie('fooclass', $username, time() + 3600, 'foopass')); @@ -147,15 +147,15 @@ class TokenBasedRememberMeServicesTest extends TestCase public function provideUsernamesForAutoLogin() { - return array( - array('foouser', 'Simple username'), - array('foo'.TokenBasedRememberMeServices::COOKIE_DELIMITER.'user', 'Username might contain the delimiter'), - ); + return [ + ['foouser', 'Simple username'], + ['foo'.TokenBasedRememberMeServices::COOKIE_DELIMITER.'user', 'Username might contain the delimiter'], + ]; } public function testLogout() { - $service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null, 'secure' => true, 'httponly' => false)); + $service = $this->getService(null, ['name' => 'foo', 'path' => null, 'domain' => null, 'secure' => true, 'httponly' => false]); $request = new Request(); $response = new Response(); $token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock(); @@ -172,7 +172,7 @@ class TokenBasedRememberMeServicesTest extends TestCase public function testLoginFail() { - $service = $this->getService(null, array('name' => 'foo', 'path' => '/foo', 'domain' => 'foodomain.foo')); + $service = $this->getService(null, ['name' => 'foo', 'path' => '/foo', 'domain' => 'foodomain.foo']); $request = new Request(); $service->loginFail($request); @@ -185,7 +185,7 @@ class TokenBasedRememberMeServicesTest extends TestCase public function testLoginSuccessIgnoresTokensWhichDoNotContainAnUserInterfaceImplementation() { - $service = $this->getService(null, array('name' => 'foo', 'always_remember_me' => true, 'path' => null, 'domain' => null)); + $service = $this->getService(null, ['name' => 'foo', 'always_remember_me' => true, 'path' => null, 'domain' => null]); $request = new Request(); $response = new Response(); $token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock(); @@ -206,7 +206,7 @@ class TokenBasedRememberMeServicesTest extends TestCase public function testLoginSuccess() { - $service = $this->getService(null, array('name' => 'foo', 'domain' => 'myfoodomain.foo', 'path' => '/foo/path', 'secure' => true, 'httponly' => true, 'samesite' => Cookie::SAMESITE_STRICT, 'lifetime' => 3600, 'always_remember_me' => true)); + $service = $this->getService(null, ['name' => 'foo', 'domain' => 'myfoodomain.foo', 'path' => '/foo/path', 'secure' => true, 'httponly' => true, 'samesite' => Cookie::SAMESITE_STRICT, 'lifetime' => 3600, 'always_remember_me' => true]); $request = new Request(); $response = new Response(); @@ -262,13 +262,13 @@ class TokenBasedRememberMeServicesTest extends TestCase return $r->invoke($service, $parts); } - protected function getService($userProvider = null, $options = array(), $logger = null) + protected function getService($userProvider = null, $options = [], $logger = null) { if (null === $userProvider) { $userProvider = $this->getProvider(); } - $service = new TokenBasedRememberMeServices(array($userProvider), 'foosecret', 'fookey', $options, $logger); + $service = new TokenBasedRememberMeServices([$userProvider], 'foosecret', 'fookey', $options, $logger); return $service; } diff --git a/src/Symfony/Component/Serializer/Encoder/CsvEncoder.php b/src/Symfony/Component/Serializer/Encoder/CsvEncoder.php index c453120fc6..eaaa8dffc3 100644 --- a/src/Symfony/Component/Serializer/Encoder/CsvEncoder.php +++ b/src/Symfony/Component/Serializer/Encoder/CsvEncoder.php @@ -30,31 +30,31 @@ class CsvEncoder implements EncoderInterface, DecoderInterface const ESCAPE_FORMULAS_KEY = 'csv_escape_formulas'; const AS_COLLECTION_KEY = 'as_collection'; - private $formulasStartCharacters = array('=', '-', '+', '@'); - private $defaultContext = array( + private $formulasStartCharacters = ['=', '-', '+', '@']; + private $defaultContext = [ self::DELIMITER_KEY => ',', self::ENCLOSURE_KEY => '"', self::ESCAPE_CHAR_KEY => '\\', self::ESCAPE_FORMULAS_KEY => false, - self::HEADERS_KEY => array(), + self::HEADERS_KEY => [], self::KEY_SEPARATOR_KEY => '.', - ); + ]; /** * @param array $defaultContext */ - public function __construct($defaultContext = array(), string $enclosure = '"', string $escapeChar = '\\', string $keySeparator = '.', bool $escapeFormulas = false) + public function __construct($defaultContext = [], string $enclosure = '"', string $escapeChar = '\\', string $keySeparator = '.', bool $escapeFormulas = false) { if (!\is_array($defaultContext)) { @trigger_error('Passing configuration options directly to the constructor is deprecated since Symfony 4.2, use the default context instead.', E_USER_DEPRECATED); - $defaultContext = array( + $defaultContext = [ self::DELIMITER_KEY => (string) $defaultContext, self::ENCLOSURE_KEY => $enclosure, self::ESCAPE_CHAR_KEY => $escapeChar, self::KEY_SEPARATOR_KEY => $keySeparator, self::ESCAPE_FORMULAS_KEY => $escapeFormulas, - ); + ]; } $this->defaultContext = array_merge($this->defaultContext, $defaultContext); @@ -63,20 +63,20 @@ class CsvEncoder implements EncoderInterface, DecoderInterface /** * {@inheritdoc} */ - public function encode($data, $format, array $context = array()) + public function encode($data, $format, array $context = []) { $handle = fopen('php://temp,', 'w+'); if (!\is_array($data)) { - $data = array(array($data)); + $data = [[$data]]; } elseif (empty($data)) { - $data = array(array()); + $data = [[]]; } else { // Sequential arrays of arrays are considered as collections $i = 0; foreach ($data as $key => $value) { if ($i !== $key || !\is_array($value)) { - $data = array($data); + $data = [$data]; break; } @@ -87,7 +87,7 @@ class CsvEncoder implements EncoderInterface, DecoderInterface list($delimiter, $enclosure, $escapeChar, $keySeparator, $headers, $escapeFormulas) = $this->getCsvOptions($context); foreach ($data as &$value) { - $flattened = array(); + $flattened = []; $this->flatten($value, $flattened, $keySeparator, '', $escapeFormulas); $value = $flattened; } @@ -120,7 +120,7 @@ class CsvEncoder implements EncoderInterface, DecoderInterface /** * {@inheritdoc} */ - public function decode($data, $format, array $context = array()) + public function decode($data, $format, array $context = []) { $handle = fopen('php://temp', 'r+'); fwrite($handle, $data); @@ -128,8 +128,8 @@ class CsvEncoder implements EncoderInterface, DecoderInterface $headers = null; $nbHeaders = 0; - $headerCount = array(); - $result = array(); + $headerCount = []; + $result = []; list($delimiter, $enclosure, $escapeChar, $keySeparator) = $this->getCsvOptions($context); @@ -148,7 +148,7 @@ class CsvEncoder implements EncoderInterface, DecoderInterface continue; } - $item = array(); + $item = []; for ($i = 0; ($i < $nbCols) && ($i < $nbHeaders); ++$i) { $depth = $headerCount[$i]; $arr = &$item; @@ -161,7 +161,7 @@ class CsvEncoder implements EncoderInterface, DecoderInterface } if (!isset($arr[$headers[$i][$j]])) { - $arr[$headers[$i][$j]] = array(); + $arr[$headers[$i][$j]] = []; } $arr = &$arr[$headers[$i][$j]]; @@ -227,7 +227,7 @@ class CsvEncoder implements EncoderInterface, DecoderInterface throw new InvalidArgumentException(sprintf('The "%s" context variable must be an array or null, given "%s".', self::HEADERS_KEY, \gettype($headers))); } - return array($delimiter, $enclosure, $escapeChar, $keySeparator, $headers, $escapeFormulas); + return [$delimiter, $enclosure, $escapeChar, $keySeparator, $headers, $escapeFormulas]; } /** @@ -235,8 +235,8 @@ class CsvEncoder implements EncoderInterface, DecoderInterface */ private function extractHeaders(array $data) { - $headers = array(); - $flippedHeaders = array(); + $headers = []; + $flippedHeaders = []; foreach ($data as $row) { $previousHeader = null; diff --git a/src/Symfony/Component/Serializer/Encoder/JsonDecode.php b/src/Symfony/Component/Serializer/Encoder/JsonDecode.php index 2722974d58..789e166b50 100644 --- a/src/Symfony/Component/Serializer/Encoder/JsonDecode.php +++ b/src/Symfony/Component/Serializer/Encoder/JsonDecode.php @@ -34,26 +34,26 @@ class JsonDecode implements DecoderInterface */ const RECURSION_DEPTH = 'json_decode_recursion_depth'; - private $defaultContext = array( + private $defaultContext = [ self::ASSOCIATIVE => false, self::OPTIONS => 0, self::RECURSION_DEPTH => 512, - ); + ]; /** * Constructs a new JsonDecode instance. * * @param array $defaultContext */ - public function __construct($defaultContext = array(), int $depth = 512) + public function __construct($defaultContext = [], int $depth = 512) { if (!\is_array($defaultContext)) { @trigger_error(sprintf('Using constructor parameters that are not a default context is deprecated since Symfony 4.2, use the "%s" and "%s" keys of the context instead.', self::ASSOCIATIVE, self::RECURSION_DEPTH), E_USER_DEPRECATED); - $defaultContext = array( + $defaultContext = [ self::ASSOCIATIVE => (bool) $defaultContext, self::RECURSION_DEPTH => $depth, - ); + ]; } $this->defaultContext = array_merge($this->defaultContext, $defaultContext); @@ -86,7 +86,7 @@ class JsonDecode implements DecoderInterface * * @see http://php.net/json_decode json_decode */ - public function decode($data, $format, array $context = array()) + public function decode($data, $format, array $context = []) { $associative = $context[self::ASSOCIATIVE] ?? $this->defaultContext[self::ASSOCIATIVE]; $recursionDepth = $context[self::RECURSION_DEPTH] ?? $this->defaultContext[self::RECURSION_DEPTH]; diff --git a/src/Symfony/Component/Serializer/Encoder/JsonEncode.php b/src/Symfony/Component/Serializer/Encoder/JsonEncode.php index 63669d4ca6..ca9fc9e5d7 100644 --- a/src/Symfony/Component/Serializer/Encoder/JsonEncode.php +++ b/src/Symfony/Component/Serializer/Encoder/JsonEncode.php @@ -22,14 +22,14 @@ class JsonEncode implements EncoderInterface { const OPTIONS = 'json_encode_options'; - private $defaultContext = array( + private $defaultContext = [ self::OPTIONS => 0, - ); + ]; /** * @param array $defaultContext */ - public function __construct($defaultContext = array()) + public function __construct($defaultContext = []) { if (!\is_array($defaultContext)) { @trigger_error(sprintf('Passing an integer as first parameter of the "%s()" method is deprecated since Symfony 4.2, use the "json_encode_options" key of the context instead.', __METHOD__), E_USER_DEPRECATED); @@ -45,7 +45,7 @@ class JsonEncode implements EncoderInterface * * {@inheritdoc} */ - public function encode($data, $format, array $context = array()) + public function encode($data, $format, array $context = []) { $jsonEncodeOptions = $context[self::OPTIONS] ?? $this->defaultContext[self::OPTIONS]; $encodedJson = json_encode($data, $jsonEncodeOptions); diff --git a/src/Symfony/Component/Serializer/Encoder/JsonEncoder.php b/src/Symfony/Component/Serializer/Encoder/JsonEncoder.php index 9657b3d80b..8cb98accdf 100644 --- a/src/Symfony/Component/Serializer/Encoder/JsonEncoder.php +++ b/src/Symfony/Component/Serializer/Encoder/JsonEncoder.php @@ -26,7 +26,7 @@ class JsonEncoder implements EncoderInterface, DecoderInterface public function __construct(JsonEncode $encodingImpl = null, JsonDecode $decodingImpl = null) { $this->encodingImpl = $encodingImpl ?: new JsonEncode(); - $this->decodingImpl = $decodingImpl ?: new JsonDecode(array(JsonDecode::ASSOCIATIVE => true)); + $this->decodingImpl = $decodingImpl ?: new JsonDecode([JsonDecode::ASSOCIATIVE => true]); } /** diff --git a/src/Symfony/Component/Serializer/Encoder/XmlEncoder.php b/src/Symfony/Component/Serializer/Encoder/XmlEncoder.php index 3632be1f89..86a844e535 100644 --- a/src/Symfony/Component/Serializer/Encoder/XmlEncoder.php +++ b/src/Symfony/Component/Serializer/Encoder/XmlEncoder.php @@ -54,15 +54,15 @@ class XmlEncoder implements EncoderInterface, DecoderInterface, NormalizationAwa const TYPE_CASE_ATTRIBUTES = 'xml_type_cast_attributes'; const VERSION = 'xml_version'; - private $defaultContext = array( + private $defaultContext = [ self::AS_COLLECTION => false, - self::DECODER_IGNORED_NODE_TYPES => array(XML_PI_NODE, XML_COMMENT_NODE), - self::ENCODER_IGNORED_NODE_TYPES => array(), + self::DECODER_IGNORED_NODE_TYPES => [XML_PI_NODE, XML_COMMENT_NODE], + self::ENCODER_IGNORED_NODE_TYPES => [], self::LOAD_OPTIONS => LIBXML_NONET | LIBXML_NOBLANKS, self::REMOVE_EMPTY_TAGS => false, self::ROOT_NODE_NAME => 'response', self::TYPE_CASE_ATTRIBUTES => true, - ); + ]; /** * @var \DOMDocument @@ -74,17 +74,17 @@ class XmlEncoder implements EncoderInterface, DecoderInterface, NormalizationAwa /** * @param array $defaultContext */ - public function __construct($defaultContext = array(), int $loadOptions = null, array $decoderIgnoredNodeTypes = array(XML_PI_NODE, XML_COMMENT_NODE), array $encoderIgnoredNodeTypes = array()) + public function __construct($defaultContext = [], int $loadOptions = null, array $decoderIgnoredNodeTypes = [XML_PI_NODE, XML_COMMENT_NODE], array $encoderIgnoredNodeTypes = []) { if (!\is_array($defaultContext)) { @trigger_error('Passing configuration options directly to the constructor is deprecated since Symfony 4.2, use the default context instead.', E_USER_DEPRECATED); - $defaultContext = array( + $defaultContext = [ self::DECODER_IGNORED_NODE_TYPES => $decoderIgnoredNodeTypes, self::ENCODER_IGNORED_NODE_TYPES => $encoderIgnoredNodeTypes, self::LOAD_OPTIONS => $loadOptions ?? LIBXML_NONET | LIBXML_NOBLANKS, self::ROOT_NODE_NAME => (string) $defaultContext, - ); + ]; } $this->defaultContext = array_merge($this->defaultContext, $defaultContext); @@ -93,7 +93,7 @@ class XmlEncoder implements EncoderInterface, DecoderInterface, NormalizationAwa /** * {@inheritdoc} */ - public function encode($data, $format, array $context = array()) + public function encode($data, $format, array $context = []) { $encoderIgnoredNodeTypes = $context[self::ENCODER_IGNORED_NODE_TYPES] ?? $this->defaultContext[self::ENCODER_IGNORED_NODE_TYPES]; $ignorePiNode = \in_array(XML_PI_NODE, $encoderIgnoredNodeTypes, true); @@ -121,7 +121,7 @@ class XmlEncoder implements EncoderInterface, DecoderInterface, NormalizationAwa /** * {@inheritdoc} */ - public function decode($data, $format, array $context = array()) + public function decode($data, $format, array $context = []) { if ('' === trim($data)) { throw new NotEncodableValueException('Invalid XML data, it can not be empty.'); @@ -158,7 +158,7 @@ class XmlEncoder implements EncoderInterface, DecoderInterface, NormalizationAwa if ($rootNode->hasChildNodes()) { $xpath = new \DOMXPath($dom); - $data = array(); + $data = []; foreach ($xpath->query('namespace::*', $dom->documentElement) as $nsNode) { $data['@'.$nsNode->nodeName] = $nsNode->nodeValue; } @@ -176,7 +176,7 @@ class XmlEncoder implements EncoderInterface, DecoderInterface, NormalizationAwa return $rootNode->nodeValue; } - $data = array(); + $data = []; foreach ($rootNode->attributes as $attrKey => $attr) { $data['@'.$attrKey] = $attr->nodeValue; @@ -297,7 +297,7 @@ class XmlEncoder implements EncoderInterface, DecoderInterface, NormalizationAwa * * @return array|string */ - private function parseXml(\DOMNode $node, array $context = array()) + private function parseXml(\DOMNode $node, array $context = []) { $data = $this->parseXmlAttributes($node, $context); @@ -329,13 +329,13 @@ class XmlEncoder implements EncoderInterface, DecoderInterface, NormalizationAwa /** * Parse the input DOMNode attributes into an array. */ - private function parseXmlAttributes(\DOMNode $node, array $context = array()): array + private function parseXmlAttributes(\DOMNode $node, array $context = []): array { if (!$node->hasAttributes()) { - return array(); + return []; } - $data = array(); + $data = []; $typeCastAttributes = (bool) ($context[self::TYPE_CASE_ATTRIBUTES] ?? $this->defaultContext[self::TYPE_CASE_ATTRIBUTES]); foreach ($node->attributes as $attr) { @@ -362,17 +362,17 @@ class XmlEncoder implements EncoderInterface, DecoderInterface, NormalizationAwa * * @return array|string */ - private function parseXmlValue(\DOMNode $node, array $context = array()) + private function parseXmlValue(\DOMNode $node, array $context = []) { if (!$node->hasChildNodes()) { return $node->nodeValue; } - if (1 === $node->childNodes->length && \in_array($node->firstChild->nodeType, array(XML_TEXT_NODE, XML_CDATA_SECTION_NODE))) { + if (1 === $node->childNodes->length && \in_array($node->firstChild->nodeType, [XML_TEXT_NODE, XML_CDATA_SECTION_NODE])) { return $node->firstChild->nodeValue; } - $value = array(); + $value = []; $decoderIgnoredNodeTypes = $context[self::DECODER_IGNORED_NODE_TYPES] ?? $this->defaultContext[self::DECODER_IGNORED_NODE_TYPES]; foreach ($node->childNodes as $subnode) { if (\in_array($subnode->nodeType, $decoderIgnoredNodeTypes, true)) { @@ -539,7 +539,7 @@ class XmlEncoder implements EncoderInterface, DecoderInterface, NormalizationAwa $document = new \DOMDocument(); // Set an attribute on the DOM document specifying, as part of the XML declaration, - $xmlOptions = array( + $xmlOptions = [ // nicely formats output with indentation and extra space self::FORMAT_OUTPUT => 'formatOutput', // the version number of the document @@ -548,7 +548,7 @@ class XmlEncoder implements EncoderInterface, DecoderInterface, NormalizationAwa self::ENCODING => 'encoding', // whether the document is standalone self::STANDALONE => 'xmlStandalone', - ); + ]; foreach ($xmlOptions as $xmlOption => $documentProperty) { if ($contextOption = $context[$xmlOption] ?? $this->defaultContext[$xmlOption] ?? false) { $document->$documentProperty = $contextOption; diff --git a/src/Symfony/Component/Serializer/Mapping/AttributeMetadata.php b/src/Symfony/Component/Serializer/Mapping/AttributeMetadata.php index 9e8ebc6524..a49051113d 100644 --- a/src/Symfony/Component/Serializer/Mapping/AttributeMetadata.php +++ b/src/Symfony/Component/Serializer/Mapping/AttributeMetadata.php @@ -30,7 +30,7 @@ class AttributeMetadata implements AttributeMetadataInterface * class' serialized representation. Do not access it. Use * {@link getGroups()} instead. */ - public $groups = array(); + public $groups = []; /** * @var int|null @@ -140,6 +140,6 @@ class AttributeMetadata implements AttributeMetadataInterface */ public function __sleep() { - return array('name', 'groups', 'maxDepth', 'serializedName'); + return ['name', 'groups', 'maxDepth', 'serializedName']; } } diff --git a/src/Symfony/Component/Serializer/NameConverter/AdvancedNameConverterInterface.php b/src/Symfony/Component/Serializer/NameConverter/AdvancedNameConverterInterface.php index d0f94fdfc1..03abdf18ba 100644 --- a/src/Symfony/Component/Serializer/NameConverter/AdvancedNameConverterInterface.php +++ b/src/Symfony/Component/Serializer/NameConverter/AdvancedNameConverterInterface.php @@ -21,10 +21,10 @@ interface AdvancedNameConverterInterface extends NameConverterInterface /** * {@inheritdoc} */ - public function normalize($propertyName, string $class = null, string $format = null, array $context = array()); + public function normalize($propertyName, string $class = null, string $format = null, array $context = []); /** * {@inheritdoc} */ - public function denormalize($propertyName, string $class = null, string $format = null, array $context = array()); + public function denormalize($propertyName, string $class = null, string $format = null, array $context = []); } diff --git a/src/Symfony/Component/Serializer/NameConverter/MetadataAwareNameConverter.php b/src/Symfony/Component/Serializer/NameConverter/MetadataAwareNameConverter.php index 51abde2246..a6934f54b8 100644 --- a/src/Symfony/Component/Serializer/NameConverter/MetadataAwareNameConverter.php +++ b/src/Symfony/Component/Serializer/NameConverter/MetadataAwareNameConverter.php @@ -25,11 +25,11 @@ final class MetadataAwareNameConverter implements AdvancedNameConverterInterface */ private $fallbackNameConverter; - private static $normalizeCache = array(); + private static $normalizeCache = []; - private static $denormalizeCache = array(); + private static $denormalizeCache = []; - private static $attributesMetadataCache = array(); + private static $attributesMetadataCache = []; public function __construct(ClassMetadataFactoryInterface $metadataFactory, NameConverterInterface $fallbackNameConverter = null) { @@ -40,7 +40,7 @@ final class MetadataAwareNameConverter implements AdvancedNameConverterInterface /** * {@inheritdoc} */ - public function normalize($propertyName, string $class = null, string $format = null, array $context = array()) + public function normalize($propertyName, string $class = null, string $format = null, array $context = []) { if (null === $class) { return $this->normalizeFallback($propertyName, $class, $format, $context); @@ -56,7 +56,7 @@ final class MetadataAwareNameConverter implements AdvancedNameConverterInterface /** * {@inheritdoc} */ - public function denormalize($propertyName, string $class = null, string $format = null, array $context = array()) + public function denormalize($propertyName, string $class = null, string $format = null, array $context = []) { if (null === $class) { return $this->denormalizeFallback($propertyName, $class, $format, $context); @@ -83,7 +83,7 @@ final class MetadataAwareNameConverter implements AdvancedNameConverterInterface return $attributesMetadata[$propertyName]->getSerializedName() ?? null; } - private function normalizeFallback(string $propertyName, string $class = null, string $format = null, array $context = array()): string + private function normalizeFallback(string $propertyName, string $class = null, string $format = null, array $context = []): string { return $this->fallbackNameConverter ? $this->fallbackNameConverter->normalize($propertyName, $class, $format, $context) : $propertyName; } @@ -97,7 +97,7 @@ final class MetadataAwareNameConverter implements AdvancedNameConverterInterface return self::$attributesMetadataCache[$class][$propertyName] ?? null; } - private function denormalizeFallback(string $propertyName, string $class = null, string $format = null, array $context = array()): string + private function denormalizeFallback(string $propertyName, string $class = null, string $format = null, array $context = []): string { return $this->fallbackNameConverter ? $this->fallbackNameConverter->denormalize($propertyName, $class, $format, $context) : $propertyName; } @@ -105,12 +105,12 @@ final class MetadataAwareNameConverter implements AdvancedNameConverterInterface private function getCacheValueForAttributesMetadata(string $class): array { if (!$this->metadataFactory->hasMetadataFor($class)) { - return array(); + return []; } $classMetadata = $this->metadataFactory->getMetadataFor($class); - $cache = array(); + $cache = []; foreach ($classMetadata->getAttributesMetadata() as $name => $metadata) { if (null === $metadata->getSerializedName()) { continue; diff --git a/src/Symfony/Component/Serializer/Normalizer/AbstractNormalizer.php b/src/Symfony/Component/Serializer/Normalizer/AbstractNormalizer.php index ef2409bfb0..34b02fed1d 100644 --- a/src/Symfony/Component/Serializer/Normalizer/AbstractNormalizer.php +++ b/src/Symfony/Component/Serializer/Normalizer/AbstractNormalizer.php @@ -47,11 +47,11 @@ abstract class AbstractNormalizer implements NormalizerInterface, DenormalizerIn */ const CIRCULAR_REFERENCE_LIMIT_COUNTERS = 'circular_reference_limit_counters'; - protected $defaultContext = array( + protected $defaultContext = [ self::ALLOW_EXTRA_ATTRIBUTES => true, self::CIRCULAR_REFERENCE_LIMIT => 1, - self::IGNORED_ATTRIBUTES => array(), - ); + self::IGNORED_ATTRIBUTES => [], + ]; /** * @deprecated since Symfony 4.2 @@ -93,7 +93,7 @@ abstract class AbstractNormalizer implements NormalizerInterface, DenormalizerIn /** * Sets the {@link ClassMetadataFactoryInterface} to use. */ - public function __construct(ClassMetadataFactoryInterface $classMetadataFactory = null, NameConverterInterface $nameConverter = null, array $defaultContext = array()) + public function __construct(ClassMetadataFactoryInterface $classMetadataFactory = null, NameConverterInterface $nameConverter = null, array $defaultContext = []) { $this->classMetadataFactory = $classMetadataFactory; $this->nameConverter = $nameConverter; @@ -245,7 +245,7 @@ abstract class AbstractNormalizer implements NormalizerInterface, DenormalizerIn @trigger_error(sprintf('The "%s()" method will have two new "string $format = null" and "array $context = array()" arguments in version 5.0, not defining it is deprecated since Symfony 4.2.', __METHOD__), E_USER_DEPRECATED); } $format = \func_num_args() > 1 ? func_get_arg(1) : null; - $context = \func_num_args() > 2 ? func_get_arg(2) : array(); + $context = \func_num_args() > 2 ? func_get_arg(2) : []; $circularReferenceHandler = $context[self::CIRCULAR_REFERENCE_HANDLER] ?? $this->defaultContext[self::CIRCULAR_REFERENCE_HANDLER] ?? $this->circularReferenceHandler; if ($circularReferenceHandler) { @@ -419,7 +419,7 @@ abstract class AbstractNormalizer implements NormalizerInterface, DenormalizerIn unset($data[$key]); } elseif (array_key_exists($key, $context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class] ?? [])) { $params[] = $context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key]; - } elseif (array_key_exists($key, $this->defaultContext[self::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class] ?? array())) { + } elseif (array_key_exists($key, $this->defaultContext[self::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class] ?? [])) { $params[] = $this->defaultContext[self::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key]; } elseif ($constructorParameter->isDefaultValueAvailable()) { $params[] = $constructorParameter->getDefaultValue(); diff --git a/src/Symfony/Component/Serializer/Normalizer/AbstractObjectNormalizer.php b/src/Symfony/Component/Serializer/Normalizer/AbstractObjectNormalizer.php index 8e8edde937..b17d1e8c59 100644 --- a/src/Symfony/Component/Serializer/Normalizer/AbstractObjectNormalizer.php +++ b/src/Symfony/Component/Serializer/Normalizer/AbstractObjectNormalizer.php @@ -40,8 +40,8 @@ abstract class AbstractObjectNormalizer extends AbstractNormalizer const EXCLUDE_FROM_CACHE_KEY = 'exclude_from_cache_key'; private $propertyTypeExtractor; - private $typesCache = array(); - private $attributesCache = array(); + private $typesCache = []; + private $attributesCache = []; /** * @deprecated since Symfony 4.2 @@ -56,10 +56,10 @@ abstract class AbstractObjectNormalizer extends AbstractNormalizer */ protected $classDiscriminatorResolver; - public function __construct(ClassMetadataFactoryInterface $classMetadataFactory = null, NameConverterInterface $nameConverter = null, PropertyTypeExtractorInterface $propertyTypeExtractor = null, ClassDiscriminatorResolverInterface $classDiscriminatorResolver = null, callable $objectClassResolver = null, array $defaultContext = array()) + public function __construct(ClassMetadataFactoryInterface $classMetadataFactory = null, NameConverterInterface $nameConverter = null, PropertyTypeExtractorInterface $propertyTypeExtractor = null, ClassDiscriminatorResolverInterface $classDiscriminatorResolver = null, callable $objectClassResolver = null, array $defaultContext = []) { parent::__construct($classMetadataFactory, $nameConverter, $defaultContext); - $this->defaultContext[self::EXCLUDE_FROM_CACHE_KEY] = array(self::CIRCULAR_REFERENCE_LIMIT_COUNTERS); + $this->defaultContext[self::EXCLUDE_FROM_CACHE_KEY] = [self::CIRCULAR_REFERENCE_LIMIT_COUNTERS]; $this->propertyTypeExtractor = $propertyTypeExtractor; @@ -81,7 +81,7 @@ abstract class AbstractObjectNormalizer extends AbstractNormalizer /** * {@inheritdoc} */ - public function normalize($object, $format = null, array $context = array()) + public function normalize($object, $format = null, array $context = []) { if (!isset($context['cache_key'])) { $context['cache_key'] = $this->getCacheKey($format, $context); @@ -91,8 +91,8 @@ abstract class AbstractObjectNormalizer extends AbstractNormalizer return $this->handleCircularReference($object, $format, $context); } - $data = array(); - $stack = array(); + $data = []; + $stack = []; $attributes = $this->getAttributes($object, $format, $context); $class = $this->objectClassResolver ? ($this->objectClassResolver)($object) : \get_class($object); $attributesMetadata = $this->classMetadataFactory ? $this->classMetadataFactory->getMetadataFor($class)->getAttributesMetadata() : null; @@ -110,7 +110,7 @@ abstract class AbstractObjectNormalizer extends AbstractNormalizer } /** - * @var $callback callable|null + * @var callable|null */ $callback = $context[self::CALLBACKS][$attribute] ?? $this->defaultContext[self::CALLBACKS][$attribute] ?? $this->callbacks[$attribute] ?? null; if ($callback) { @@ -211,7 +211,7 @@ abstract class AbstractObjectNormalizer extends AbstractNormalizer * * @return string[] */ - abstract protected function extractAttributes($object, $format = null, array $context = array()); + abstract protected function extractAttributes($object, $format = null, array $context = []); /** * Gets the attribute value. @@ -223,7 +223,7 @@ abstract class AbstractObjectNormalizer extends AbstractNormalizer * * @return mixed */ - abstract protected function getAttributeValue($object, $attribute, $format = null, array $context = array()); + abstract protected function getAttributeValue($object, $attribute, $format = null, array $context = []); /** * Sets a handler function that will be called when the max depth is reached. @@ -248,7 +248,7 @@ abstract class AbstractObjectNormalizer extends AbstractNormalizer /** * {@inheritdoc} */ - public function denormalize($data, $class, $format = null, array $context = array()) + public function denormalize($data, $class, $format = null, array $context = []) { if (!isset($context['cache_key'])) { $context['cache_key'] = $this->getCacheKey($format, $context); @@ -256,7 +256,7 @@ abstract class AbstractObjectNormalizer extends AbstractNormalizer $allowedAttributes = $this->getAllowedAttributes($class, $context, true); $normalizedData = $this->prepareForDenormalization($data); - $extraAttributes = array(); + $extraAttributes = []; $reflectionClass = new \ReflectionClass($class); $object = $this->instantiateObject($normalizedData, $class, $context, $reflectionClass, $allowedAttributes, $format); @@ -298,7 +298,7 @@ abstract class AbstractObjectNormalizer extends AbstractNormalizer * @param string|null $format * @param array $context */ - abstract protected function setAttributeValue($object, $attribute, $value, $format = null, array $context = array()); + abstract protected function setAttributeValue($object, $attribute, $value, $format = null, array $context = []); /** * Validates the submitted data and denormalizes it. @@ -316,7 +316,7 @@ abstract class AbstractObjectNormalizer extends AbstractNormalizer return $data; } - $expectedTypes = array(); + $expectedTypes = []; foreach ($types as $type) { if (null === $data && $type->isNullable()) { return; @@ -329,7 +329,7 @@ abstract class AbstractObjectNormalizer extends AbstractNormalizer // Fix a collection that contains the only one element // This is special to xml format only if ('xml' === $format && !\is_int(key($data))) { - $data = array($data); + $data = [$data]; } if (null !== $collectionKeyType = $type->getCollectionKeyType()) { @@ -407,9 +407,9 @@ abstract class AbstractObjectNormalizer extends AbstractNormalizer if (null !== $this->classDiscriminatorResolver && null !== $discriminatorMapping = $this->classDiscriminatorResolver->getMappingForClass($currentClass)) { if ($discriminatorMapping->getTypeProperty() === $attribute) { - return $this->typesCache[$key] = array( + return $this->typesCache[$key] = [ new Type(Type::BUILTIN_TYPE_STRING), - ); + ]; } foreach ($discriminatorMapping->getTypesMapping() as $mappedClass) { diff --git a/src/Symfony/Component/Serializer/Normalizer/ConstraintViolationListNormalizer.php b/src/Symfony/Component/Serializer/Normalizer/ConstraintViolationListNormalizer.php index dc24f6ec16..aa45a0fc1b 100644 --- a/src/Symfony/Component/Serializer/Normalizer/ConstraintViolationListNormalizer.php +++ b/src/Symfony/Component/Serializer/Normalizer/ConstraintViolationListNormalizer.php @@ -31,7 +31,7 @@ class ConstraintViolationListNormalizer implements NormalizerInterface, Cacheabl private $defaultContext; - public function __construct($defaultContext = array()) + public function __construct($defaultContext = []) { $this->defaultContext = $defaultContext; } @@ -39,17 +39,17 @@ class ConstraintViolationListNormalizer implements NormalizerInterface, Cacheabl /** * {@inheritdoc} */ - public function normalize($object, $format = null, array $context = array()) + public function normalize($object, $format = null, array $context = []) { - $violations = array(); - $messages = array(); + $violations = []; + $messages = []; foreach ($object as $violation) { $propertyPath = $violation->getPropertyPath(); - $violationEntry = array( + $violationEntry = [ 'propertyPath' => $propertyPath, 'title' => $violation->getMessage(), - ); + ]; if (null !== $code = $violation->getCode()) { $violationEntry['type'] = sprintf('urn:uuid:%s', $code); } @@ -60,10 +60,10 @@ class ConstraintViolationListNormalizer implements NormalizerInterface, Cacheabl $messages[] = $prefix.$violation->getMessage(); } - $result = array( + $result = [ 'type' => $context[self::TYPE] ?? $this->defaultContext[self::TYPE] ?? 'https://symfony.com/errors/validation', 'title' => $context[self::TITLE] ?? $this->defaultContext[self::TITLE] ?? 'Validation Failed', - ); + ]; if (null !== $status = ($context[self::STATUS] ?? $this->defaultContext[self::STATUS] ?? null)) { $result['status'] = $status; } @@ -74,7 +74,7 @@ class ConstraintViolationListNormalizer implements NormalizerInterface, Cacheabl $result['instance'] = $instance; } - return $result + array('violations' => $violations); + return $result + ['violations' => $violations]; } /** diff --git a/src/Symfony/Component/Serializer/Normalizer/DateIntervalNormalizer.php b/src/Symfony/Component/Serializer/Normalizer/DateIntervalNormalizer.php index 16d28a17ec..0b2d4214bf 100644 --- a/src/Symfony/Component/Serializer/Normalizer/DateIntervalNormalizer.php +++ b/src/Symfony/Component/Serializer/Normalizer/DateIntervalNormalizer.php @@ -24,19 +24,19 @@ class DateIntervalNormalizer implements NormalizerInterface, DenormalizerInterfa { const FORMAT_KEY = 'dateinterval_format'; - private $defaultContext = array( + private $defaultContext = [ self::FORMAT_KEY => 'P%yY%mM%dDT%hH%iM%sS', - ); + ]; /** * @param array $defaultContext */ - public function __construct($defaultContext = array()) + public function __construct($defaultContext = []) { if (!\is_array($defaultContext)) { @trigger_error(sprintf('The "format" parameter is deprecated since Symfony 4.2, use the "%s" key of the context instead.', self::FORMAT_KEY), E_USER_DEPRECATED); - $defaultContext = array(self::FORMAT_KEY => (string) $defaultContext); + $defaultContext = [self::FORMAT_KEY => (string) $defaultContext]; } $this->defaultContext = array_merge($this->defaultContext, $defaultContext); diff --git a/src/Symfony/Component/Serializer/Normalizer/DateTimeNormalizer.php b/src/Symfony/Component/Serializer/Normalizer/DateTimeNormalizer.php index 9d3058ff5c..d3de806e18 100644 --- a/src/Symfony/Component/Serializer/Normalizer/DateTimeNormalizer.php +++ b/src/Symfony/Component/Serializer/Normalizer/DateTimeNormalizer.php @@ -36,17 +36,17 @@ class DateTimeNormalizer implements NormalizerInterface, DenormalizerInterface, /** * @param array $defaultContext */ - public function __construct($defaultContext = array(), \DateTimeZone $timezone = null) + public function __construct($defaultContext = [], \DateTimeZone $timezone = null) { - $this->defaultContext = array( + $this->defaultContext = [ self::FORMAT_KEY => \DateTime::RFC3339, self::TIMEZONE_KEY => null, - ); + ]; if (!\is_array($defaultContext)) { @trigger_error('Passing configuration options directly to the constructor is deprecated since Symfony 4.2, use the default context instead.', E_USER_DEPRECATED); - $defaultContext = array(self::FORMAT_KEY => (string) $defaultContext); + $defaultContext = [self::FORMAT_KEY => (string) $defaultContext]; $defaultContext[self::TIMEZONE_KEY] = $timezone; } diff --git a/src/Symfony/Component/Serializer/Normalizer/ObjectNormalizer.php b/src/Symfony/Component/Serializer/Normalizer/ObjectNormalizer.php index 2270c24b76..530f168c6a 100644 --- a/src/Symfony/Component/Serializer/Normalizer/ObjectNormalizer.php +++ b/src/Symfony/Component/Serializer/Normalizer/ObjectNormalizer.php @@ -32,7 +32,7 @@ class ObjectNormalizer extends AbstractObjectNormalizer private $discriminatorCache = []; - public function __construct(ClassMetadataFactoryInterface $classMetadataFactory = null, NameConverterInterface $nameConverter = null, PropertyAccessorInterface $propertyAccessor = null, PropertyTypeExtractorInterface $propertyTypeExtractor = null, ClassDiscriminatorResolverInterface $classDiscriminatorResolver = null, callable $objectClassResolver = null, array $defaultContext = array()) + public function __construct(ClassMetadataFactoryInterface $classMetadataFactory = null, NameConverterInterface $nameConverter = null, PropertyAccessorInterface $propertyAccessor = null, PropertyTypeExtractorInterface $propertyTypeExtractor = null, ClassDiscriminatorResolverInterface $classDiscriminatorResolver = null, callable $objectClassResolver = null, array $defaultContext = []) { if (!\class_exists(PropertyAccess::class)) { throw new LogicException('The ObjectNormalizer class requires the "PropertyAccess" component. Install "symfony/property-access" to use it.'); diff --git a/src/Symfony/Component/Serializer/Serializer.php b/src/Symfony/Component/Serializer/Serializer.php index f7daa6f73f..3aefec553e 100644 --- a/src/Symfony/Component/Serializer/Serializer.php +++ b/src/Symfony/Component/Serializer/Serializer.php @@ -58,17 +58,17 @@ class Serializer implements SerializerInterface, ContextAwareNormalizerInterface /** * @internal since Symfony 4.1 */ - protected $normalizers = array(); + protected $normalizers = []; private $cachedNormalizers; - private $denormalizerCache = array(); - private $normalizerCache = array(); + private $denormalizerCache = []; + private $normalizerCache = []; /** * @param (NormalizerInterface|DenormalizerInterface)[] $normalizers * @param (EncoderInterface|DecoderInterface)[] $encoders */ - public function __construct(array $normalizers = array(), array $encoders = array()) + public function __construct(array $normalizers = [], array $encoders = []) { foreach ($normalizers as $normalizer) { if ($normalizer instanceof SerializerAwareInterface) { @@ -90,8 +90,8 @@ class Serializer implements SerializerInterface, ContextAwareNormalizerInterface } $this->normalizers = $normalizers; - $decoders = array(); - $realEncoders = array(); + $decoders = []; + $realEncoders = []; foreach ($encoders as $encoder) { if ($encoder instanceof SerializerAwareInterface) { $encoder->setSerializer($this); @@ -115,7 +115,7 @@ class Serializer implements SerializerInterface, ContextAwareNormalizerInterface /** * {@inheritdoc} */ - final public function serialize($data, $format, array $context = array()) + final public function serialize($data, $format, array $context = []) { if (!$this->supportsEncoding($format, $context)) { throw new NotEncodableValueException(sprintf('Serialization for the format %s is not supported', $format)); @@ -131,7 +131,7 @@ class Serializer implements SerializerInterface, ContextAwareNormalizerInterface /** * {@inheritdoc} */ - final public function deserialize($data, $type, $format, array $context = array()) + final public function deserialize($data, $type, $format, array $context = []) { if (!$this->supportsDecoding($format, $context)) { throw new NotEncodableValueException(sprintf('Deserialization for the format %s is not supported', $format)); @@ -145,7 +145,7 @@ class Serializer implements SerializerInterface, ContextAwareNormalizerInterface /** * {@inheritdoc} */ - public function normalize($data, $format = null, array $context = array()) + public function normalize($data, $format = null, array $context = []) { // If a normalizer supports the given data, use it if ($normalizer = $this->getNormalizer($data, $format, $context)) { @@ -157,7 +157,7 @@ class Serializer implements SerializerInterface, ContextAwareNormalizerInterface } if (\is_array($data) || $data instanceof \Traversable) { - $normalized = array(); + $normalized = []; foreach ($data as $key => $val) { $normalized[$key] = $this->normalize($val, $format, $context); } @@ -181,7 +181,7 @@ class Serializer implements SerializerInterface, ContextAwareNormalizerInterface * * @throws NotNormalizableValueException */ - public function denormalize($data, $type, $format = null, array $context = array()) + public function denormalize($data, $type, $format = null, array $context = []) { if (!$this->normalizers) { throw new LogicException('You must register at least one normalizer to be able to denormalize objects.'); @@ -197,7 +197,7 @@ class Serializer implements SerializerInterface, ContextAwareNormalizerInterface /** * {@inheritdoc} */ - public function supportsNormalization($data, $format = null, array $context = array()) + public function supportsNormalization($data, $format = null, array $context = []) { return null !== $this->getNormalizer($data, $format, $context); } @@ -205,7 +205,7 @@ class Serializer implements SerializerInterface, ContextAwareNormalizerInterface /** * {@inheritdoc} */ - public function supportsDenormalization($data, $type, $format = null, array $context = array()) + public function supportsDenormalization($data, $type, $format = null, array $context = []) { return null !== $this->getDenormalizer($data, $type, $format, $context); } @@ -223,12 +223,12 @@ class Serializer implements SerializerInterface, ContextAwareNormalizerInterface { if ($this->cachedNormalizers !== $this->normalizers) { $this->cachedNormalizers = $this->normalizers; - $this->denormalizerCache = $this->normalizerCache = array(); + $this->denormalizerCache = $this->normalizerCache = []; } $type = \is_object($data) ? \get_class($data) : 'native-'.\gettype($data); if (!isset($this->normalizerCache[$format][$type])) { - $this->normalizerCache[$format][$type] = array(); + $this->normalizerCache[$format][$type] = []; foreach ($this->normalizers as $k => $normalizer) { if (!$normalizer instanceof NormalizerInterface) { @@ -266,10 +266,10 @@ class Serializer implements SerializerInterface, ContextAwareNormalizerInterface { if ($this->cachedNormalizers !== $this->normalizers) { $this->cachedNormalizers = $this->normalizers; - $this->denormalizerCache = $this->normalizerCache = array(); + $this->denormalizerCache = $this->normalizerCache = []; } if (!isset($this->denormalizerCache[$format][$class])) { - $this->denormalizerCache[$format][$class] = array(); + $this->denormalizerCache[$format][$class] = []; foreach ($this->normalizers as $k => $normalizer) { if (!$normalizer instanceof DenormalizerInterface) { @@ -296,7 +296,7 @@ class Serializer implements SerializerInterface, ContextAwareNormalizerInterface /** * {@inheritdoc} */ - final public function encode($data, $format, array $context = array()) + final public function encode($data, $format, array $context = []) { return $this->encoder->encode($data, $format, $context); } @@ -304,7 +304,7 @@ class Serializer implements SerializerInterface, ContextAwareNormalizerInterface /** * {@inheritdoc} */ - final public function decode($data, $format, array $context = array()) + final public function decode($data, $format, array $context = []) { return $this->decoder->decode($data, $format, $context); } @@ -312,7 +312,7 @@ class Serializer implements SerializerInterface, ContextAwareNormalizerInterface /** * {@inheritdoc} */ - public function supportsEncoding($format, array $context = array()) + public function supportsEncoding($format, array $context = []) { return $this->encoder->supportsEncoding($format, $context); } @@ -320,7 +320,7 @@ class Serializer implements SerializerInterface, ContextAwareNormalizerInterface /** * {@inheritdoc} */ - public function supportsDecoding($format, array $context = array()) + public function supportsDecoding($format, array $context = []) { return $this->decoder->supportsDecoding($format, $context); } diff --git a/src/Symfony/Component/Serializer/Tests/Annotation/SerializedNameTest.php b/src/Symfony/Component/Serializer/Tests/Annotation/SerializedNameTest.php index 45a18db69b..1b6f4ff9f0 100644 --- a/src/Symfony/Component/Serializer/Tests/Annotation/SerializedNameTest.php +++ b/src/Symfony/Component/Serializer/Tests/Annotation/SerializedNameTest.php @@ -25,15 +25,15 @@ class SerializedNameTest extends TestCase */ public function testNotSetSerializedNameParameter() { - new SerializedName(array()); + new SerializedName([]); } public function provideInvalidValues() { - return array( - array(''), - array(0), - ); + return [ + [''], + [0], + ]; } /** @@ -44,12 +44,12 @@ class SerializedNameTest extends TestCase */ public function testNotAStringSerializedNameParameter($value) { - new SerializedName(array('value' => $value)); + new SerializedName(['value' => $value]); } public function testSerializedNameParameters() { - $maxDepth = new SerializedName(array('value' => 'foo')); + $maxDepth = new SerializedName(['value' => 'foo']); $this->assertEquals('foo', $maxDepth->getSerializedName()); } } diff --git a/src/Symfony/Component/Serializer/Tests/Encoder/CsvEncoderTest.php b/src/Symfony/Component/Serializer/Tests/Encoder/CsvEncoderTest.php index 65ced222a9..66ffe2d70c 100644 --- a/src/Symfony/Component/Serializer/Tests/Encoder/CsvEncoderTest.php +++ b/src/Symfony/Component/Serializer/Tests/Encoder/CsvEncoderTest.php @@ -37,7 +37,7 @@ class CsvEncoderTest extends TestCase public function testEncode() { - $value = array('foo' => 'hello', 'bar' => 'hey ho'); + $value = ['foo' => 'hello', 'bar' => 'hey ho']; $this->assertEquals(<<<'CSV' foo,bar @@ -49,10 +49,10 @@ CSV public function testEncodeCollection() { - $value = array( - array('foo' => 'hello', 'bar' => 'hey ho'), - array('foo' => 'hi', 'bar' => 'let\'s go'), - ); + $value = [ + ['foo' => 'hello', 'bar' => 'hey ho'], + ['foo' => 'hi', 'bar' => 'let\'s go'], + ]; $this->assertEquals(<<<'CSV' foo,bar @@ -70,7 +70,7 @@ CSV a,b,c CSV - , $this->encoder->encode(array('a', 'b', 'c'), 'csv')); + , $this->encoder->encode(['a', 'b', 'c'], 'csv')); } public function testEncodeNonArray() @@ -85,10 +85,10 @@ CSV public function testEncodeNestedArrays() { - $value = array('foo' => 'hello', 'bar' => array( - array('id' => 'yo', 1 => 'wesh'), - array('baz' => 'Halo', 'foo' => 'olá'), - )); + $value = ['foo' => 'hello', 'bar' => [ + ['id' => 'yo', 1 => 'wesh'], + ['baz' => 'Halo', 'foo' => 'olá'], + ]]; $this->assertEquals(<<<'CSV' foo,bar.0.id,bar.0.1,bar.1.baz,bar.1.foo @@ -113,15 +113,15 @@ CSV if ($legacy) { $this->encoder = new CsvEncoder(';', "'", '|', '-'); } else { - $this->encoder = new CsvEncoder(array( + $this->encoder = new CsvEncoder([ CsvEncoder::DELIMITER_KEY => ';', CsvEncoder::ENCLOSURE_KEY => "'", CsvEncoder::ESCAPE_CHAR_KEY => '|', CsvEncoder::KEY_SEPARATOR_KEY => '-', - )); + ]); } - $value = array('a' => 'he\'llo', 'c' => array('d' => 'foo')); + $value = ['a' => 'he\'llo', 'c' => ['d' => 'foo']]; $this->assertEquals(<<<'CSV' a;c-d @@ -133,34 +133,34 @@ CSV public function testEncodeCustomSettingsPassedInContext() { - $value = array('a' => 'he\'llo', 'c' => array('d' => 'foo')); + $value = ['a' => 'he\'llo', 'c' => ['d' => 'foo']]; $this->assertSame(<<<'CSV' a;c-d 'he''llo';foo CSV - , $this->encoder->encode($value, 'csv', array( + , $this->encoder->encode($value, 'csv', [ CsvEncoder::DELIMITER_KEY => ';', CsvEncoder::ENCLOSURE_KEY => "'", CsvEncoder::ESCAPE_CHAR_KEY => '|', CsvEncoder::KEY_SEPARATOR_KEY => '-', - ))); + ])); } public function testEncodeEmptyArray() { - $this->assertEquals("\n\n", $this->encoder->encode(array(), 'csv')); - $this->assertEquals("\n\n", $this->encoder->encode(array(array()), 'csv')); + $this->assertEquals("\n\n", $this->encoder->encode([], 'csv')); + $this->assertEquals("\n\n", $this->encoder->encode([[]], 'csv')); } public function testEncodeVariableStructure() { - $value = array( - array('a' => array('foo', 'bar')), - array('a' => array(), 'b' => 'baz'), - array('a' => array('bar', 'foo'), 'c' => 'pong'), - ); + $value = [ + ['a' => ['foo', 'bar']], + ['a' => [], 'b' => 'baz'], + ['a' => ['bar', 'foo'], 'c' => 'pong'], + ]; $csv = << array( + $context = [ + CsvEncoder::HEADERS_KEY => [ 'b', 'c', - ), - ); - $value = array( - array('a' => 'foo', 'b' => 'bar'), - ); + ], + ]; + $value = [ + ['a' => 'foo', 'b' => 'bar'], + ]; $csv = <<encoder = new CsvEncoder(',', '"', '\\', '.', true); } else { - $this->encoder = new CsvEncoder(array(CsvEncoder::ESCAPE_FORMULAS_KEY => true)); + $this->encoder = new CsvEncoder([CsvEncoder::ESCAPE_FORMULAS_KEY => true]); } $this->assertSame(<<<'CSV' @@ -215,28 +215,28 @@ CSV; " =2+3" CSV - , $this->encoder->encode(array('=2+3'), 'csv')); + , $this->encoder->encode(['=2+3'], 'csv')); $this->assertSame(<<<'CSV' 0 " -2+3" CSV - , $this->encoder->encode(array('-2+3'), 'csv')); + , $this->encoder->encode(['-2+3'], 'csv')); $this->assertSame(<<<'CSV' 0 " +2+3" CSV - , $this->encoder->encode(array('+2+3'), 'csv')); + , $this->encoder->encode(['+2+3'], 'csv')); $this->assertSame(<<<'CSV' 0 " @MyDataColumn" CSV - , $this->encoder->encode(array('@MyDataColumn'), 'csv')); + , $this->encoder->encode(['@MyDataColumn'], 'csv')); } public function testDoNotEncodeFormulas() @@ -246,28 +246,28 @@ CSV =2+3 CSV - , $this->encoder->encode(array('=2+3'), 'csv')); + , $this->encoder->encode(['=2+3'], 'csv')); $this->assertSame(<<<'CSV' 0 -2+3 CSV - , $this->encoder->encode(array('-2+3'), 'csv')); + , $this->encoder->encode(['-2+3'], 'csv')); $this->assertSame(<<<'CSV' 0 +2+3 CSV - , $this->encoder->encode(array('+2+3'), 'csv')); + , $this->encoder->encode(['+2+3'], 'csv')); $this->assertSame(<<<'CSV' 0 @MyDataColumn CSV - , $this->encoder->encode(array('@MyDataColumn'), 'csv')); + , $this->encoder->encode(['@MyDataColumn'], 'csv')); } public function testEncodeFormulasWithSettingsPassedInContext() @@ -277,36 +277,36 @@ CSV " =2+3" CSV - , $this->encoder->encode(array('=2+3'), 'csv', array( + , $this->encoder->encode(['=2+3'], 'csv', [ CsvEncoder::ESCAPE_FORMULAS_KEY => true, - ))); + ])); $this->assertSame(<<<'CSV' 0 " -2+3" CSV - , $this->encoder->encode(array('-2+3'), 'csv', array( + , $this->encoder->encode(['-2+3'], 'csv', [ CsvEncoder::ESCAPE_FORMULAS_KEY => true, - ))); + ])); $this->assertSame(<<<'CSV' 0 " +2+3" CSV - , $this->encoder->encode(array('+2+3'), 'csv', array( + , $this->encoder->encode(['+2+3'], 'csv', [ CsvEncoder::ESCAPE_FORMULAS_KEY => true, - ))); + ])); $this->assertSame(<<<'CSV' 0 " @MyDataColumn" CSV - , $this->encoder->encode(array('@MyDataColumn'), 'csv', array( + , $this->encoder->encode(['@MyDataColumn'], 'csv', [ CsvEncoder::ESCAPE_FORMULAS_KEY => true, - ))); + ])); } public function testSupportsDecoding() @@ -321,7 +321,7 @@ CSV */ public function testDecodeLegacy() { - $expected = array('foo' => 'a', 'bar' => 'b'); + $expected = ['foo' => 'a', 'bar' => 'b']; $this->assertEquals($expected, $this->encoder->decode(<<<'CSV' foo,bar @@ -332,22 +332,22 @@ CSV public function testDecodeAsSingle() { - $expected = array('foo' => 'a', 'bar' => 'b'); + $expected = ['foo' => 'a', 'bar' => 'b']; $this->assertEquals($expected, $this->encoder->decode(<<<'CSV' foo,bar a,b CSV - , 'csv', array(CsvEncoder::AS_COLLECTION_KEY => false))); + , 'csv', [CsvEncoder::AS_COLLECTION_KEY => false])); } public function testDecodeCollection() { - $expected = array( - array('foo' => 'a', 'bar' => 'b'), - array('foo' => 'c', 'bar' => 'd'), - array('foo' => 'f'), - ); + $expected = [ + ['foo' => 'a', 'bar' => 'b'], + ['foo' => 'c', 'bar' => 'd'], + ['foo' => 'f'], + ]; $this->assertEquals($expected, $this->encoder->decode(<<<'CSV' foo,bar @@ -361,28 +361,28 @@ CSV public function testDecode() { - $expected = array( - array('foo' => 'a'), - ); + $expected = [ + ['foo' => 'a'], + ]; $this->assertEquals($expected, $this->encoder->decode(<<<'CSV' foo a CSV - , 'csv', array( + , 'csv', [ CsvEncoder::AS_COLLECTION_KEY => true, // Can be removed in 5.0 - ))); + ])); } public function testDecodeToManyRelation() { - $expected = array( - array('foo' => 'bar', 'relations' => array(array('a' => 'b'), array('a' => 'b'))), - array('foo' => 'bat', 'relations' => array(array('a' => 'b'), array('a' => ''))), - array('foo' => 'bat', 'relations' => array(array('a' => 'b'))), - array('foo' => 'baz', 'relations' => array(array('a' => 'c'), array('a' => 'c'))), - ); + $expected = [ + ['foo' => 'bar', 'relations' => [['a' => 'b'], ['a' => 'b']]], + ['foo' => 'bat', 'relations' => [['a' => 'b'], ['a' => '']]], + ['foo' => 'bat', 'relations' => [['a' => 'b']]], + ['foo' => 'baz', 'relations' => [['a' => 'c'], ['a' => 'c']]], + ]; $this->assertEquals($expected, $this->encoder->decode(<<<'CSV' foo,relations.0.a,relations.1.a @@ -396,10 +396,10 @@ CSV public function testDecodeNestedArrays() { - $expected = array( - array('foo' => 'a', 'bar' => array('baz' => array('bat' => 'b'))), - array('foo' => 'c', 'bar' => array('baz' => array('bat' => 'd'))), - ); + $expected = [ + ['foo' => 'a', 'bar' => ['baz' => ['bat' => 'b']]], + ['foo' => 'c', 'bar' => ['baz' => ['bat' => 'd']]], + ]; $this->assertEquals($expected, $this->encoder->decode(<<<'CSV' foo,bar.baz.bat @@ -424,47 +424,47 @@ CSV if ($legacy) { $this->encoder = new CsvEncoder(';', "'", '|', '-'); } else { - $this->encoder = new CsvEncoder(array( + $this->encoder = new CsvEncoder([ CsvEncoder::DELIMITER_KEY => ';', CsvEncoder::ENCLOSURE_KEY => "'", CsvEncoder::ESCAPE_CHAR_KEY => '|', CsvEncoder::KEY_SEPARATOR_KEY => '-', - )); + ]); } - $expected = array(array('a' => 'hell\'o', 'bar' => array('baz' => 'b'))); + $expected = [['a' => 'hell\'o', 'bar' => ['baz' => 'b']]]; $this->assertEquals($expected, $this->encoder->decode(<<<'CSV' a;bar-baz 'hell''o';b;c CSV - , 'csv', array( + , 'csv', [ CsvEncoder::AS_COLLECTION_KEY => true, // Can be removed in 5.0 - ))); + ])); } public function testDecodeCustomSettingsPassedInContext() { - $expected = array(array('a' => 'hell\'o', 'bar' => array('baz' => 'b'))); + $expected = [['a' => 'hell\'o', 'bar' => ['baz' => 'b']]]; $this->assertEquals($expected, $this->encoder->decode(<<<'CSV' a;bar-baz 'hell''o';b;c CSV - , 'csv', array( + , 'csv', [ CsvEncoder::DELIMITER_KEY => ';', CsvEncoder::ENCLOSURE_KEY => "'", CsvEncoder::ESCAPE_CHAR_KEY => '|', CsvEncoder::KEY_SEPARATOR_KEY => '-', CsvEncoder::AS_COLLECTION_KEY => true, // Can be removed in 5.0 - ))); + ])); } public function testDecodeMalformedCollection() { - $expected = array( - array('foo' => 'a', 'bar' => 'b'), - array('foo' => 'c', 'bar' => 'd'), - array('foo' => 'f'), - ); + $expected = [ + ['foo' => 'a', 'bar' => 'b'], + ['foo' => 'c', 'bar' => 'd'], + ['foo' => 'f'], + ]; $this->assertEquals($expected, $this->encoder->decode(<<<'CSV' foo,bar @@ -478,6 +478,6 @@ CSV public function testDecodeEmptyArray() { - $this->assertEquals(array(), $this->encoder->decode('', 'csv')); + $this->assertEquals([], $this->encoder->decode('', 'csv')); } } diff --git a/src/Symfony/Component/Serializer/Tests/Encoder/XmlEncoderTest.php b/src/Symfony/Component/Serializer/Tests/Encoder/XmlEncoderTest.php index 6ef68c13f9..53b7f7b691 100644 --- a/src/Symfony/Component/Serializer/Tests/Encoder/XmlEncoderTest.php +++ b/src/Symfony/Component/Serializer/Tests/Encoder/XmlEncoderTest.php @@ -32,7 +32,7 @@ class XmlEncoderTest extends TestCase protected function setUp() { $this->encoder = new XmlEncoder(); - $serializer = new Serializer(array(new CustomNormalizer()), array('xml' => new XmlEncoder())); + $serializer = new Serializer([new CustomNormalizer()], ['xml' => new XmlEncoder()]); $this->encoder->setSerializer($serializer); } @@ -74,19 +74,19 @@ class XmlEncoderTest extends TestCase public function testAttributes() { $obj = new ScalarDummy(); - $obj->xmlFoo = array( - 'foo-bar' => array( + $obj->xmlFoo = [ + 'foo-bar' => [ '@id' => 1, '@name' => 'Bar', - ), - 'Foo' => array( + ], + 'Foo' => [ 'Bar' => 'Test', '@Type' => 'test', - ), + ], 'föo_bär' => 'a', - 'Bar' => array(1, 2, 3), + 'Bar' => [1, 2, 3], 'a' => 'b', - ); + ]; $expected = ''."\n". ''. ''. @@ -103,11 +103,11 @@ class XmlEncoderTest extends TestCase public function testElementNameValid() { $obj = new ScalarDummy(); - $obj->xmlFoo = array( + $obj->xmlFoo = [ 'foo-bar' => 'a', 'foo_bar' => 'a', 'föo_bär' => 'a', - ); + ]; $expected = ''."\n". ''. @@ -122,7 +122,7 @@ class XmlEncoderTest extends TestCase public function testEncodeSimpleXML() { $xml = simplexml_load_string('Peter'); - $array = array('person' => $xml); + $array = ['person' => $xml]; $expected = ''."\n". 'Peter'."\n"; @@ -133,35 +133,35 @@ class XmlEncoderTest extends TestCase public function testEncodeXmlAttributes() { $xml = simplexml_load_string('Peter'); - $array = array('person' => $xml); + $array = ['person' => $xml]; $expected = ''."\n". 'Peter'."\n"; - $context = array( + $context = [ 'xml_version' => '1.1', 'xml_encoding' => 'utf-8', 'xml_standalone' => true, - ); + ]; $this->assertSame($expected, $this->encoder->encode($array, 'xml', $context)); } public function testEncodeRemovingEmptyTags() { - $array = array('person' => array('firstname' => 'Peter', 'lastname' => null)); + $array = ['person' => ['firstname' => 'Peter', 'lastname' => null]]; $expected = ''."\n". 'Peter'."\n"; - $context = array('remove_empty_tags' => true); + $context = ['remove_empty_tags' => true]; $this->assertSame($expected, $this->encoder->encode($array, 'xml', $context)); } public function testEncodeNotRemovingEmptyTags() { - $array = array('person' => array('firstname' => 'Peter', 'lastname' => null)); + $array = ['person' => ['firstname' => 'Peter', 'lastname' => null]]; $expected = ''."\n". 'Peter'."\n"; @@ -171,7 +171,7 @@ class XmlEncoderTest extends TestCase public function testContext() { - $array = array('person' => array('name' => 'George Abitbol')); + $array = ['person' => ['name' => 'George Abitbol']]; $expected = <<<'XML' @@ -182,19 +182,19 @@ class XmlEncoderTest extends TestCase XML; - $context = array( + $context = [ 'xml_format_output' => true, - ); + ]; $this->assertSame($expected, $this->encoder->encode($array, 'xml', $context)); } public function testEncodeScalarRootAttributes() { - $array = array( + $array = [ '#' => 'Paul', '@gender' => 'm', - ); + ]; $expected = ''."\n". 'Paul'."\n"; @@ -204,10 +204,10 @@ XML; public function testEncodeRootAttributes() { - $array = array( + $array = [ 'firstname' => 'Paul', '@gender' => 'm', - ); + ]; $expected = ''."\n". 'Paul'."\n"; @@ -217,9 +217,9 @@ XML; public function testEncodeCdataWrapping() { - $array = array( + $array = [ 'firstname' => 'Paul ', - ); + ]; $expected = ''."\n". ']]>'."\n"; @@ -229,9 +229,9 @@ XML; public function testEncodeScalarWithAttribute() { - $array = array( - 'person' => array('@gender' => 'M', '#' => 'Peter'), - ); + $array = [ + 'person' => ['@gender' => 'M', '#' => 'Peter'], + ]; $expected = ''."\n". 'Peter'."\n"; @@ -254,7 +254,7 @@ XML; Name XML; - $this->assertSame(array('@index' => 182077241760011681341821060401202210011000045913000000017100, '#' => 'Name'), $this->encoder->decode($source, 'xml')); + $this->assertSame(['@index' => 182077241760011681341821060401202210011000045913000000017100, '#' => 'Name'], $this->encoder->decode($source, 'xml')); } public function testDecodeNegativeIntAttribute() @@ -264,7 +264,7 @@ XML; Name XML; - $this->assertSame(array('@index' => -1234, '#' => 'Name'), $this->encoder->decode($source, 'xml')); + $this->assertSame(['@index' => -1234, '#' => 'Name'], $this->encoder->decode($source, 'xml')); } public function testDecodeFloatAttribute() @@ -274,7 +274,7 @@ XML; Name XML; - $this->assertSame(array('@index' => -12.11, '#' => 'Name'), $this->encoder->decode($source, 'xml')); + $this->assertSame(['@index' => -12.11, '#' => 'Name'], $this->encoder->decode($source, 'xml')); } public function testDecodeNegativeFloatAttribute() @@ -284,7 +284,7 @@ XML; Name XML; - $this->assertSame(array('@index' => -12.11, '#' => 'Name'), $this->encoder->decode($source, 'xml')); + $this->assertSame(['@index' => -12.11, '#' => 'Name'], $this->encoder->decode($source, 'xml')); } public function testNoTypeCastAttribute() @@ -296,16 +296,16 @@ XML; XML; - $data = $this->encoder->decode($source, 'xml', array('xml_type_cast_attributes' => false)); - $expected = array( + $data = $this->encoder->decode($source, 'xml', ['xml_type_cast_attributes' => false]); + $expected = [ '@a' => '018', '@b' => '-12.11', - 'node' => array( + 'node' => [ '@a' => '018', '@b' => '-12.11', '#' => '', - ), - ); + ], + ]; $this->assertSame($expected, $data); } @@ -327,14 +327,14 @@ XML; public function testEncodeSerializerXmlRootNodeNameOption() { - $options = array('xml_root_node_name' => 'test'); + $options = ['xml_root_node_name' => 'test']; $this->encoder = new XmlEncoder(); - $serializer = new Serializer(array(), array('xml' => new XmlEncoder())); + $serializer = new Serializer([], ['xml' => new XmlEncoder()]); $this->encoder->setSerializer($serializer); - $array = array( - 'person' => array('@gender' => 'M', '#' => 'Peter'), - ); + $array = [ + 'person' => ['@gender' => 'M', '#' => 'Peter'], + ]; $expected = ''."\n". 'Peter'."\n"; @@ -345,7 +345,7 @@ XML; public function testEncodeTraversableWhenNormalizable() { $this->encoder = new XmlEncoder(); - $serializer = new Serializer(array(new CustomNormalizer()), array('xml' => new XmlEncoder())); + $serializer = new Serializer([new CustomNormalizer()], ['xml' => new XmlEncoder()]); $this->encoder->setSerializer($serializer); $expected = <<<'XML' @@ -367,9 +367,9 @@ XML; public function testDecodeCdataWrapping() { - $expected = array( + $expected = [ 'firstname' => 'Paul ', - ); + ]; $xml = ''."\n". ']]>'."\n"; @@ -379,9 +379,9 @@ XML; public function testDecodeCdataWrappingAndWhitespace() { - $expected = array( + $expected = [ 'firstname' => 'Paul ', - ); + ]; $xml = ''."\n". ''."\n". @@ -403,9 +403,9 @@ XML; $source = ''."\n". 'Peter'."\n"; - $expected = array( - 'person' => array('@gender' => 'M', '#' => 'Peter'), - ); + $expected = [ + 'person' => ['@gender' => 'M', '#' => 'Peter'], + ]; $this->assertEquals($expected, $this->encoder->decode($source, 'xml')); } @@ -415,10 +415,10 @@ XML; $source = ''."\n". 'Peter'."\n"; - $expected = array( + $expected = [ '#' => 'Peter', '@gender' => 'M', - ); + ]; $this->assertEquals($expected, $this->encoder->decode($source, 'xml')); } @@ -428,11 +428,11 @@ XML; $source = ''."\n". 'PeterMac Calloway'."\n"; - $expected = array( + $expected = [ 'firstname' => 'Peter', 'lastname' => 'Mac Calloway', '@gender' => 'M', - ); + ]; $this->assertEquals($expected, $this->encoder->decode($source, 'xml')); } @@ -447,12 +447,12 @@ XML; ''. ''."\n"; - $expected = array( - 'people' => array('person' => array( - array('firstname' => 'Benjamin', 'lastname' => 'Alexandre'), - array('firstname' => 'Damien', 'lastname' => 'Clay'), - )), - ); + $expected = [ + 'people' => ['person' => [ + ['firstname' => 'Benjamin', 'lastname' => 'Alexandre'], + ['firstname' => 'Damien', 'lastname' => 'Clay'], + ]], + ]; $this->assertEquals($expected, $this->encoder->decode($source, 'xml')); } @@ -510,10 +510,10 @@ XML; XML; - $expected = array('person' => array( - array('firstname' => 'Benjamin', 'lastname' => 'Alexandre'), - array('firstname' => 'Damien', 'lastname' => 'Clay'), - )); + $expected = ['person' => [ + ['firstname' => 'Benjamin', 'lastname' => 'Alexandre'], + ['firstname' => 'Damien', 'lastname' => 'Clay'], + ]]; $this->assertEquals($expected, $this->encoder->decode($source, 'xml')); } @@ -537,10 +537,10 @@ XML; XML; - $expected = array('person' => array( - array('firstname' => 'Benjamin', 'lastname' => 'Alexandre'), - array('firstname' => 'Damien', 'lastname' => 'Clay'), - )); + $expected = ['person' => [ + ['firstname' => 'Benjamin', 'lastname' => 'Alexandre'], + ['firstname' => 'Damien', 'lastname' => 'Clay'], + ]]; $this->assertEquals($expected, $this->encoder->decode($source, 'xml')); } @@ -573,20 +573,20 @@ XML; XML; if ($legacy) { - $this->encoder = new XmlEncoder('people', null, array(XML_PI_NODE)); + $this->encoder = new XmlEncoder('people', null, [XML_PI_NODE]); } else { - $this->encoder = new XmlEncoder(array( + $this->encoder = new XmlEncoder([ XmlEncoder::ROOT_NODE_NAME => 'people', - XmlEncoder::DECODER_IGNORED_NODE_TYPES => array(XML_PI_NODE), - )); + XmlEncoder::DECODER_IGNORED_NODE_TYPES => [XML_PI_NODE], + ]); } - $serializer = new Serializer(array(new CustomNormalizer()), array('xml' => new XmlEncoder())); + $serializer = new Serializer([new CustomNormalizer()], ['xml' => new XmlEncoder()]); $this->encoder->setSerializer($serializer); - $expected = array('person' => array( - array('firstname' => 'Benjamin', 'lastname' => 'Alexandre', '#comment' => ' This comment should be decoded. '), - array('firstname' => 'Damien', 'lastname' => 'Clay'), - )); + $expected = ['person' => [ + ['firstname' => 'Benjamin', 'lastname' => 'Alexandre', '#comment' => ' This comment should be decoded. '], + ['firstname' => 'Damien', 'lastname' => 'Clay'], + ]]; $this->assertEquals($expected, $this->encoder->decode($source, 'xml')); } @@ -606,9 +606,9 @@ XML; if ($legacy) { $this->encoder = new XmlEncoder('response', null); } else { - $this->encoder = new XmlEncoder(array(XmlEncoder::ROOT_NODE_NAME => 'response')); + $this->encoder = new XmlEncoder([XmlEncoder::ROOT_NODE_NAME => 'response']); } - $serializer = new Serializer(array(new CustomNormalizer()), array('xml' => new XmlEncoder())); + $serializer = new Serializer([new CustomNormalizer()], ['xml' => new XmlEncoder()]); $this->encoder->setSerializer($serializer); $source = <<<'XML' @@ -620,47 +620,47 @@ XML; XML; - $expected = array( + $expected = [ '@nodeType' => 'order_row', '@virtualEntity' => 'true', - 'order_row' => array(array( - 'id' => array(16), - 'test' => array(16), - )), - ); + 'order_row' => [[ + 'id' => [16], + 'test' => [16], + ]], + ]; - $this->assertEquals($expected, $this->encoder->decode($source, 'xml', array('as_collection' => true))); + $this->assertEquals($expected, $this->encoder->decode($source, 'xml', ['as_collection' => true])); } public function testDecodeWithoutItemHash() { $obj = new ScalarDummy(); - $obj->xmlFoo = array( - 'foo-bar' => array( + $obj->xmlFoo = [ + 'foo-bar' => [ '@key' => 'value', - 'item' => array('@key' => 'key', 'key-val' => 'val'), - ), - 'Foo' => array( + 'item' => ['@key' => 'key', 'key-val' => 'val'], + ], + 'Foo' => [ 'Bar' => 'Test', '@Type' => 'test', - ), + ], 'föo_bär' => 'a', - 'Bar' => array(1, 2, 3), + 'Bar' => [1, 2, 3], 'a' => 'b', - ); - $expected = array( - 'foo-bar' => array( + ]; + $expected = [ + 'foo-bar' => [ '@key' => 'value', - 'key' => array('@key' => 'key', 'key-val' => 'val'), - ), - 'Foo' => array( + 'key' => ['@key' => 'key', 'key-val' => 'val'], + ], + 'Foo' => [ 'Bar' => 'Test', '@Type' => 'test', - ), + ], 'föo_bär' => 'a', - 'Bar' => array(1, 2, 3), + 'Bar' => [1, 2, 3], 'a' => 'b', - ); + ]; $xml = $this->encoder->encode($obj, 'xml'); $this->assertEquals($expected, $this->encoder->decode($xml, 'xml')); } @@ -720,7 +720,7 @@ XML; protected function getNamespacedArray() { - return array( + return [ '@xmlns' => 'http://www.w3.org/2005/Atom', '@xmlns:app' => 'http://www.w3.org/2007/app', '@xmlns:media' => 'http://search.yahoo.com/mrss/', @@ -728,36 +728,36 @@ XML; '@xmlns:yt' => 'http://gdata.youtube.com/schemas/2007', 'qux' => '1', 'app:foo' => 'foo', - 'yt:bar' => array('a', 'b'), - 'media:baz' => array( + 'yt:bar' => ['a', 'b'], + 'media:baz' => [ 'media:key' => 'val', 'media:key2' => 'val', 'A B' => 'bar', - 'item' => array( - array( + 'item' => [ + [ 'title' => 'title1', - ), - array( + ], + [ 'title' => 'title2', - ), - ), - 'Barry' => array( + ], + ], + 'Barry' => [ '@size' => 'large', - 'FooBar' => array( + 'FooBar' => [ 'Baz' => 'Ed', '@gd:id' => 1, - ), - ), - ), - ); + ], + ], + ], + ]; } protected function getObject() { $obj = new Dummy(); $obj->foo = 'foo'; - $obj->bar = array('a', 'b'); - $obj->baz = array('key' => 'val', 'key2' => 'val', 'A B' => 'bar', 'item' => array(array('title' => 'title1'), array('title' => 'title2')), 'Barry' => array('FooBar' => array('Baz' => 'Ed', '@id' => 1))); + $obj->bar = ['a', 'b']; + $obj->baz = ['key' => 'val', 'key2' => 'val', 'A B' => 'bar', 'item' => [['title' => 'title1'], ['title' => 'title2']], 'Barry' => ['FooBar' => ['Baz' => 'Ed', '@id' => 1]]]; $obj->qux = '1'; return $obj; @@ -771,7 +771,7 @@ XML; XML; - $actualXml = $this->encoder->encode(array('foo' => true, 'bar' => false), 'xml'); + $actualXml = $this->encoder->encode(['foo' => true, 'bar' => false], 'xml'); $this->assertEquals($expectedXml, $actualXml); } @@ -780,7 +780,7 @@ XML; { $xmlEncoder = $this->createXmlEncoderWithDateTimeNormalizer(); - $actualXml = $xmlEncoder->encode(array('dateTime' => new \DateTime($this->exampleDateTimeString)), 'xml'); + $actualXml = $xmlEncoder->encode(['dateTime' => new \DateTime($this->exampleDateTimeString)], 'xml'); $this->assertEquals($this->createXmlWithDateTime(), $actualXml); } @@ -789,7 +789,7 @@ XML; { $xmlEncoder = $this->createXmlEncoderWithDateTimeNormalizer(); - $actualXml = $xmlEncoder->encode(array('foo' => array('@dateTime' => new \DateTime($this->exampleDateTimeString))), 'xml'); + $actualXml = $xmlEncoder->encode(['foo' => ['@dateTime' => new \DateTime($this->exampleDateTimeString)]], 'xml'); $this->assertEquals($this->createXmlWithDateTimeField(), $actualXml); } @@ -802,7 +802,7 @@ XML; XML; - $data = array('#comment' => ' foo '); + $data = ['#comment' => ' foo ']; $this->assertEquals($expected, $this->encoder->encode($data, 'xml')); } @@ -820,17 +820,17 @@ XML; private function doTestEncodeWithoutPi(bool $legacy = false) { if ($legacy) { - $encoder = new XmlEncoder('response', null, array(), array(XML_PI_NODE)); + $encoder = new XmlEncoder('response', null, [], [XML_PI_NODE]); } else { - $encoder = new XmlEncoder(array( + $encoder = new XmlEncoder([ XmlEncoder::ROOT_NODE_NAME => 'response', - XmlEncoder::ENCODER_IGNORED_NODE_TYPES => array(XML_PI_NODE), - )); + XmlEncoder::ENCODER_IGNORED_NODE_TYPES => [XML_PI_NODE], + ]); } $expected = ''; - $this->assertEquals($expected, $encoder->encode(array(), 'xml')); + $this->assertEquals($expected, $encoder->encode([], 'xml')); } public function testEncodeWithoutComment() @@ -846,12 +846,12 @@ XML; private function doTestEncodeWithoutComment(bool $legacy = false) { if ($legacy) { - $encoder = new XmlEncoder('response', null, array(), array(XML_COMMENT_NODE)); + $encoder = new XmlEncoder('response', null, [], [XML_COMMENT_NODE]); } else { - $encoder = new XmlEncoder(array( + $encoder = new XmlEncoder([ XmlEncoder::ROOT_NODE_NAME => 'response', - XmlEncoder::ENCODER_IGNORED_NODE_TYPES => array(XML_COMMENT_NODE), - )); + XmlEncoder::ENCODER_IGNORED_NODE_TYPES => [XML_COMMENT_NODE], + ]); } $expected = <<<'XML' @@ -860,7 +860,7 @@ XML; XML; - $data = array('#comment' => ' foo '); + $data = ['#comment' => ' foo ']; $this->assertEquals($expected, $encoder->encode($data, 'xml')); } @@ -871,7 +871,7 @@ XML; private function createXmlEncoderWithDateTimeNormalizer() { $encoder = new XmlEncoder(); - $serializer = new Serializer(array($this->createMockDateTimeNormalizer()), array('xml' => new XmlEncoder())); + $serializer = new Serializer([$this->createMockDateTimeNormalizer()], ['xml' => new XmlEncoder()]); $encoder->setSerializer($serializer); return $encoder; @@ -887,7 +887,7 @@ XML; $mock ->expects($this->once()) ->method('normalize') - ->with(new \DateTime($this->exampleDateTimeString), 'xml', array()) + ->with(new \DateTime($this->exampleDateTimeString), 'xml', []) ->willReturn($this->exampleDateTimeString); $mock diff --git a/src/Symfony/Component/Serializer/Tests/NameConverter/MetadataAwareNameConverterTest.php b/src/Symfony/Component/Serializer/Tests/NameConverter/MetadataAwareNameConverterTest.php index 40fbc396f6..f4c5c5b305 100644 --- a/src/Symfony/Component/Serializer/Tests/NameConverter/MetadataAwareNameConverterTest.php +++ b/src/Symfony/Component/Serializer/Tests/NameConverter/MetadataAwareNameConverterTest.php @@ -98,19 +98,19 @@ final class MetadataAwareNameConverterTest extends TestCase public function attributeProvider() { - return array( - array('foo', 'baz'), - array('bar', 'qux'), - array('quux', 'quux'), - ); + return [ + ['foo', 'baz'], + ['bar', 'qux'], + ['quux', 'quux'], + ]; } public function fallbackAttributeProvider() { - return array( - array('foo', 'baz'), - array('bar', 'qux'), - array('quux', 'QUUX'), - ); + return [ + ['foo', 'baz'], + ['bar', 'qux'], + ['quux', 'QUUX'], + ]; } } diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/AbstractNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/AbstractNormalizerTest.php index 46f5bb46f2..fbf33aa7c6 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/AbstractNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/AbstractNormalizerTest.php @@ -33,8 +33,8 @@ class AbstractNormalizerTest extends TestCase protected function setUp() { - $loader = $this->getMockBuilder('Symfony\Component\Serializer\Mapping\Loader\LoaderChain')->setConstructorArgs(array(array()))->getMock(); - $this->classMetadata = $this->getMockBuilder('Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory')->setConstructorArgs(array($loader))->getMock(); + $loader = $this->getMockBuilder('Symfony\Component\Serializer\Mapping\Loader\LoaderChain')->setConstructorArgs([[]])->getMock(); + $this->classMetadata = $this->getMockBuilder('Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory')->setConstructorArgs([$loader])->getMock(); $this->normalizer = new AbstractNormalizerDummy($this->classMetadata); } @@ -60,11 +60,11 @@ class AbstractNormalizerTest extends TestCase $this->classMetadata->method('getMetadataFor')->willReturn($classMetadata); - $result = $this->normalizer->getAllowedAttributes('c', array(AbstractNormalizer::GROUPS => array('test')), true); - $this->assertEquals(array('a2', 'a4'), $result); + $result = $this->normalizer->getAllowedAttributes('c', [AbstractNormalizer::GROUPS => ['test']], true); + $this->assertEquals(['a2', 'a4'], $result); - $result = $this->normalizer->getAllowedAttributes('c', array(AbstractNormalizer::GROUPS => array('other')), true); - $this->assertEquals(array('a3', 'a4'), $result); + $result = $this->normalizer->getAllowedAttributes('c', [AbstractNormalizer::GROUPS => ['other']], true); + $this->assertEquals(['a3', 'a4'], $result); } public function testGetAllowedAttributesAsObjects() @@ -89,24 +89,24 @@ class AbstractNormalizerTest extends TestCase $this->classMetadata->method('getMetadataFor')->willReturn($classMetadata); - $result = $this->normalizer->getAllowedAttributes('c', array(AbstractNormalizer::GROUPS => array('test')), false); - $this->assertEquals(array($a2, $a4), $result); + $result = $this->normalizer->getAllowedAttributes('c', [AbstractNormalizer::GROUPS => ['test']], false); + $this->assertEquals([$a2, $a4], $result); - $result = $this->normalizer->getAllowedAttributes('c', array(AbstractNormalizer::GROUPS => 'test'), false); - $this->assertEquals(array($a2, $a4), $result); + $result = $this->normalizer->getAllowedAttributes('c', [AbstractNormalizer::GROUPS => 'test'], false); + $this->assertEquals([$a2, $a4], $result); - $result = $this->normalizer->getAllowedAttributes('c', array(AbstractNormalizer::GROUPS => array('other')), false); - $this->assertEquals(array($a3, $a4), $result); + $result = $this->normalizer->getAllowedAttributes('c', [AbstractNormalizer::GROUPS => ['other']], false); + $this->assertEquals([$a3, $a4], $result); } public function testObjectToPopulateWithProxy() { $proxyDummy = new ProxyDummy(); - $context = array(AbstractNormalizer::OBJECT_TO_POPULATE => $proxyDummy); + $context = [AbstractNormalizer::OBJECT_TO_POPULATE => $proxyDummy]; $normalizer = new ObjectNormalizer(); - $normalizer->denormalize(array('foo' => 'bar'), 'Symfony\Component\Serializer\Tests\Fixtures\ToBeProxyfiedDummy', null, $context); + $normalizer->denormalize(['foo' => 'bar'], 'Symfony\Component\Serializer\Tests\Fixtures\ToBeProxyfiedDummy', null, $context); $this->assertSame('bar', $proxyDummy->getFoo()); } @@ -114,7 +114,7 @@ class AbstractNormalizerTest extends TestCase public function testObjectWithStaticConstructor() { $normalizer = new StaticConstructorNormalizer(); - $dummy = $normalizer->denormalize(array('foo' => 'baz'), StaticConstructorDummy::class); + $dummy = $normalizer->denormalize(['foo' => 'baz'], StaticConstructorDummy::class); $this->assertInstanceOf(StaticConstructorDummy::class, $dummy); $this->assertEquals('baz', $dummy->quz); @@ -127,7 +127,7 @@ class AbstractNormalizerTest extends TestCase public function testObjectWithNullableConstructorArgument() { $normalizer = new ObjectNormalizer(); - $dummy = $normalizer->denormalize(array('foo' => null), NullableConstructorArgumentDummy::class); + $dummy = $normalizer->denormalize(['foo' => null], NullableConstructorArgumentDummy::class); $this->assertNull($dummy->getFoo()); } diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/AbstractObjectNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/AbstractObjectNormalizerTest.php index 0b69dad90e..a45009d233 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/AbstractObjectNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/AbstractObjectNormalizerTest.php @@ -168,8 +168,8 @@ class AbstractObjectNormalizerTest extends TestCase $dummy->bar = 'present'; $normalizer = new ObjectNormalizer(); - $result = $normalizer->normalize($dummy, null, array(AbstractObjectNormalizer::SKIP_NULL_VALUES => true)); - $this->assertSame(array('bar' => 'present'), $result); + $result = $normalizer->normalize($dummy, null, [AbstractObjectNormalizer::SKIP_NULL_VALUES => true]); + $this->assertSame(['bar' => 'present'], $result); } } diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/DateIntervalNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/DateIntervalNormalizerTest.php index 707921650f..b8ac21b5a6 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/DateIntervalNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/DateIntervalNormalizerTest.php @@ -71,7 +71,7 @@ class DateIntervalNormalizerTest extends TestCase private function doTestNormalizeUsingFormatPassedInConstructor($format, $output, $input, bool $legacy = false) { - $normalizer = $legacy ? new DateIntervalNormalizer($format) : new DateIntervalNormalizer(array(DateIntervalNormalizer::FORMAT_KEY => $format)); + $normalizer = $legacy ? new DateIntervalNormalizer($format) : new DateIntervalNormalizer([DateIntervalNormalizer::FORMAT_KEY => $format]); $this->assertEquals($output, $normalizer->normalize(new \DateInterval($input))); } @@ -121,7 +121,7 @@ class DateIntervalNormalizerTest extends TestCase private function doTestDenormalizeUsingFormatPassedInConstructor($format, $input, $output, bool $legacy = false) { - $normalizer = $legacy ? new DateIntervalNormalizer($format) : new DateIntervalNormalizer(array(DateIntervalNormalizer::FORMAT_KEY => $format)); + $normalizer = $legacy ? new DateIntervalNormalizer($format) : new DateIntervalNormalizer([DateIntervalNormalizer::FORMAT_KEY => $format]); $this->assertDateIntervalEquals(new \DateInterval($output), $normalizer->denormalize($input, \DateInterval::class)); } diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/DateTimeNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/DateTimeNormalizerTest.php index 695837f054..7d087d7d5e 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/DateTimeNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/DateTimeNormalizerTest.php @@ -59,7 +59,7 @@ class DateTimeNormalizerTest extends TestCase private function doTestNormalizeUsingFormatPassedInConstructor(bool $legacy = false) { - $normalizer = $legacy ? new DateTimeNormalizer('y') : new DateTimeNormalizer(array(DateTimeNormalizer::FORMAT_KEY => 'y')); + $normalizer = $legacy ? new DateTimeNormalizer('y') : new DateTimeNormalizer([DateTimeNormalizer::FORMAT_KEY => 'y']); $this->assertEquals('16', $normalizer->normalize(new \DateTime('2016/01/01', new \DateTimeZone('UTC')))); } @@ -78,7 +78,7 @@ class DateTimeNormalizerTest extends TestCase if ($legacy) { $normalizer = new DateTimeNormalizer(\DateTime::RFC3339, new \DateTimeZone('Japan')); } else { - $normalizer = new DateTimeNormalizer(array(DateTimeNormalizer::TIMEZONE_KEY => new \DateTimeZone('Japan'))); + $normalizer = new DateTimeNormalizer([DateTimeNormalizer::TIMEZONE_KEY => new \DateTimeZone('Japan')]); } $this->assertSame('2016-12-01T00:00:00+09:00', $normalizer->normalize(new \DateTime('2016/12/01', new \DateTimeZone('Japan')))); @@ -217,7 +217,7 @@ class DateTimeNormalizerTest extends TestCase { $timezone = new \DateTimeZone('Japan'); $expected = new \DateTime('2016/12/01 17:35:00', $timezone); - $normalizer = $legacy ? new DateTimeNormalizer(null, $timezone) : new DateTimeNormalizer(array(DateTimeNormalizer::TIMEZONE_KEY => $timezone)); + $normalizer = $legacy ? new DateTimeNormalizer(null, $timezone) : new DateTimeNormalizer([DateTimeNormalizer::TIMEZONE_KEY => $timezone]); $this->assertEquals($expected, $normalizer->denormalize('2016.12.01 17:35:00', \DateTime::class, null, [ DateTimeNormalizer::FORMAT_KEY => 'Y.m.d H:i:s', diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/GetSetMethodNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/GetSetMethodNormalizerTest.php index 07277579b3..37948bef47 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/GetSetMethodNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/GetSetMethodNormalizerTest.php @@ -41,7 +41,7 @@ class GetSetMethodNormalizerTest extends TestCase $this->createNormalizer(); } - private function createNormalizer(array $defaultContext = array()) + private function createNormalizer(array $defaultContext = []) { $this->serializer = $this->getMockBuilder(__NAMESPACE__.'\SerializerNormalizer')->getMock(); $this->normalizer = new GetSetMethodNormalizer(null, null, null, null, null, $defaultContext); @@ -72,14 +72,14 @@ class GetSetMethodNormalizerTest extends TestCase ; $this->assertEquals( - array( + [ 'foo' => 'foo', 'bar' => 'bar', 'baz' => true, 'fooBar' => 'foobar', 'camelCase' => 'camelcase', 'object' => 'string_object', - ), + ], $this->normalizer->normalize($obj, 'any') ); } @@ -87,7 +87,7 @@ class GetSetMethodNormalizerTest extends TestCase public function testDenormalize() { $obj = $this->normalizer->denormalize( - array('foo' => 'foo', 'bar' => 'bar', 'baz' => true, 'fooBar' => 'foobar'), + ['foo' => 'foo', 'bar' => 'bar', 'baz' => true, 'fooBar' => 'foobar'], __NAMESPACE__.'\GetSetDummy', 'any' ); @@ -115,7 +115,7 @@ class GetSetMethodNormalizerTest extends TestCase public function testConstructorDenormalize() { $obj = $this->normalizer->denormalize( - array('foo' => 'foo', 'bar' => 'bar', 'baz' => true, 'fooBar' => 'foobar'), + ['foo' => 'foo', 'bar' => 'bar', 'baz' => true, 'fooBar' => 'foobar'], __NAMESPACE__.'\GetConstructorDummy', 'any'); $this->assertEquals('foo', $obj->getFoo()); $this->assertEquals('bar', $obj->getBar()); @@ -125,7 +125,7 @@ class GetSetMethodNormalizerTest extends TestCase public function testConstructorDenormalizeWithNullArgument() { $obj = $this->normalizer->denormalize( - array('foo' => 'foo', 'bar' => null, 'baz' => true), + ['foo' => 'foo', 'bar' => null, 'baz' => true], __NAMESPACE__.'\GetConstructorDummy', 'any'); $this->assertEquals('foo', $obj->getFoo()); $this->assertNull($obj->getBar()); @@ -135,36 +135,36 @@ class GetSetMethodNormalizerTest extends TestCase public function testConstructorDenormalizeWithMissingOptionalArgument() { $obj = $this->normalizer->denormalize( - array('foo' => 'test', 'baz' => array(1, 2, 3)), + ['foo' => 'test', 'baz' => [1, 2, 3]], __NAMESPACE__.'\GetConstructorOptionalArgsDummy', 'any'); $this->assertEquals('test', $obj->getFoo()); - $this->assertEquals(array(), $obj->getBar()); - $this->assertEquals(array(1, 2, 3), $obj->getBaz()); + $this->assertEquals([], $obj->getBar()); + $this->assertEquals([1, 2, 3], $obj->getBaz()); } public function testConstructorDenormalizeWithOptionalDefaultArgument() { $obj = $this->normalizer->denormalize( - array('bar' => 'test'), + ['bar' => 'test'], __NAMESPACE__.'\GetConstructorArgsWithDefaultValueDummy', 'any'); - $this->assertEquals(array(), $obj->getFoo()); + $this->assertEquals([], $obj->getFoo()); $this->assertEquals('test', $obj->getBar()); } public function testConstructorDenormalizeWithVariadicArgument() { $obj = $this->normalizer->denormalize( - array('foo' => array(1, 2, 3)), + ['foo' => [1, 2, 3]], 'Symfony\Component\Serializer\Tests\Fixtures\VariadicConstructorArgsDummy', 'any'); - $this->assertEquals(array(1, 2, 3), $obj->getFoo()); + $this->assertEquals([1, 2, 3], $obj->getFoo()); } public function testConstructorDenormalizeWithMissingVariadicArgument() { $obj = $this->normalizer->denormalize( - array(), + [], 'Symfony\Component\Serializer\Tests\Fixtures\VariadicConstructorArgsDummy', 'any'); - $this->assertEquals(array(), $obj->getFoo()); + $this->assertEquals([], $obj->getFoo()); } public function testConstructorWithObjectDenormalize() @@ -181,7 +181,7 @@ class GetSetMethodNormalizerTest extends TestCase public function testConstructorWArgWithPrivateMutator() { - $obj = $this->normalizer->denormalize(array('foo' => 'bar'), __NAMESPACE__.'\ObjectConstructorArgsWithPrivateMutatorDummy', 'any'); + $obj = $this->normalizer->denormalize(['foo' => 'bar'], __NAMESPACE__.'\ObjectConstructorArgsWithPrivateMutatorDummy', 'any'); $this->assertEquals('bar', $obj->getFoo()); } @@ -199,18 +199,18 @@ class GetSetMethodNormalizerTest extends TestCase $obj->setKevin('kevin'); $obj->setCoopTilleuls('coopTilleuls'); - $this->assertEquals(array( + $this->assertEquals([ 'bar' => 'bar', - ), $this->normalizer->normalize($obj, null, array(GetSetMethodNormalizer::GROUPS => array('c')))); + ], $this->normalizer->normalize($obj, null, [GetSetMethodNormalizer::GROUPS => ['c']])); - $this->assertEquals(array( + $this->assertEquals([ 'symfony' => 'symfony', 'foo' => 'foo', 'fooBar' => 'fooBar', 'bar' => 'bar', 'kevin' => 'kevin', 'coopTilleuls' => 'coopTilleuls', - ), $this->normalizer->normalize($obj, null, array(GetSetMethodNormalizer::GROUPS => array('a', 'c')))); + ], $this->normalizer->normalize($obj, null, [GetSetMethodNormalizer::GROUPS => ['a', 'c']])); } public function testGroupsDenormalize() @@ -222,13 +222,13 @@ class GetSetMethodNormalizerTest extends TestCase $obj = new GroupDummy(); $obj->setFoo('foo'); - $toNormalize = array('foo' => 'foo', 'bar' => 'bar'); + $toNormalize = ['foo' => 'foo', 'bar' => 'bar']; $normalized = $this->normalizer->denormalize( $toNormalize, 'Symfony\Component\Serializer\Tests\Fixtures\GroupDummy', null, - array(GetSetMethodNormalizer::GROUPS => array('a')) + [GetSetMethodNormalizer::GROUPS => ['a']] ); $this->assertEquals($obj, $normalized); @@ -238,7 +238,7 @@ class GetSetMethodNormalizerTest extends TestCase $toNormalize, 'Symfony\Component\Serializer\Tests\Fixtures\GroupDummy', null, - array(GetSetMethodNormalizer::GROUPS => array('a', 'b')) + [GetSetMethodNormalizer::GROUPS => ['a', 'b']] ); $this->assertEquals($obj, $normalized); } @@ -255,12 +255,12 @@ class GetSetMethodNormalizerTest extends TestCase $obj->setCoopTilleuls('les-tilleuls.coop'); $this->assertEquals( - array( + [ 'bar' => null, 'foo_bar' => '@dunglas', 'symfony' => '@coopTilleuls', - ), - $this->normalizer->normalize($obj, null, array(GetSetMethodNormalizer::GROUPS => array('name_converter'))) + ], + $this->normalizer->normalize($obj, null, [GetSetMethodNormalizer::GROUPS => ['name_converter']]) ); } @@ -276,12 +276,12 @@ class GetSetMethodNormalizerTest extends TestCase $this->assertEquals( $obj, - $this->normalizer->denormalize(array( + $this->normalizer->denormalize([ 'bar' => null, 'foo_bar' => '@dunglas', 'symfony' => '@coopTilleuls', 'coop_tilleuls' => 'les-tilleuls.coop', - ), 'Symfony\Component\Serializer\Tests\Fixtures\GroupDummy', null, array(GetSetMethodNormalizer::GROUPS => array('name_converter'))) + ], 'Symfony\Component\Serializer\Tests\Fixtures\GroupDummy', null, [GetSetMethodNormalizer::GROUPS => ['name_converter']]) ); } @@ -303,7 +303,7 @@ class GetSetMethodNormalizerTest extends TestCase private function doTestCallbacks($callbacks, $value, $result, $message, bool $legacy = false) { - $legacy ? $this->normalizer->setCallbacks($callbacks) : $this->createNormalizer(array(GetSetMethodNormalizer::CALLBACKS => $callbacks)); + $legacy ? $this->normalizer->setCallbacks($callbacks) : $this->createNormalizer([GetSetMethodNormalizer::CALLBACKS => $callbacks]); $obj = new GetConstructorDummy('', $value, true); $this->assertEquals( @@ -331,8 +331,8 @@ class GetSetMethodNormalizerTest extends TestCase private function doTestUncallableCallbacks(bool $legacy = false) { - $callbacks = array('bar' => null); - $legacy ? $this->normalizer->setCallbacks($callbacks) : $this->createNormalizer(array(GetSetMethodNormalizer::CALLBACKS => $callbacks)); + $callbacks = ['bar' => null]; + $legacy ? $this->normalizer->setCallbacks($callbacks) : $this->createNormalizer([GetSetMethodNormalizer::CALLBACKS => $callbacks]); $obj = new GetConstructorDummy('baz', 'quux', true); @@ -351,8 +351,8 @@ class GetSetMethodNormalizerTest extends TestCase private function doTestIgnoredAttributes(bool $legacy = false) { - $ignoredAttributes = array('foo', 'bar', 'baz', 'camelCase', 'object'); - $legacy ? $this->normalizer->setIgnoredAttributes($ignoredAttributes) : $this->createNormalizer(array(GetSetMethodNormalizer::IGNORED_ATTRIBUTES => $ignoredAttributes)); + $ignoredAttributes = ['foo', 'bar', 'baz', 'camelCase', 'object']; + $legacy ? $this->normalizer->setIgnoredAttributes($ignoredAttributes) : $this->createNormalizer([GetSetMethodNormalizer::IGNORED_ATTRIBUTES => $ignoredAttributes]); $obj = new GetSetDummy(); $obj->setFoo('foo'); @@ -360,45 +360,45 @@ class GetSetMethodNormalizerTest extends TestCase $obj->setBaz(true); $this->assertEquals( - array('fooBar' => 'foobar'), + ['fooBar' => 'foobar'], $this->normalizer->normalize($obj, 'any') ); } public function provideCallbacks() { - return array( - array( - array( + return [ + [ + [ 'bar' => function ($bar) { return 'baz'; }, - ), + ], 'baz', - array('foo' => '', 'bar' => 'baz', 'baz' => true), + ['foo' => '', 'bar' => 'baz', 'baz' => true], 'Change a string', - ), - array( - array( + ], + [ + [ 'bar' => function ($bar) { }, - ), + ], 'baz', - array('foo' => '', 'bar' => null, 'baz' => true), + ['foo' => '', 'bar' => null, 'baz' => true], 'Null an item', - ), - array( - array( + ], + [ + [ 'bar' => function ($bar) { return $bar->format('d-m-Y H:i:s'); }, - ), + ], new \DateTime('2011-09-10 06:30:00'), - array('foo' => '', 'bar' => '10-09-2011 06:30:00', 'baz' => true), + ['foo' => '', 'bar' => '10-09-2011 06:30:00', 'baz' => true], 'Format a date', - ), - array( - array( + ], + [ + [ 'bar' => function ($bars) { $foos = ''; foreach ($bars as $bar) { @@ -407,22 +407,22 @@ class GetSetMethodNormalizerTest extends TestCase return $foos; }, - ), - array(new GetConstructorDummy('baz', '', false), new GetConstructorDummy('quux', '', false)), - array('foo' => '', 'bar' => 'bazquux', 'baz' => true), + ], + [new GetConstructorDummy('baz', '', false), new GetConstructorDummy('quux', '', false)], + ['foo' => '', 'bar' => 'bazquux', 'baz' => true], 'Collect a property', - ), - array( - array( + ], + [ + [ 'bar' => function ($bars) { return \count($bars); }, - ), - array(new GetConstructorDummy('baz', '', false), new GetConstructorDummy('quux', '', false)), - array('foo' => '', 'bar' => 2, 'baz' => true), + ], + [new GetConstructorDummy('baz', '', false), new GetConstructorDummy('quux', '', false)], + ['foo' => '', 'bar' => 2, 'baz' => true], 'Count a property', - ), - ); + ], + ]; } /** @@ -459,8 +459,8 @@ class GetSetMethodNormalizerTest extends TestCase private function doTestUnableToNormalizeCircularReference(bool $legacy = false) { - $legacy ? $this->normalizer->setCircularReferenceLimit(2) : $this->createNormalizer(array(GetSetMethodNormalizer::CIRCULAR_REFERENCE_LIMIT => 2)); - $this->serializer = new Serializer(array($this->normalizer)); + $legacy ? $this->normalizer->setCircularReferenceLimit(2) : $this->createNormalizer([GetSetMethodNormalizer::CIRCULAR_REFERENCE_LIMIT => 2]); + $this->serializer = new Serializer([$this->normalizer]); $this->normalizer->setSerializer($this->serializer); $obj = new CircularReferenceDummy(); @@ -469,16 +469,16 @@ class GetSetMethodNormalizerTest extends TestCase public function testSiblingReference() { - $serializer = new Serializer(array($this->normalizer)); + $serializer = new Serializer([$this->normalizer]); $this->normalizer->setSerializer($serializer); $siblingHolder = new SiblingHolder(); - $expected = array( - 'sibling0' => array('coopTilleuls' => 'Les-Tilleuls.coop'), - 'sibling1' => array('coopTilleuls' => 'Les-Tilleuls.coop'), - 'sibling2' => array('coopTilleuls' => 'Les-Tilleuls.coop'), - ); + $expected = [ + 'sibling0' => ['coopTilleuls' => 'Les-Tilleuls.coop'], + 'sibling1' => ['coopTilleuls' => 'Les-Tilleuls.coop'], + 'sibling2' => ['coopTilleuls' => 'Les-Tilleuls.coop'], + ]; $this->assertEquals($expected, $this->normalizer->normalize($siblingHolder)); } @@ -498,13 +498,13 @@ class GetSetMethodNormalizerTest extends TestCase return \get_class($obj); }; - $legacy ? $this->normalizer->setCircularReferenceHandler($handler) : $this->createNormalizer(array(GetSetMethodNormalizer::CIRCULAR_REFERENCE_HANDLER => $handler)); - $this->serializer = new Serializer(array($this->normalizer)); + $legacy ? $this->normalizer->setCircularReferenceHandler($handler) : $this->createNormalizer([GetSetMethodNormalizer::CIRCULAR_REFERENCE_HANDLER => $handler]); + $this->serializer = new Serializer([$this->normalizer]); $this->normalizer->setSerializer($this->serializer); $obj = new CircularReferenceDummy(); - $expected = array('me' => 'Symfony\Component\Serializer\Tests\Fixtures\CircularReferenceDummy'); + $expected = ['me' => 'Symfony\Component\Serializer\Tests\Fixtures\CircularReferenceDummy']; $this->assertEquals($expected, $this->normalizer->normalize($obj)); } @@ -514,10 +514,10 @@ class GetSetMethodNormalizerTest extends TestCase $dummy->setFoo('foo'); $obj = $this->normalizer->denormalize( - array('bar' => 'bar'), + ['bar' => 'bar'], __NAMESPACE__.'\GetSetDummy', null, - array(GetSetMethodNormalizer::OBJECT_TO_POPULATE => $dummy) + [GetSetMethodNormalizer::OBJECT_TO_POPULATE => $dummy] ); $this->assertEquals($dummy, $obj); @@ -529,13 +529,13 @@ class GetSetMethodNormalizerTest extends TestCase { $this->assertEquals( new GetSetDummy(), - $this->normalizer->denormalize(array('non_existing' => true), __NAMESPACE__.'\GetSetDummy') + $this->normalizer->denormalize(['non_existing' => true], __NAMESPACE__.'\GetSetDummy') ); } public function testDenormalizeShouldNotSetStaticAttribute() { - $obj = $this->normalizer->denormalize(array('staticObject' => true), __NAMESPACE__.'\GetSetDummy'); + $obj = $this->normalizer->denormalize(['staticObject' => true], __NAMESPACE__.'\GetSetDummy'); $this->assertEquals(new GetSetDummy(), $obj); $this->assertNull(GetSetDummy::getStaticObject()); @@ -553,13 +553,13 @@ class GetSetMethodNormalizerTest extends TestCase public function testPrivateSetter() { - $obj = $this->normalizer->denormalize(array('foo' => 'foobar'), __NAMESPACE__.'\ObjectWithPrivateSetterDummy'); + $obj = $this->normalizer->denormalize(['foo' => 'foobar'], __NAMESPACE__.'\ObjectWithPrivateSetterDummy'); $this->assertEquals('bar', $obj->getFoo()); } public function testHasGetterDenormalize() { - $obj = $this->normalizer->denormalize(array('foo' => true), ObjectWithHasGetterDummy::class); + $obj = $this->normalizer->denormalize(['foo' => true], ObjectWithHasGetterDummy::class); $this->assertTrue($obj->hasFoo()); } @@ -569,7 +569,7 @@ class GetSetMethodNormalizerTest extends TestCase $obj->setFoo(true); $this->assertEquals( - array('foo' => true), + ['foo' => true], $this->normalizer->normalize($obj, 'any') ); } @@ -578,7 +578,7 @@ class GetSetMethodNormalizerTest extends TestCase { $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader())); $this->normalizer = new GetSetMethodNormalizer($classMetadataFactory); - $serializer = new Serializer(array($this->normalizer)); + $serializer = new Serializer([$this->normalizer]); $this->normalizer->setSerializer($serializer); $level1 = new MaxDepthDummy(); @@ -596,20 +596,20 @@ class GetSetMethodNormalizerTest extends TestCase $level4->bar = 'level4'; $level3->child = $level4; - $result = $serializer->normalize($level1, null, array(GetSetMethodNormalizer::ENABLE_MAX_DEPTH => true)); + $result = $serializer->normalize($level1, null, [GetSetMethodNormalizer::ENABLE_MAX_DEPTH => true]); - $expected = array( + $expected = [ 'bar' => 'level1', - 'child' => array( + 'child' => [ 'bar' => 'level2', - 'child' => array( + 'child' => [ 'bar' => 'level3', - 'child' => array( + 'child' => [ 'child' => null, - ), - ), - ), - ); + ], + ], + ], + ]; $this->assertEquals($expected, $result); } @@ -744,7 +744,7 @@ class GetConstructorOptionalArgsDummy private $bar; private $baz; - public function __construct($foo, $bar = array(), $baz = array()) + public function __construct($foo, $bar = [], $baz = []) { $this->foo = $foo; $this->bar = $bar; @@ -777,7 +777,7 @@ class GetConstructorArgsWithDefaultValueDummy protected $foo; protected $bar; - public function __construct($foo = array(), $bar) + public function __construct($foo = [], $bar) { $this->foo = $foo; $this->bar = $bar; diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/JsonSerializableNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/JsonSerializableNormalizerTest.php index 14d4cd743b..5f6731b7ca 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/JsonSerializableNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/JsonSerializableNormalizerTest.php @@ -37,7 +37,7 @@ class JsonSerializableNormalizerTest extends TestCase $this->createNormalizer(); } - private function createNormalizer(array $defaultContext = array()) + private function createNormalizer(array $defaultContext = []) { $this->serializer = $this->getMockBuilder(JsonSerializerNormalizer::class)->getMock(); $this->normalizer = new JsonSerializableNormalizer(null, null, $defaultContext); @@ -86,7 +86,7 @@ class JsonSerializableNormalizerTest extends TestCase */ private function doTestCircularNormalize(bool $legacy = false) { - $legacy ? $this->normalizer->setCircularReferenceLimit(1) : $this->createNormalizer(array(JsonSerializableNormalizer::CIRCULAR_REFERENCE_LIMIT => 1)); + $legacy ? $this->normalizer->setCircularReferenceLimit(1) : $this->createNormalizer([JsonSerializableNormalizer::CIRCULAR_REFERENCE_LIMIT => 1]); $this->serializer ->expects($this->once()) diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/ObjectNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/ObjectNormalizerTest.php index b4619c262d..b2bc76a86a 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/ObjectNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/ObjectNormalizerTest.php @@ -53,7 +53,7 @@ class ObjectNormalizerTest extends TestCase $this->createNormalizer(); } - private function createNormalizer(array $defaultContext = array(), ClassMetadataFactoryInterface $classMetadataFactory = null) + private function createNormalizer(array $defaultContext = [], ClassMetadataFactoryInterface $classMetadataFactory = null) { $this->serializer = $this->getMockBuilder(__NAMESPACE__.'\ObjectSerializerNormalizer')->getMock(); $this->normalizer = new ObjectNormalizer($classMetadataFactory, null, null, null, null, null, $defaultContext); @@ -78,14 +78,14 @@ class ObjectNormalizerTest extends TestCase ; $this->assertEquals( - array( + [ 'foo' => 'foo', 'bar' => 'bar', 'baz' => true, 'fooBar' => 'foobar', 'camelCase' => 'camelcase', 'object' => 'string_object', - ), + ], $this->normalizer->normalize($obj, 'any') ); } @@ -93,7 +93,7 @@ class ObjectNormalizerTest extends TestCase public function testDenormalize() { $obj = $this->normalizer->denormalize( - array('foo' => 'foo', 'bar' => 'bar', 'baz' => true, 'fooBar' => 'foobar'), + ['foo' => 'foo', 'bar' => 'bar', 'baz' => true, 'fooBar' => 'foobar'], __NAMESPACE__.'\ObjectDummy', 'any' ); @@ -121,7 +121,7 @@ class ObjectNormalizerTest extends TestCase public function testConstructorDenormalize() { $obj = $this->normalizer->denormalize( - array('foo' => 'foo', 'bar' => 'bar', 'baz' => true, 'fooBar' => 'foobar'), + ['foo' => 'foo', 'bar' => 'bar', 'baz' => true, 'fooBar' => 'foobar'], __NAMESPACE__.'\ObjectConstructorDummy', 'any'); $this->assertEquals('foo', $obj->getFoo()); $this->assertEquals('bar', $obj->bar); @@ -131,7 +131,7 @@ class ObjectNormalizerTest extends TestCase public function testConstructorDenormalizeWithNullArgument() { $obj = $this->normalizer->denormalize( - array('foo' => 'foo', 'bar' => null, 'baz' => true), + ['foo' => 'foo', 'bar' => null, 'baz' => true], __NAMESPACE__.'\ObjectConstructorDummy', 'any'); $this->assertEquals('foo', $obj->getFoo()); $this->assertNull($obj->bar); @@ -141,19 +141,19 @@ class ObjectNormalizerTest extends TestCase public function testConstructorDenormalizeWithMissingOptionalArgument() { $obj = $this->normalizer->denormalize( - array('foo' => 'test', 'baz' => array(1, 2, 3)), + ['foo' => 'test', 'baz' => [1, 2, 3]], __NAMESPACE__.'\ObjectConstructorOptionalArgsDummy', 'any'); $this->assertEquals('test', $obj->getFoo()); - $this->assertEquals(array(), $obj->bar); - $this->assertEquals(array(1, 2, 3), $obj->getBaz()); + $this->assertEquals([], $obj->bar); + $this->assertEquals([1, 2, 3], $obj->getBaz()); } public function testConstructorDenormalizeWithOptionalDefaultArgument() { $obj = $this->normalizer->denormalize( - array('bar' => 'test'), + ['bar' => 'test'], __NAMESPACE__.'\ObjectConstructorArgsWithDefaultValueDummy', 'any'); - $this->assertEquals(array(), $obj->getFoo()); + $this->assertEquals([], $obj->getFoo()); $this->assertEquals('test', $obj->getBar()); } @@ -171,16 +171,16 @@ class ObjectNormalizerTest extends TestCase public function testConstructorWithObjectTypeHintDenormalize() { - $data = array( + $data = [ 'id' => 10, - 'inner' => array( + 'inner' => [ 'foo' => 'oof', 'bar' => 'rab', - ), - ); + ], + ]; $normalizer = new ObjectNormalizer(); - $serializer = new Serializer(array($normalizer)); + $serializer = new Serializer([$normalizer]); $normalizer->setSerializer($serializer); $obj = $normalizer->denormalize($data, DummyWithConstructorObject::class); @@ -193,13 +193,13 @@ class ObjectNormalizerTest extends TestCase public function testConstructorWithUnconstructableNullableObjectTypeHintDenormalize() { - $data = array( + $data = [ 'id' => 10, 'inner' => null, - ); + ]; $normalizer = new ObjectNormalizer(); - $serializer = new Serializer(array($normalizer)); + $serializer = new Serializer([$normalizer]); $normalizer->setSerializer($serializer); $obj = $normalizer->denormalize($data, DummyWithNullableConstructorObject::class); @@ -214,16 +214,16 @@ class ObjectNormalizerTest extends TestCase */ public function testConstructorWithUnknownObjectTypeHintDenormalize() { - $data = array( + $data = [ 'id' => 10, - 'unknown' => array( + 'unknown' => [ 'foo' => 'oof', 'bar' => 'rab', - ), - ); + ], + ]; $normalizer = new ObjectNormalizer(); - $serializer = new Serializer(array($normalizer)); + $serializer = new Serializer([$normalizer]); $normalizer->setSerializer($serializer); $normalizer->denormalize($data, DummyWithConstructorInexistingObject::class); @@ -235,9 +235,9 @@ class ObjectNormalizerTest extends TestCase */ public function testConstructorWithMissingData() { - $data = array( + $data = [ 'foo' => 10, - ); + ]; $normalizer = new ObjectNormalizer(); @@ -246,17 +246,17 @@ class ObjectNormalizerTest extends TestCase public function testFillWithEmptyDataWhenMissingData() { - $data = array( + $data = [ 'foo' => 10, - ); + ]; $normalizer = new ObjectNormalizer(); - $result = $normalizer->denormalize($data, DummyValueObject::class, 'json', array( - 'default_constructor_arguments' => array( - DummyValueObject::class => array('foo' => '', 'bar' => '', 'baz' => null), - ), - )); + $result = $normalizer->denormalize($data, DummyValueObject::class, 'json', [ + 'default_constructor_arguments' => [ + DummyValueObject::class => ['foo' => '', 'bar' => '', 'baz' => null], + ], + ]); $this->assertEquals(new DummyValueObject(10, '', null), $result); } @@ -275,18 +275,18 @@ class ObjectNormalizerTest extends TestCase $obj->setKevin('kevin'); $obj->setCoopTilleuls('coopTilleuls'); - $this->assertEquals(array( + $this->assertEquals([ 'bar' => 'bar', - ), $this->normalizer->normalize($obj, null, array(ObjectNormalizer::GROUPS => array('c')))); + ], $this->normalizer->normalize($obj, null, [ObjectNormalizer::GROUPS => ['c']])); - $this->assertEquals(array( + $this->assertEquals([ 'symfony' => 'symfony', 'foo' => 'foo', 'fooBar' => 'fooBar', 'bar' => 'bar', 'kevin' => 'kevin', 'coopTilleuls' => 'coopTilleuls', - ), $this->normalizer->normalize($obj, null, array(ObjectNormalizer::GROUPS => array('a', 'c')))); + ], $this->normalizer->normalize($obj, null, [ObjectNormalizer::GROUPS => ['a', 'c']])); } public function testGroupsDenormalize() @@ -298,13 +298,13 @@ class ObjectNormalizerTest extends TestCase $obj = new GroupDummy(); $obj->setFoo('foo'); - $toNormalize = array('foo' => 'foo', 'bar' => 'bar'); + $toNormalize = ['foo' => 'foo', 'bar' => 'bar']; $normalized = $this->normalizer->denormalize( $toNormalize, 'Symfony\Component\Serializer\Tests\Fixtures\GroupDummy', null, - array(ObjectNormalizer::GROUPS => array('a')) + [ObjectNormalizer::GROUPS => ['a']] ); $this->assertEquals($obj, $normalized); @@ -314,7 +314,7 @@ class ObjectNormalizerTest extends TestCase $toNormalize, 'Symfony\Component\Serializer\Tests\Fixtures\GroupDummy', null, - array(ObjectNormalizer::GROUPS => array('a', 'b')) + [ObjectNormalizer::GROUPS => ['a', 'b']] ); $this->assertEquals($obj, $normalized); } @@ -328,7 +328,7 @@ class ObjectNormalizerTest extends TestCase $obj = new GroupDummy(); $obj->setFoo('foo'); - $this->assertEquals(array(), $this->normalizer->normalize($obj, null, array('groups' => array('notExist')))); + $this->assertEquals([], $this->normalizer->normalize($obj, null, ['groups' => ['notExist']])); } public function testGroupsNormalizeWithNameConverter() @@ -343,12 +343,12 @@ class ObjectNormalizerTest extends TestCase $obj->setCoopTilleuls('les-tilleuls.coop'); $this->assertEquals( - array( + [ 'bar' => null, 'foo_bar' => '@dunglas', 'symfony' => '@coopTilleuls', - ), - $this->normalizer->normalize($obj, null, array(ObjectNormalizer::GROUPS => array('name_converter'))) + ], + $this->normalizer->normalize($obj, null, [ObjectNormalizer::GROUPS => ['name_converter']]) ); } @@ -364,12 +364,12 @@ class ObjectNormalizerTest extends TestCase $this->assertEquals( $obj, - $this->normalizer->denormalize(array( + $this->normalizer->denormalize([ 'bar' => null, 'foo_bar' => '@dunglas', 'symfony' => '@coopTilleuls', 'coop_tilleuls' => 'les-tilleuls.coop', - ), 'Symfony\Component\Serializer\Tests\Fixtures\GroupDummy', null, array(ObjectNormalizer::GROUPS => array('name_converter'))) + ], 'Symfony\Component\Serializer\Tests\Fixtures\GroupDummy', null, [ObjectNormalizer::GROUPS => ['name_converter']]) ); } @@ -384,12 +384,12 @@ class ObjectNormalizerTest extends TestCase $this->assertEquals( $obj, - $this->normalizer->denormalize(array('bar' => 'xyz'), + $this->normalizer->denormalize(['bar' => 'xyz'], 'Symfony\Component\Serializer\Tests\Fixtures\NotSerializedConstructorArgumentDummy', null, - array(ObjectNormalizer::DEFAULT_CONSTRUCTOR_ARGUMENTS => array( - 'Symfony\Component\Serializer\Tests\Fixtures\NotSerializedConstructorArgumentDummy' => array('foo' => 'buz'), - )) + [ObjectNormalizer::DEFAULT_CONSTRUCTOR_ARGUMENTS => [ + 'Symfony\Component\Serializer\Tests\Fixtures\NotSerializedConstructorArgumentDummy' => ['foo' => 'buz'], + ]] ) ); } @@ -412,7 +412,7 @@ class ObjectNormalizerTest extends TestCase private function doTestCallbacks($callbacks, $value, $result, $message, bool $legacy = false) { - $legacy ? $this->normalizer->setCallbacks($callbacks) : $this->createNormalizer(array(ObjectNormalizer::CALLBACKS => $callbacks)); + $legacy ? $this->normalizer->setCallbacks($callbacks) : $this->createNormalizer([ObjectNormalizer::CALLBACKS => $callbacks]); $obj = new ObjectConstructorDummy('', $value, true); $this->assertEquals( @@ -440,8 +440,8 @@ class ObjectNormalizerTest extends TestCase private function doTestUncallableCallbacks(bool $legacy = false) { - $callbacks = array('bar' => null); - $legacy ? $this->normalizer->setCallbacks($callbacks) : $this->createNormalizer(array(ObjectNormalizer::CALLBACKS => $callbacks)); + $callbacks = ['bar' => null]; + $legacy ? $this->normalizer->setCallbacks($callbacks) : $this->createNormalizer([ObjectNormalizer::CALLBACKS => $callbacks]); $obj = new ObjectConstructorDummy('baz', 'quux', true); @@ -460,8 +460,8 @@ class ObjectNormalizerTest extends TestCase private function doTestIgnoredAttributes(bool $legacy = false) { - $ignoredAttributes = array('foo', 'bar', 'baz', 'camelCase', 'object'); - $legacy ? $this->normalizer->setIgnoredAttributes($ignoredAttributes) : $this->createNormalizer(array(ObjectNormalizer::IGNORED_ATTRIBUTES => $ignoredAttributes)); + $ignoredAttributes = ['foo', 'bar', 'baz', 'camelCase', 'object']; + $legacy ? $this->normalizer->setIgnoredAttributes($ignoredAttributes) : $this->createNormalizer([ObjectNormalizer::IGNORED_ATTRIBUTES => $ignoredAttributes]); $obj = new ObjectDummy(); $obj->setFoo('foo'); @@ -469,7 +469,7 @@ class ObjectNormalizerTest extends TestCase $obj->setBaz(true); $this->assertEquals( - array('fooBar' => 'foobar'), + ['fooBar' => 'foobar'], $this->normalizer->normalize($obj, 'any') ); } @@ -486,35 +486,35 @@ class ObjectNormalizerTest extends TestCase private function doTestIgnoredAttributesDenormalize(bool $legacy = false) { - $ignoredAttributes = array('fooBar', 'bar', 'baz'); - $legacy ? $this->normalizer->setIgnoredAttributes($ignoredAttributes) : $this->createNormalizer(array(ObjectNormalizer::IGNORED_ATTRIBUTES => $ignoredAttributes)); + $ignoredAttributes = ['fooBar', 'bar', 'baz']; + $legacy ? $this->normalizer->setIgnoredAttributes($ignoredAttributes) : $this->createNormalizer([ObjectNormalizer::IGNORED_ATTRIBUTES => $ignoredAttributes]); $obj = new ObjectDummy(); $obj->setFoo('foo'); $this->assertEquals( $obj, - $this->normalizer->denormalize(array('fooBar' => 'fooBar', 'foo' => 'foo', 'baz' => 'baz'), __NAMESPACE__.'\ObjectDummy') + $this->normalizer->denormalize(['fooBar' => 'fooBar', 'foo' => 'foo', 'baz' => 'baz'], __NAMESPACE__.'\ObjectDummy') ); } public function provideCallbacks() { - return array( - array( - array( + return [ + [ + [ 'bar' => function ($bar) { $this->assertEquals('baz', $bar); return 'baz'; }, - ), + ], 'baz', - array('foo' => '', 'bar' => 'baz', 'baz' => true), + ['foo' => '', 'bar' => 'baz', 'baz' => true], 'Change a string', - ), - array( - array( + ], + [ + [ 'bar' => function ($value, $object, $attributeName, $format, $context) { $this->assertSame('baz', $value); $this->assertInstanceOf(ObjectConstructorDummy::class, $object); @@ -522,23 +522,23 @@ class ObjectNormalizerTest extends TestCase $this->assertSame('any', $format); $this->assertArrayHasKey('circular_reference_limit_counters', $context); }, - ), + ], 'baz', - array('foo' => '', 'bar' => null, 'baz' => true), + ['foo' => '', 'bar' => null, 'baz' => true], 'Null an item', - ), - array( - array( + ], + [ + [ 'bar' => function ($bar) { return $bar->format('d-m-Y H:i:s'); }, - ), + ], new \DateTime('2011-09-10 06:30:00'), - array('foo' => '', 'bar' => '10-09-2011 06:30:00', 'baz' => true), + ['foo' => '', 'bar' => '10-09-2011 06:30:00', 'baz' => true], 'Format a date', - ), - array( - array( + ], + [ + [ 'bar' => function ($bars) { $foos = ''; foreach ($bars as $bar) { @@ -547,22 +547,22 @@ class ObjectNormalizerTest extends TestCase return $foos; }, - ), - array(new ObjectConstructorDummy('baz', '', false), new ObjectConstructorDummy('quux', '', false)), - array('foo' => '', 'bar' => 'bazquux', 'baz' => true), + ], + [new ObjectConstructorDummy('baz', '', false), new ObjectConstructorDummy('quux', '', false)], + ['foo' => '', 'bar' => 'bazquux', 'baz' => true], 'Collect a property', - ), - array( - array( + ], + [ + [ 'bar' => function ($bars) { return \count($bars); }, - ), - array(new ObjectConstructorDummy('baz', '', false), new ObjectConstructorDummy('quux', '', false)), - array('foo' => '', 'bar' => 2, 'baz' => true), + ], + [new ObjectConstructorDummy('baz', '', false), new ObjectConstructorDummy('quux', '', false)], + ['foo' => '', 'bar' => 2, 'baz' => true], 'Count a property', - ), - ); + ], + ]; } /** @@ -599,8 +599,8 @@ class ObjectNormalizerTest extends TestCase private function doTestUnableToNormalizeCircularReference(bool $legacy = false) { - $legacy ? $this->normalizer->setCircularReferenceLimit(2) : $this->createNormalizer(array(ObjectNormalizer::CIRCULAR_REFERENCE_LIMIT => 2)); - $serializer = new Serializer(array($this->normalizer)); + $legacy ? $this->normalizer->setCircularReferenceLimit(2) : $this->createNormalizer([ObjectNormalizer::CIRCULAR_REFERENCE_LIMIT => 2]); + $serializer = new Serializer([$this->normalizer]); $this->normalizer->setSerializer($serializer); $obj = new CircularReferenceDummy(); @@ -610,16 +610,16 @@ class ObjectNormalizerTest extends TestCase public function testSiblingReference() { - $serializer = new Serializer(array($this->normalizer)); + $serializer = new Serializer([$this->normalizer]); $this->normalizer->setSerializer($serializer); $siblingHolder = new SiblingHolder(); - $expected = array( - 'sibling0' => array('coopTilleuls' => 'Les-Tilleuls.coop'), - 'sibling1' => array('coopTilleuls' => 'Les-Tilleuls.coop'), - 'sibling2' => array('coopTilleuls' => 'Les-Tilleuls.coop'), - ); + $expected = [ + 'sibling0' => ['coopTilleuls' => 'Les-Tilleuls.coop'], + 'sibling1' => ['coopTilleuls' => 'Les-Tilleuls.coop'], + 'sibling2' => ['coopTilleuls' => 'Les-Tilleuls.coop'], + ]; $this->assertEquals($expected, $this->normalizer->normalize($siblingHolder)); } @@ -640,7 +640,7 @@ class ObjectNormalizerTest extends TestCase }, $legacy); $obj = new CircularReferenceDummy(); - $expected = array('me' => 'Symfony\Component\Serializer\Tests\Fixtures\CircularReferenceDummy'); + $expected = ['me' => 'Symfony\Component\Serializer\Tests\Fixtures\CircularReferenceDummy']; $this->assertEquals($expected, $this->normalizer->normalize($obj)); $this->createNormalizerWithCircularReferenceHandler(function ($obj, string $format, array $context) { @@ -650,13 +650,13 @@ class ObjectNormalizerTest extends TestCase return \get_class($obj); }, $legacy); - $this->assertEquals($expected, $this->normalizer->normalize($obj, 'test', array('foo' => 'bar'))); + $this->assertEquals($expected, $this->normalizer->normalize($obj, 'test', ['foo' => 'bar'])); } private function createNormalizerWithCircularReferenceHandler(callable $handler, bool $legacy) { - $legacy ? $this->normalizer->setCircularReferenceHandler($handler) : $this->createNormalizer(array(ObjectNormalizer::CIRCULAR_REFERENCE_HANDLER => $handler)); - $this->serializer = new Serializer(array($this->normalizer)); + $legacy ? $this->normalizer->setCircularReferenceHandler($handler) : $this->createNormalizer([ObjectNormalizer::CIRCULAR_REFERENCE_HANDLER => $handler]); + $this->serializer = new Serializer([$this->normalizer]); $this->normalizer->setSerializer($this->serializer); } @@ -664,7 +664,7 @@ class ObjectNormalizerTest extends TestCase { $this->assertEquals( new ObjectDummy(), - $this->normalizer->denormalize(array('non_existing' => true), __NAMESPACE__.'\ObjectDummy') + $this->normalizer->denormalize(['non_existing' => true], __NAMESPACE__.'\ObjectDummy') ); } @@ -675,28 +675,28 @@ class ObjectNormalizerTest extends TestCase public function testNormalizeStatic() { - $this->assertEquals(array('foo' => 'K'), $this->normalizer->normalize(new ObjectWithStaticPropertiesAndMethods())); + $this->assertEquals(['foo' => 'K'], $this->normalizer->normalize(new ObjectWithStaticPropertiesAndMethods())); } public function testNormalizeUpperCaseAttributes() { - $this->assertEquals(array('Foo' => 'Foo', 'Bar' => 'BarBar'), $this->normalizer->normalize(new ObjectWithUpperCaseAttributeNames())); + $this->assertEquals(['Foo' => 'Foo', 'Bar' => 'BarBar'], $this->normalizer->normalize(new ObjectWithUpperCaseAttributeNames())); } public function testNormalizeNotSerializableContext() { $objectDummy = new ObjectDummy(); - $expected = array( + $expected = [ 'foo' => null, 'baz' => null, 'fooBar' => '', 'camelCase' => null, 'object' => null, 'bar' => null, - ); + ]; - $this->assertEquals($expected, $this->normalizer->normalize($objectDummy, null, array('not_serializable' => function () { - }))); + $this->assertEquals($expected, $this->normalizer->normalize($objectDummy, null, ['not_serializable' => function () { + }])); } public function testMaxDepth() @@ -723,41 +723,41 @@ class ObjectNormalizerTest extends TestCase $level2->child = $level3; $this->createNormalizerWithMaxDepthHandler(null, $legacy); - $result = $this->serializer->normalize($level1, null, array(ObjectNormalizer::ENABLE_MAX_DEPTH => true)); + $result = $this->serializer->normalize($level1, null, [ObjectNormalizer::ENABLE_MAX_DEPTH => true]); - $expected = array( + $expected = [ 'bar' => null, 'foo' => 'level1', - 'child' => array( + 'child' => [ 'bar' => null, 'foo' => 'level2', - 'child' => array( + 'child' => [ 'bar' => null, 'child' => null, - ), - ), - ); + ], + ], + ]; $this->assertEquals($expected, $result); - $expected = array( + $expected = [ 'bar' => null, 'foo' => 'level1', - 'child' => array( + 'child' => [ 'bar' => null, 'foo' => 'level2', - 'child' => array( + 'child' => [ 'bar' => null, 'child' => null, 'foo' => 'handler', - ), - ), - ); + ], + ], + ]; $this->createNormalizerWithMaxDepthHandler(function () { return 'handler'; }, $legacy); - $result = $this->serializer->normalize($level1, null, array(ObjectNormalizer::ENABLE_MAX_DEPTH => true)); + $result = $this->serializer->normalize($level1, null, [ObjectNormalizer::ENABLE_MAX_DEPTH => true]); $this->assertEquals($expected, $result); $this->createNormalizerWithMaxDepthHandler(function ($object, $parentObject, $attributeName, $format, $context) { @@ -769,21 +769,21 @@ class ObjectNormalizerTest extends TestCase return 'handler'; }, $legacy); - $this->serializer->normalize($level1, 'test', array(ObjectNormalizer::ENABLE_MAX_DEPTH => true)); + $this->serializer->normalize($level1, 'test', [ObjectNormalizer::ENABLE_MAX_DEPTH => true]); } private function createNormalizerWithMaxDepthHandler(callable $handler = null, bool $legacy = false) { $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader())); if ($legacy) { - $this->createNormalizer(array(), $classMetadataFactory); + $this->createNormalizer([], $classMetadataFactory); if (null !== $handler) { $this->normalizer->setMaxDepthHandler($handler); } } else { - $this->createNormalizer(array(ObjectNormalizer::MAX_DEPTH_HANDLER => $handler), $classMetadataFactory); + $this->createNormalizer([ObjectNormalizer::MAX_DEPTH_HANDLER => $handler], $classMetadataFactory); } - $this->serializer = new Serializer(array($this->normalizer)); + $this->serializer = new Serializer([$this->normalizer]); $this->normalizer->setSerializer($this->serializer); } @@ -792,20 +792,20 @@ class ObjectNormalizerTest extends TestCase */ public function testThrowUnexpectedValueException() { - $this->normalizer->denormalize(array('foo' => 'bar'), ObjectTypeHinted::class); + $this->normalizer->denormalize(['foo' => 'bar'], ObjectTypeHinted::class); } public function testDenomalizeRecursive() { - $extractor = new PropertyInfoExtractor(array(), array(new PhpDocExtractor(), new ReflectionExtractor())); + $extractor = new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()]); $normalizer = new ObjectNormalizer(null, null, null, $extractor); - $serializer = new Serializer(array(new ArrayDenormalizer(), new DateTimeNormalizer(), $normalizer)); + $serializer = new Serializer([new ArrayDenormalizer(), new DateTimeNormalizer(), $normalizer]); - $obj = $serializer->denormalize(array( - 'inner' => array('foo' => 'foo', 'bar' => 'bar'), + $obj = $serializer->denormalize([ + 'inner' => ['foo' => 'foo', 'bar' => 'bar'], 'date' => '1988/01/21', - 'inners' => array(array('foo' => 1), array('foo' => 2)), - ), ObjectOuter::class); + 'inners' => [['foo' => 1], ['foo' => 2]], + ], ObjectOuter::class); $this->assertSame('foo', $obj->getInner()->foo); $this->assertSame('bar', $obj->getInner()->bar); @@ -816,12 +816,12 @@ class ObjectNormalizerTest extends TestCase public function testAcceptJsonNumber() { - $extractor = new PropertyInfoExtractor(array(), array(new PhpDocExtractor(), new ReflectionExtractor())); + $extractor = new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()]); $normalizer = new ObjectNormalizer(null, null, null, $extractor); - $serializer = new Serializer(array(new ArrayDenormalizer(), new DateTimeNormalizer(), $normalizer)); + $serializer = new Serializer([new ArrayDenormalizer(), new DateTimeNormalizer(), $normalizer]); - $this->assertSame(10.0, $serializer->denormalize(array('number' => 10), JsonNumber::class, 'json')->number); - $this->assertSame(10.0, $serializer->denormalize(array('number' => 10), JsonNumber::class, 'jsonld')->number); + $this->assertSame(10.0, $serializer->denormalize(['number' => 10], JsonNumber::class, 'json')->number); + $this->assertSame(10.0, $serializer->denormalize(['number' => 10], JsonNumber::class, 'jsonld')->number); } /** @@ -831,9 +831,9 @@ class ObjectNormalizerTest extends TestCase public function testRejectInvalidType() { $normalizer = new ObjectNormalizer(null, null, null, new ReflectionExtractor()); - $serializer = new Serializer(array($normalizer)); + $serializer = new Serializer([$normalizer]); - $serializer->denormalize(array('date' => 'foo'), ObjectOuter::class); + $serializer->denormalize(['date' => 'foo'], ObjectOuter::class); } /** @@ -842,21 +842,21 @@ class ObjectNormalizerTest extends TestCase */ public function testRejectInvalidKey() { - $extractor = new PropertyInfoExtractor(array(), array(new PhpDocExtractor(), new ReflectionExtractor())); + $extractor = new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()]); $normalizer = new ObjectNormalizer(null, null, null, $extractor); - $serializer = new Serializer(array(new ArrayDenormalizer(), new DateTimeNormalizer(), $normalizer)); + $serializer = new Serializer([new ArrayDenormalizer(), new DateTimeNormalizer(), $normalizer]); - $serializer->denormalize(array('inners' => array('a' => array('foo' => 1))), ObjectOuter::class); + $serializer->denormalize(['inners' => ['a' => ['foo' => 1]]], ObjectOuter::class); } public function testDoNotRejectInvalidTypeOnDisableTypeEnforcementContextOption() { - $extractor = new PropertyInfoExtractor(array(), array(new PhpDocExtractor())); + $extractor = new PropertyInfoExtractor([], [new PhpDocExtractor()]); $normalizer = new ObjectNormalizer(null, null, null, $extractor); - $serializer = new Serializer(array($normalizer)); - $context = array(ObjectNormalizer::DISABLE_TYPE_ENFORCEMENT => true); + $serializer = new Serializer([$normalizer]); + $context = [ObjectNormalizer::DISABLE_TYPE_ENFORCEMENT => true]; - $this->assertSame('foo', $serializer->denormalize(array('number' => 'foo'), JsonNumber::class, null, $context)->number); + $this->assertSame('foo', $serializer->denormalize(['number' => 'foo'], JsonNumber::class, null, $context)->number); } public function testExtractAttributesRespectsFormat() @@ -867,7 +867,7 @@ class ObjectNormalizerTest extends TestCase $data->setFoo('bar'); $data->bar = 'foo'; - $this->assertSame(array('foo' => 'bar', 'bar' => 'foo'), $normalizer->normalize($data, 'foo_and_bar_included')); + $this->assertSame(['foo' => 'bar', 'bar' => 'foo'], $normalizer->normalize($data, 'foo_and_bar_included')); } public function testExtractAttributesRespectsContext() @@ -878,13 +878,13 @@ class ObjectNormalizerTest extends TestCase $data->setFoo('bar'); $data->bar = 'foo'; - $this->assertSame(array('foo' => 'bar', 'bar' => 'foo'), $normalizer->normalize($data, null, array('include_foo_and_bar' => true))); + $this->assertSame(['foo' => 'bar', 'bar' => 'foo'], $normalizer->normalize($data, null, ['include_foo_and_bar' => true])); } public function testAttributesContextNormalize() { $normalizer = new ObjectNormalizer(); - $serializer = new Serializer(array($normalizer)); + $serializer = new Serializer([$normalizer]); $objectInner = new ObjectInner(); $objectInner->foo = 'innerFoo'; @@ -895,23 +895,23 @@ class ObjectNormalizerTest extends TestCase $objectDummy->setBaz(true); $objectDummy->setObject($objectInner); - $context = array('attributes' => array('foo', 'baz', 'object' => array('foo'))); + $context = ['attributes' => ['foo', 'baz', 'object' => ['foo']]]; $this->assertEquals( - array( + [ 'foo' => 'foo', 'baz' => true, - 'object' => array('foo' => 'innerFoo'), - ), + 'object' => ['foo' => 'innerFoo'], + ], $serializer->normalize($objectDummy, null, $context) ); - $context = array('attributes' => array('foo', 'baz', 'object')); + $context = ['attributes' => ['foo', 'baz', 'object']]; $this->assertEquals( - array( + [ 'foo' => 'foo', 'baz' => true, - 'object' => array('foo' => 'innerFoo', 'bar' => 'innerBar'), - ), + 'object' => ['foo' => 'innerFoo', 'bar' => 'innerBar'], + ], $serializer->normalize($objectDummy, null, $context) ); } @@ -919,7 +919,7 @@ class ObjectNormalizerTest extends TestCase public function testAttributesContextDenormalize() { $normalizer = new ObjectNormalizer(null, null, null, new ReflectionExtractor()); - $serializer = new Serializer(array($normalizer)); + $serializer = new Serializer([$normalizer]); $objectInner = new ObjectInner(); $objectInner->foo = 'innerFoo'; @@ -928,38 +928,38 @@ class ObjectNormalizerTest extends TestCase $objectOuter->bar = 'bar'; $objectOuter->setInner($objectInner); - $context = array('attributes' => array('bar', 'inner' => array('foo'))); + $context = ['attributes' => ['bar', 'inner' => ['foo']]]; $this->assertEquals($objectOuter, $serializer->denormalize( - array( + [ 'foo' => 'foo', 'bar' => 'bar', 'date' => '2017-02-03', - 'inner' => array('foo' => 'innerFoo', 'bar' => 'innerBar'), - ), ObjectOuter::class, null, $context)); + 'inner' => ['foo' => 'innerFoo', 'bar' => 'innerBar'], + ], ObjectOuter::class, null, $context)); } public function testAttributesContextDenormalizeConstructor() { $normalizer = new ObjectNormalizer(null, null, null, new ReflectionExtractor()); - $serializer = new Serializer(array($normalizer)); + $serializer = new Serializer([$normalizer]); $objectInner = new ObjectInner(); $objectInner->bar = 'bar'; $obj = new DummyWithConstructorObjectAndDefaultValue('a', $objectInner); - $context = array('attributes' => array('inner' => array('bar'))); - $this->assertEquals($obj, $serializer->denormalize(array( + $context = ['attributes' => ['inner' => ['bar']]]; + $this->assertEquals($obj, $serializer->denormalize([ 'foo' => 'b', - 'inner' => array('foo' => 'foo', 'bar' => 'bar'), - ), DummyWithConstructorObjectAndDefaultValue::class, null, $context)); + 'inner' => ['foo' => 'foo', 'bar' => 'bar'], + ], DummyWithConstructorObjectAndDefaultValue::class, null, $context)); } public function testNormalizeSameObjectWithDifferentAttributes() { $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader())); $this->normalizer = new ObjectNormalizer($classMetadataFactory); - $serializer = new Serializer(array($this->normalizer)); + $serializer = new Serializer([$this->normalizer]); $this->normalizer->setSerializer($serializer); $dummy = new ObjectOuter(); @@ -971,37 +971,37 @@ class ObjectNormalizerTest extends TestCase $dummy->bar->foo = 'bar.foo'; $dummy->bar->bar = 'bar.bar'; - $this->assertEquals(array( - 'foo' => array( + $this->assertEquals([ + 'foo' => [ 'bar' => 'foo.bar', - ), - 'bar' => array( + ], + 'bar' => [ 'foo' => 'bar.foo', - ), - ), $this->normalizer->normalize($dummy, 'json', array( - 'attributes' => array( - 'foo' => array('bar'), - 'bar' => array('foo'), - ), - ))); + ], + ], $this->normalizer->normalize($dummy, 'json', [ + 'attributes' => [ + 'foo' => ['bar'], + 'bar' => ['foo'], + ], + ])); } public function testAdvancedNameConverter() { $nameConverter = new class() implements AdvancedNameConverterInterface { - public function normalize($propertyName, string $class = null, string $format = null, array $context = array()) + public function normalize($propertyName, string $class = null, string $format = null, array $context = []) { return sprintf('%s-%s-%s-%s', $propertyName, $class, $format, $context['foo']); } - public function denormalize($propertyName, string $class = null, string $format = null, array $context = array()) + public function denormalize($propertyName, string $class = null, string $format = null, array $context = []) { return sprintf('%s-%s-%s-%s', $propertyName, $class, $format, $context['foo']); } }; $normalizer = new ObjectNormalizer(null, $nameConverter); - $this->assertArrayHasKey('foo-Symfony\Component\Serializer\Tests\Normalizer\ObjectDummy-json-bar', $normalizer->normalize(new ObjectDummy(), 'json', array('foo' => 'bar'))); + $this->assertArrayHasKey('foo-Symfony\Component\Serializer\Tests\Normalizer\ObjectDummy-json-bar', $normalizer->normalize(new ObjectDummy(), 'json', ['foo' => 'bar'])); } } @@ -1103,7 +1103,7 @@ class ObjectConstructorOptionalArgsDummy public $bar; private $baz; - public function __construct($foo, $bar = array(), $baz = array()) + public function __construct($foo, $bar = [], $baz = []) { $this->foo = $foo; $this->bar = $bar; @@ -1131,7 +1131,7 @@ class ObjectConstructorArgsWithDefaultValueDummy protected $foo; protected $bar; - public function __construct($foo = array(), $bar) + public function __construct($foo = [], $bar) { $this->foo = $foo; $this->bar = $bar; @@ -1222,13 +1222,13 @@ class ObjectInner class FormatAndContextAwareNormalizer extends ObjectNormalizer { - protected function isAllowedAttribute($classOrObject, $attribute, $format = null, array $context = array()) + protected function isAllowedAttribute($classOrObject, $attribute, $format = null, array $context = []) { - if (\in_array($attribute, array('foo', 'bar')) && 'foo_and_bar_included' === $format) { + if (\in_array($attribute, ['foo', 'bar']) && 'foo_and_bar_included' === $format) { return true; } - if (\in_array($attribute, array('foo', 'bar')) && isset($context['include_foo_and_bar']) && true === $context['include_foo_and_bar']) { + if (\in_array($attribute, ['foo', 'bar']) && isset($context['include_foo_and_bar']) && true === $context['include_foo_and_bar']) { return true; } diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/PropertyNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/PropertyNormalizerTest.php index 091421f072..26bccdfcad 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/PropertyNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/PropertyNormalizerTest.php @@ -41,7 +41,7 @@ class PropertyNormalizerTest extends TestCase $this->createNormalizer(); } - private function createNormalizer(array $defaultContext = array()) + private function createNormalizer(array $defaultContext = []) { $this->serializer = $this->getMockBuilder('Symfony\Component\Serializer\SerializerInterface')->getMock(); $this->normalizer = new PropertyNormalizer(null, null, null, null, null, $defaultContext); @@ -55,7 +55,7 @@ class PropertyNormalizerTest extends TestCase $obj->setBar('bar'); $obj->setCamelCase('camelcase'); $this->assertEquals( - array('foo' => 'foo', 'bar' => 'bar', 'camelCase' => 'camelcase'), + ['foo' => 'foo', 'bar' => 'bar', 'camelCase' => 'camelcase'], $this->normalizer->normalize($obj, 'any') ); } @@ -63,7 +63,7 @@ class PropertyNormalizerTest extends TestCase public function testDenormalize() { $obj = $this->normalizer->denormalize( - array('foo' => 'foo', 'bar' => 'bar'), + ['foo' => 'foo', 'bar' => 'bar'], __NAMESPACE__.'\PropertyDummy', 'any' ); @@ -80,7 +80,7 @@ class PropertyNormalizerTest extends TestCase $group->setKevin('Kevin'); $group->setCoopTilleuls('coop'); $this->assertEquals( - array('foo' => 'foo', 'bar' => 'bar', 'kevin' => 'Kevin', 'coopTilleuls' => 'coop', 'fooBar' => null, 'symfony' => null, 'baz' => 'baz'), + ['foo' => 'foo', 'bar' => 'bar', 'kevin' => 'Kevin', 'coopTilleuls' => 'coop', 'fooBar' => null, 'symfony' => null, 'baz' => 'baz'], $this->normalizer->normalize($group, 'any') ); } @@ -88,7 +88,7 @@ class PropertyNormalizerTest extends TestCase public function testDenormalizeWithParentClass() { $obj = $this->normalizer->denormalize( - array('foo' => 'foo', 'bar' => 'bar', 'kevin' => 'Kevin', 'baz' => 'baz'), + ['foo' => 'foo', 'bar' => 'bar', 'kevin' => 'Kevin', 'baz' => 'baz'], GroupDummyChild::class, 'any' ); @@ -102,7 +102,7 @@ class PropertyNormalizerTest extends TestCase public function testConstructorDenormalize() { $obj = $this->normalizer->denormalize( - array('foo' => 'foo', 'bar' => 'bar'), + ['foo' => 'foo', 'bar' => 'bar'], __NAMESPACE__.'\PropertyConstructorDummy', 'any' ); @@ -113,7 +113,7 @@ class PropertyNormalizerTest extends TestCase public function testConstructorDenormalizeWithNullArgument() { $obj = $this->normalizer->denormalize( - array('foo' => null, 'bar' => 'bar'), + ['foo' => null, 'bar' => 'bar'], __NAMESPACE__.'\PropertyConstructorDummy', ' any' ); @@ -139,7 +139,7 @@ class PropertyNormalizerTest extends TestCase private function doTestCallbacks($callbacks, $value, $result, $message, bool $legacy = false) { - $legacy ? $this->normalizer->setCallbacks($callbacks) : $this->createNormalizer(array(PropertyNormalizer::CALLBACKS => $callbacks)); + $legacy ? $this->normalizer->setCallbacks($callbacks) : $this->createNormalizer([PropertyNormalizer::CALLBACKS => $callbacks]); $obj = new PropertyConstructorDummy('', $value); @@ -171,8 +171,8 @@ class PropertyNormalizerTest extends TestCase */ private function doTestUncallableCallbacks(bool $legacy = false) { - $callbacks = array('bar' => null); - $legacy ? $this->normalizer->setCallbacks($callbacks) : $this->createNormalizer(array(PropertyNormalizer::CALLBACKS => $callbacks)); + $callbacks = ['bar' => null]; + $legacy ? $this->normalizer->setCallbacks($callbacks) : $this->createNormalizer([PropertyNormalizer::CALLBACKS => $callbacks]); $obj = new PropertyConstructorDummy('baz', 'quux'); @@ -191,15 +191,15 @@ class PropertyNormalizerTest extends TestCase private function doTestIgnoredAttributes(bool $legacy = false) { - $ignoredAttributes = array('foo', 'bar', 'camelCase'); - $legacy ? $this->normalizer->setIgnoredAttributes($ignoredAttributes) : $this->createNormalizer(array(PropertyNormalizer::IGNORED_ATTRIBUTES => $ignoredAttributes)); + $ignoredAttributes = ['foo', 'bar', 'camelCase']; + $legacy ? $this->normalizer->setIgnoredAttributes($ignoredAttributes) : $this->createNormalizer([PropertyNormalizer::IGNORED_ATTRIBUTES => $ignoredAttributes]); $obj = new PropertyDummy(); $obj->foo = 'foo'; $obj->setBar('bar'); $this->assertEquals( - array(), + [], $this->normalizer->normalize($obj, 'any') ); } @@ -218,19 +218,19 @@ class PropertyNormalizerTest extends TestCase $obj->setKevin('kevin'); $obj->setCoopTilleuls('coopTilleuls'); - $this->assertEquals(array( + $this->assertEquals([ 'bar' => 'bar', - ), $this->normalizer->normalize($obj, null, array(PropertyNormalizer::GROUPS => array('c')))); + ], $this->normalizer->normalize($obj, null, [PropertyNormalizer::GROUPS => ['c']])); // The PropertyNormalizer is also able to hydrate properties from parent classes - $this->assertEquals(array( + $this->assertEquals([ 'symfony' => 'symfony', 'foo' => 'foo', 'fooBar' => 'fooBar', 'bar' => 'bar', 'kevin' => 'kevin', 'coopTilleuls' => 'coopTilleuls', - ), $this->normalizer->normalize($obj, null, array(PropertyNormalizer::GROUPS => array('a', 'c')))); + ], $this->normalizer->normalize($obj, null, [PropertyNormalizer::GROUPS => ['a', 'c']])); } public function testGroupsDenormalize() @@ -242,13 +242,13 @@ class PropertyNormalizerTest extends TestCase $obj = new GroupDummy(); $obj->setFoo('foo'); - $toNormalize = array('foo' => 'foo', 'bar' => 'bar'); + $toNormalize = ['foo' => 'foo', 'bar' => 'bar']; $normalized = $this->normalizer->denormalize( $toNormalize, 'Symfony\Component\Serializer\Tests\Fixtures\GroupDummy', null, - array(PropertyNormalizer::GROUPS => array('a')) + [PropertyNormalizer::GROUPS => ['a']] ); $this->assertEquals($obj, $normalized); @@ -258,7 +258,7 @@ class PropertyNormalizerTest extends TestCase $toNormalize, 'Symfony\Component\Serializer\Tests\Fixtures\GroupDummy', null, - array(PropertyNormalizer::GROUPS => array('a', 'b')) + [PropertyNormalizer::GROUPS => ['a', 'b']] ); $this->assertEquals($obj, $normalized); } @@ -275,12 +275,12 @@ class PropertyNormalizerTest extends TestCase $obj->setCoopTilleuls('les-tilleuls.coop'); $this->assertEquals( - array( + [ 'bar' => null, 'foo_bar' => '@dunglas', 'symfony' => '@coopTilleuls', - ), - $this->normalizer->normalize($obj, null, array(PropertyNormalizer::GROUPS => array('name_converter'))) + ], + $this->normalizer->normalize($obj, null, [PropertyNormalizer::GROUPS => ['name_converter']]) ); } @@ -296,49 +296,49 @@ class PropertyNormalizerTest extends TestCase $this->assertEquals( $obj, - $this->normalizer->denormalize(array( + $this->normalizer->denormalize([ 'bar' => null, 'foo_bar' => '@dunglas', 'symfony' => '@coopTilleuls', 'coop_tilleuls' => 'les-tilleuls.coop', - ), 'Symfony\Component\Serializer\Tests\Fixtures\GroupDummy', null, array(PropertyNormalizer::GROUPS => array('name_converter'))) + ], 'Symfony\Component\Serializer\Tests\Fixtures\GroupDummy', null, [PropertyNormalizer::GROUPS => ['name_converter']]) ); } public function provideCallbacks() { - return array( - array( - array( + return [ + [ + [ 'bar' => function ($bar) { return 'baz'; }, - ), + ], 'baz', - array('foo' => '', 'bar' => 'baz'), + ['foo' => '', 'bar' => 'baz'], 'Change a string', - ), - array( - array( + ], + [ + [ 'bar' => function ($bar) { }, - ), + ], 'baz', - array('foo' => '', 'bar' => null), + ['foo' => '', 'bar' => null], 'Null an item', - ), - array( - array( + ], + [ + [ 'bar' => function ($bar) { return $bar->format('d-m-Y H:i:s'); }, - ), + ], new \DateTime('2011-09-10 06:30:00'), - array('foo' => '', 'bar' => '10-09-2011 06:30:00'), + ['foo' => '', 'bar' => '10-09-2011 06:30:00'], 'Format a date', - ), - array( - array( + ], + [ + [ 'bar' => function ($bars) { $foos = ''; foreach ($bars as $bar) { @@ -347,22 +347,22 @@ class PropertyNormalizerTest extends TestCase return $foos; }, - ), - array(new PropertyConstructorDummy('baz', ''), new PropertyConstructorDummy('quux', '')), - array('foo' => '', 'bar' => 'bazquux'), + ], + [new PropertyConstructorDummy('baz', ''), new PropertyConstructorDummy('quux', '')], + ['foo' => '', 'bar' => 'bazquux'], 'Collect a property', - ), - array( - array( + ], + [ + [ 'bar' => function ($bars) { return \count($bars); }, - ), - array(new PropertyConstructorDummy('baz', ''), new PropertyConstructorDummy('quux', '')), - array('foo' => '', 'bar' => 2), + ], + [new PropertyConstructorDummy('baz', ''), new PropertyConstructorDummy('quux', '')], + ['foo' => '', 'bar' => 2], 'Count a property', - ), - ); + ], + ]; } /** @@ -383,8 +383,8 @@ class PropertyNormalizerTest extends TestCase private function doTestUnableToNormalizeCircularReference(bool $legacy = false) { - $legacy ? $this->normalizer->setCircularReferenceLimit(2) : $this->createNormalizer(array(PropertyNormalizer::CIRCULAR_REFERENCE_LIMIT => 2)); - $this->serializer = new Serializer(array($this->normalizer)); + $legacy ? $this->normalizer->setCircularReferenceLimit(2) : $this->createNormalizer([PropertyNormalizer::CIRCULAR_REFERENCE_LIMIT => 2]); + $this->serializer = new Serializer([$this->normalizer]); $this->normalizer->setSerializer($this->serializer); $obj = new PropertyCircularReferenceDummy(); @@ -394,16 +394,16 @@ class PropertyNormalizerTest extends TestCase public function testSiblingReference() { - $serializer = new Serializer(array($this->normalizer)); + $serializer = new Serializer([$this->normalizer]); $this->normalizer->setSerializer($serializer); $siblingHolder = new PropertySiblingHolder(); - $expected = array( - 'sibling0' => array('coopTilleuls' => 'Les-Tilleuls.coop'), - 'sibling1' => array('coopTilleuls' => 'Les-Tilleuls.coop'), - 'sibling2' => array('coopTilleuls' => 'Les-Tilleuls.coop'), - ); + $expected = [ + 'sibling0' => ['coopTilleuls' => 'Les-Tilleuls.coop'], + 'sibling1' => ['coopTilleuls' => 'Les-Tilleuls.coop'], + 'sibling2' => ['coopTilleuls' => 'Les-Tilleuls.coop'], + ]; $this->assertEquals($expected, $this->normalizer->normalize($siblingHolder)); } @@ -422,14 +422,14 @@ class PropertyNormalizerTest extends TestCase $handler = function ($obj) { return \get_class($obj); }; - $legacy ? $this->normalizer->setCircularReferenceHandler($handler) : $this->createNormalizer(array(PropertyNormalizer::CIRCULAR_REFERENCE_HANDLER => $handler)); + $legacy ? $this->normalizer->setCircularReferenceHandler($handler) : $this->createNormalizer([PropertyNormalizer::CIRCULAR_REFERENCE_HANDLER => $handler]); - $this->serializer = new Serializer(array($this->normalizer)); + $this->serializer = new Serializer([$this->normalizer]); $this->normalizer->setSerializer($this->serializer); $obj = new PropertyCircularReferenceDummy(); - $expected = array('me' => 'Symfony\Component\Serializer\Tests\Fixtures\PropertyCircularReferenceDummy'); + $expected = ['me' => 'Symfony\Component\Serializer\Tests\Fixtures\PropertyCircularReferenceDummy']; $this->assertEquals($expected, $this->normalizer->normalize($obj)); } @@ -437,13 +437,13 @@ class PropertyNormalizerTest extends TestCase { $this->assertEquals( new PropertyDummy(), - $this->normalizer->denormalize(array('non_existing' => true), __NAMESPACE__.'\PropertyDummy') + $this->normalizer->denormalize(['non_existing' => true], __NAMESPACE__.'\PropertyDummy') ); } public function testDenormalizeShouldIgnoreStaticProperty() { - $obj = $this->normalizer->denormalize(array('outOfScope' => true), __NAMESPACE__.'\PropertyDummy'); + $obj = $this->normalizer->denormalize(['outOfScope' => true], __NAMESPACE__.'\PropertyDummy'); $this->assertEquals(new PropertyDummy(), $obj); $this->assertEquals('out_of_scope', PropertyDummy::$outOfScope); @@ -479,7 +479,7 @@ class PropertyNormalizerTest extends TestCase { $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader())); $this->normalizer = new PropertyNormalizer($classMetadataFactory); - $serializer = new Serializer(array($this->normalizer)); + $serializer = new Serializer([$this->normalizer]); $this->normalizer->setSerializer($serializer); $level1 = new MaxDepthDummy(); @@ -493,20 +493,20 @@ class PropertyNormalizerTest extends TestCase $level3->foo = 'level3'; $level2->child = $level3; - $result = $serializer->normalize($level1, null, array(PropertyNormalizer::ENABLE_MAX_DEPTH => true)); + $result = $serializer->normalize($level1, null, [PropertyNormalizer::ENABLE_MAX_DEPTH => true]); - $expected = array( + $expected = [ 'foo' => 'level1', - 'child' => array( + 'child' => [ 'foo' => 'level2', - 'child' => array( + 'child' => [ 'child' => null, 'bar' => null, - ), + ], 'bar' => null, - ), + ], 'bar' => null, - ); + ]; $this->assertEquals($expected, $result); } diff --git a/src/Symfony/Component/Serializer/Tests/SerializerTest.php b/src/Symfony/Component/Serializer/Tests/SerializerTest.php index 222a2d7091..ce6be57f33 100644 --- a/src/Symfony/Component/Serializer/Tests/SerializerTest.php +++ b/src/Symfony/Component/Serializer/Tests/SerializerTest.php @@ -61,7 +61,7 @@ class SerializerTest extends TestCase */ public function testDeprecationErrorOnInvalidNormalizer() { - new Serializer(array(new \stdClass())); + new Serializer([new \stdClass()]); } /** @@ -70,7 +70,7 @@ class SerializerTest extends TestCase */ public function testDeprecationErrorOnInvalidEncoder() { - new Serializer(array(), array(new \stdClass())); + new Serializer([], [new \stdClass()]); } /** @@ -352,7 +352,7 @@ class SerializerTest extends TestCase public function testNormalizerAware() { - $normalizerAware = $this->getMockBuilder(array(NormalizerAwareInterface::class, NormalizerInterface::class))->getMock(); + $normalizerAware = $this->getMockBuilder([NormalizerAwareInterface::class, NormalizerInterface::class])->getMock(); $normalizerAware->expects($this->once()) ->method('setNormalizer') ->with($this->isInstanceOf(NormalizerInterface::class)); @@ -362,7 +362,7 @@ class SerializerTest extends TestCase public function testDenormalizerAware() { - $denormalizerAware = $this->getMockBuilder(array(DenormalizerAwareInterface::class, DenormalizerInterface::class))->getMock(); + $denormalizerAware = $this->getMockBuilder([DenormalizerAwareInterface::class, DenormalizerInterface::class])->getMock(); $denormalizerAware->expects($this->once()) ->method('setDenormalizer') ->with($this->isInstanceOf(DenormalizerInterface::class)); diff --git a/src/Symfony/Component/Translation/Catalogue/MergeOperation.php b/src/Symfony/Component/Translation/Catalogue/MergeOperation.php index 8dd4026176..d2f4abd13f 100644 --- a/src/Symfony/Component/Translation/Catalogue/MergeOperation.php +++ b/src/Symfony/Component/Translation/Catalogue/MergeOperation.php @@ -29,16 +29,16 @@ class MergeOperation extends AbstractOperation */ protected function processDomain($domain) { - $this->messages[$domain] = array( - 'all' => array(), - 'new' => array(), - 'obsolete' => array(), - ); + $this->messages[$domain] = [ + 'all' => [], + 'new' => [], + 'obsolete' => [], + ]; $intlDomain = $domain.MessageCatalogueInterface::INTL_DOMAIN_SUFFIX; foreach ($this->source->all($domain) as $id => $message) { $this->messages[$domain]['all'][$id] = $message; - $this->result->add(array($id => $message), $this->source->defines($id, $intlDomain) ? $intlDomain : $domain); + $this->result->add([$id => $message], $this->source->defines($id, $intlDomain) ? $intlDomain : $domain); if (null !== $keyMetadata = $this->source->getMetadata($id, $domain)) { $this->result->setMetadata($id, $keyMetadata, $domain); } @@ -48,7 +48,7 @@ class MergeOperation extends AbstractOperation if (!$this->source->has($id, $domain)) { $this->messages[$domain]['all'][$id] = $message; $this->messages[$domain]['new'][$id] = $message; - $this->result->add(array($id => $message), $this->target->defines($id, $intlDomain) ? $intlDomain : $domain); + $this->result->add([$id => $message], $this->target->defines($id, $intlDomain) ? $intlDomain : $domain); if (null !== $keyMetadata = $this->target->getMetadata($id, $domain)) { $this->result->setMetadata($id, $keyMetadata, $domain); } diff --git a/src/Symfony/Component/Translation/Catalogue/TargetOperation.php b/src/Symfony/Component/Translation/Catalogue/TargetOperation.php index 523022550a..22aa9a3911 100644 --- a/src/Symfony/Component/Translation/Catalogue/TargetOperation.php +++ b/src/Symfony/Component/Translation/Catalogue/TargetOperation.php @@ -30,11 +30,11 @@ class TargetOperation extends AbstractOperation */ protected function processDomain($domain) { - $this->messages[$domain] = array( - 'all' => array(), - 'new' => array(), - 'obsolete' => array(), - ); + $this->messages[$domain] = [ + 'all' => [], + 'new' => [], + 'obsolete' => [], + ]; $intlDomain = $domain.MessageCatalogueInterface::INTL_DOMAIN_SUFFIX; // For 'all' messages, the code can't be simplified as ``$this->messages[$domain]['all'] = $target->all($domain);``, @@ -49,7 +49,7 @@ class TargetOperation extends AbstractOperation foreach ($this->source->all($domain) as $id => $message) { if ($this->target->has($id, $domain)) { $this->messages[$domain]['all'][$id] = $message; - $this->result->add(array($id => $message), $this->target->defines($id, $intlDomain) ? $intlDomain : $domain); + $this->result->add([$id => $message], $this->target->defines($id, $intlDomain) ? $intlDomain : $domain); if (null !== $keyMetadata = $this->source->getMetadata($id, $domain)) { $this->result->setMetadata($id, $keyMetadata, $domain); } @@ -62,7 +62,7 @@ class TargetOperation extends AbstractOperation if (!$this->source->has($id, $domain)) { $this->messages[$domain]['all'][$id] = $message; $this->messages[$domain]['new'][$id] = $message; - $this->result->add(array($id => $message), $this->target->defines($id, $intlDomain) ? $intlDomain : $domain); + $this->result->add([$id => $message], $this->target->defines($id, $intlDomain) ? $intlDomain : $domain); if (null !== $keyMetadata = $this->target->getMetadata($id, $domain)) { $this->result->setMetadata($id, $keyMetadata, $domain); } diff --git a/src/Symfony/Component/Translation/Command/XliffLintCommand.php b/src/Symfony/Component/Translation/Command/XliffLintCommand.php index 17e1a72bb4..f8791a490e 100644 --- a/src/Symfony/Component/Translation/Command/XliffLintCommand.php +++ b/src/Symfony/Component/Translation/Command/XliffLintCommand.php @@ -89,10 +89,10 @@ EOF throw new RuntimeException('Please provide a filename or pipe file content to STDIN.'); } - return $this->display($io, array($this->validate($stdin))); + return $this->display($io, [$this->validate($stdin)]); } - $filesInfo = array(); + $filesInfo = []; foreach ($filenames as $filename) { if (!$this->isReadable($filename)) { throw new RuntimeException(sprintf('File or directory "%s" is not readable.', $filename)); @@ -108,11 +108,11 @@ EOF private function validate($content, $file = null) { - $errors = array(); + $errors = []; // Avoid: Warning DOMDocument::loadXML(): Empty string supplied as input if ('' === trim($content)) { - return array('file' => $file, 'valid' => true); + return ['file' => $file, 'valid' => true]; } libxml_use_internal_errors(true); @@ -127,23 +127,23 @@ EOF $expectedFilenamePattern = $this->requireStrictFileNames ? sprintf('/^.*\.%s\.xlf/', $normalizedLocale) : sprintf('/^(.*\.%s\.xlf|%s\..*\.xlf)/', $normalizedLocale, $normalizedLocale); if (0 === preg_match($expectedFilenamePattern, basename($file))) { - $errors[] = array( + $errors[] = [ 'line' => -1, 'column' => -1, 'message' => sprintf('There is a mismatch between the language included in the file name ("%s") and the "%s" value used in the "target-language" attribute of the file.', basename($file), $targetLanguage), - ); + ]; } } foreach (XliffUtils::validateSchema($document) as $xmlError) { - $errors[] = array( + $errors[] = [ 'line' => $xmlError['line'], 'column' => $xmlError['column'], 'message' => $xmlError['message'], - ); + ]; } - return array('file' => $file, 'valid' => 0 === \count($errors), 'messages' => $errors); + return ['file' => $file, 'valid' => 0 === \count($errors), 'messages' => $errors]; } private function display(SymfonyStyle $io, array $files) @@ -210,7 +210,7 @@ EOF } foreach ($this->getDirectoryIterator($fileOrDirectory) as $file) { - if (!\in_array($file->getExtension(), array('xlf', 'xliff'))) { + if (!\in_array($file->getExtension(), ['xlf', 'xliff'])) { continue; } @@ -263,7 +263,7 @@ EOF private function getTargetLanguageFromFile(\DOMDocument $xliffContents): ?string { - foreach ($xliffContents->getElementsByTagName('file')[0]->attributes ?? array() as $attribute) { + foreach ($xliffContents->getElementsByTagName('file')[0]->attributes ?? [] as $attribute) { if ('target-language' === $attribute->nodeName) { return $attribute->nodeValue; } diff --git a/src/Symfony/Component/Translation/DataCollectorTranslator.php b/src/Symfony/Component/Translation/DataCollectorTranslator.php index ca6bedc71b..39561ec92e 100644 --- a/src/Symfony/Component/Translation/DataCollectorTranslator.php +++ b/src/Symfony/Component/Translation/DataCollectorTranslator.php @@ -30,7 +30,7 @@ class DataCollectorTranslator implements LegacyTranslatorInterface, TranslatorIn */ private $translator; - private $messages = array(); + private $messages = []; /** * @param TranslatorInterface $translator The translator must implement TranslatorBagInterface @@ -50,7 +50,7 @@ class DataCollectorTranslator implements LegacyTranslatorInterface, TranslatorIn /** * {@inheritdoc} */ - public function trans($id, array $parameters = array(), $domain = null, $locale = null) + public function trans($id, array $parameters = [], $domain = null, $locale = null) { $trans = $this->translator->trans($id, $parameters, $domain, $locale); $this->collectMessage($locale, $domain, $id, $trans, $parameters); @@ -63,15 +63,15 @@ class DataCollectorTranslator implements LegacyTranslatorInterface, TranslatorIn * * @deprecated since Symfony 4.2, use the trans() method instead with a %count% parameter */ - public function transChoice($id, $number, array $parameters = array(), $domain = null, $locale = null) + public function transChoice($id, $number, array $parameters = [], $domain = null, $locale = null) { if ($this->translator instanceof TranslatorInterface) { - $trans = $this->translator->trans($id, array('%count%' => $number) + $parameters, $domain, $locale); + $trans = $this->translator->trans($id, ['%count%' => $number] + $parameters, $domain, $locale); } $trans = $this->translator->transChoice($id, $number, $parameters, $domain, $locale); - $this->collectMessage($locale, $domain, $id, $trans, array('%count%' => $number) + $parameters); + $this->collectMessage($locale, $domain, $id, $trans, ['%count%' => $number] + $parameters); return $trans; } @@ -111,7 +111,7 @@ class DataCollectorTranslator implements LegacyTranslatorInterface, TranslatorIn return $this->translator->getFallbackLocales(); } - return array(); + return []; } /** @@ -137,7 +137,7 @@ class DataCollectorTranslator implements LegacyTranslatorInterface, TranslatorIn * @param string $translation * @param array|null $parameters */ - private function collectMessage($locale, $domain, $id, $translation, $parameters = array()) + private function collectMessage($locale, $domain, $id, $translation, $parameters = []) { if (null === $domain) { $domain = 'messages'; @@ -164,7 +164,7 @@ class DataCollectorTranslator implements LegacyTranslatorInterface, TranslatorIn $state = self::MESSAGE_MISSING; } - $this->messages[] = array( + $this->messages[] = [ 'locale' => $locale, 'domain' => $domain, 'id' => $id, @@ -172,6 +172,6 @@ class DataCollectorTranslator implements LegacyTranslatorInterface, TranslatorIn 'parameters' => $parameters, 'state' => $state, 'transChoiceNumber' => isset($parameters['%count%']) && is_numeric($parameters['%count%']) ? $parameters['%count%'] : null, - ); + ]; } } diff --git a/src/Symfony/Component/Translation/Dumper/FileDumper.php b/src/Symfony/Component/Translation/Dumper/FileDumper.php index 7fe6576a21..57ce9d2141 100644 --- a/src/Symfony/Component/Translation/Dumper/FileDumper.php +++ b/src/Symfony/Component/Translation/Dumper/FileDumper.php @@ -84,7 +84,7 @@ abstract class FileDumper implements DumperInterface $intlPath = $options['path'].'/'.$this->getRelativePath($intlDomain, $messages->getLocale()); file_put_contents($intlPath, $this->formatCatalogue($messages, $intlDomain, $options)); - $messages->replace(array(), $intlDomain); + $messages->replace([], $intlDomain); try { if ($messages->all($domain)) { diff --git a/src/Symfony/Component/Translation/Formatter/IntlFormatter.php b/src/Symfony/Component/Translation/Formatter/IntlFormatter.php index 338d5151f5..1d5f468d46 100644 --- a/src/Symfony/Component/Translation/Formatter/IntlFormatter.php +++ b/src/Symfony/Component/Translation/Formatter/IntlFormatter.php @@ -21,12 +21,12 @@ use Symfony\Component\Translation\Exception\LogicException; class IntlFormatter implements IntlFormatterInterface { private $hasMessageFormatter; - private $cache = array(); + private $cache = []; /** * {@inheritdoc} */ - public function formatIntl(string $message, string $locale, array $parameters = array()): string + public function formatIntl(string $message, string $locale, array $parameters = []): string { if (!$formatter = $this->cache[$locale][$message] ?? null) { if (!($this->hasMessageFormatter ?? $this->hasMessageFormatter = class_exists(\MessageFormatter::class))) { @@ -40,7 +40,7 @@ class IntlFormatter implements IntlFormatterInterface } foreach ($parameters as $key => $value) { - if (\in_array($key[0] ?? null, array('%', '{'), true)) { + if (\in_array($key[0] ?? null, ['%', '{'], true)) { unset($parameters[$key]); $parameters[trim($key, '%{ }')] = $value; } diff --git a/src/Symfony/Component/Translation/Formatter/IntlFormatterInterface.php b/src/Symfony/Component/Translation/Formatter/IntlFormatterInterface.php index 5fc5d97d24..02fc6acbdf 100644 --- a/src/Symfony/Component/Translation/Formatter/IntlFormatterInterface.php +++ b/src/Symfony/Component/Translation/Formatter/IntlFormatterInterface.php @@ -23,5 +23,5 @@ interface IntlFormatterInterface * * @see http://icu-project.org/apiref/icu4c/classMessageFormat.html#details */ - public function formatIntl(string $message, string $locale, array $parameters = array()): string; + public function formatIntl(string $message, string $locale, array $parameters = []): string; } diff --git a/src/Symfony/Component/Translation/Formatter/MessageFormatter.php b/src/Symfony/Component/Translation/Formatter/MessageFormatter.php index e36f242c89..030d7a5c3e 100644 --- a/src/Symfony/Component/Translation/Formatter/MessageFormatter.php +++ b/src/Symfony/Component/Translation/Formatter/MessageFormatter.php @@ -42,7 +42,7 @@ class MessageFormatter implements MessageFormatterInterface, IntlFormatterInterf /** * {@inheritdoc} */ - public function format($message, $locale, array $parameters = array()) + public function format($message, $locale, array $parameters = []) { if ($this->translator instanceof TranslatorInterface) { return $this->translator->trans($message, $parameters, null, $locale); @@ -54,7 +54,7 @@ class MessageFormatter implements MessageFormatterInterface, IntlFormatterInterf /** * {@inheritdoc} */ - public function formatIntl(string $message, string $locale, array $parameters = array()): string + public function formatIntl(string $message, string $locale, array $parameters = []): string { return $this->intlFormatter->formatIntl($message, $locale, $parameters); } @@ -64,16 +64,16 @@ class MessageFormatter implements MessageFormatterInterface, IntlFormatterInterf * * @deprecated since Symfony 4.2, use format() with a %count% parameter instead */ - public function choiceFormat($message, $number, $locale, array $parameters = array()) + public function choiceFormat($message, $number, $locale, array $parameters = []) { @trigger_error(sprintf('The "%s()" method is deprecated since Symfony 4.2, use the format() one instead with a %%count%% parameter.', __METHOD__), E_USER_DEPRECATED); - $parameters = array('%count%' => $number) + $parameters; + $parameters = ['%count%' => $number] + $parameters; if ($this->translator instanceof TranslatorInterface) { return $this->format($message, $locale, $parameters); } - return $this->format($this->translator->transChoice($message, $number, array(), null, $locale), $locale, $parameters); + return $this->format($this->translator->transChoice($message, $number, [], null, $locale), $locale, $parameters); } } diff --git a/src/Symfony/Component/Translation/IdentityTranslator.php b/src/Symfony/Component/Translation/IdentityTranslator.php index 31abdaab12..41807af04a 100644 --- a/src/Symfony/Component/Translation/IdentityTranslator.php +++ b/src/Symfony/Component/Translation/IdentityTranslator.php @@ -43,7 +43,7 @@ class IdentityTranslator implements LegacyTranslatorInterface, TranslatorInterfa * * @deprecated since Symfony 4.2, use the trans() method instead with a %count% parameter */ - public function transChoice($id, $number, array $parameters = array(), $domain = null, $locale = null) + public function transChoice($id, $number, array $parameters = [], $domain = null, $locale = null) { @trigger_error(sprintf('The "%s()" method is deprecated since Symfony 4.2, use the trans() one instead with a "%count%" parameter.', __METHOD__), E_USER_DEPRECATED); @@ -51,7 +51,7 @@ class IdentityTranslator implements LegacyTranslatorInterface, TranslatorInterfa return strtr($this->selector->choose((string) $id, $number, $locale ?: $this->getLocale()), $parameters); } - return $this->trans($id, array('%count%' => $number) + $parameters, $domain, $locale); + return $this->trans($id, ['%count%' => $number] + $parameters, $domain, $locale); } private function getPluralizationRule(int $number, string $locale): int diff --git a/src/Symfony/Component/Translation/Loader/XliffFileLoader.php b/src/Symfony/Component/Translation/Loader/XliffFileLoader.php index 1106ec65f0..99306b86b1 100644 --- a/src/Symfony/Component/Translation/Loader/XliffFileLoader.php +++ b/src/Symfony/Component/Translation/Loader/XliffFileLoader.php @@ -97,13 +97,13 @@ class XliffFileLoader implements LoaderInterface $catalogue->set((string) $source, $target, $domain); - $metadata = array(); + $metadata = []; if ($notes = $this->parseNotesMetadata($translation->note, $encoding)) { $metadata['notes'] = $notes; } if (isset($translation->target) && $translation->target->attributes()) { - $metadata['target-attributes'] = array(); + $metadata['target-attributes'] = []; foreach ($translation->target->attributes() as $key => $value) { $metadata['target-attributes'][$key] = (string) $value; } @@ -134,18 +134,18 @@ class XliffFileLoader implements LoaderInterface $catalogue->set((string) $source, $target, $domain); - $metadata = array(); + $metadata = []; if (isset($segment->target) && $segment->target->attributes()) { - $metadata['target-attributes'] = array(); + $metadata['target-attributes'] = []; foreach ($segment->target->attributes() as $key => $value) { $metadata['target-attributes'][$key] = (string) $value; } } if (isset($unit->notes)) { - $metadata['notes'] = array(); + $metadata['notes'] = []; foreach ($unit->notes->note as $noteNode) { - $note = array(); + $note = []; foreach ($noteNode->attributes() as $key => $value) { $note[$key] = (string) $value; } @@ -173,7 +173,7 @@ class XliffFileLoader implements LoaderInterface private function parseNotesMetadata(\SimpleXMLElement $noteElement = null, string $encoding = null): array { - $notes = array(); + $notes = []; if (null === $noteElement) { return $notes; @@ -182,7 +182,7 @@ class XliffFileLoader implements LoaderInterface /** @var \SimpleXMLElement $xmlNote */ foreach ($noteElement as $xmlNote) { $noteAttributes = $xmlNote->attributes(); - $note = array('content' => $this->utf8ToCharset((string) $xmlNote, $encoding)); + $note = ['content' => $this->utf8ToCharset((string) $xmlNote, $encoding)]; if (isset($noteAttributes['priority'])) { $note['priority'] = (int) $noteAttributes['priority']; } diff --git a/src/Symfony/Component/Translation/LoggingTranslator.php b/src/Symfony/Component/Translation/LoggingTranslator.php index 4fe756d7a7..62314b309d 100644 --- a/src/Symfony/Component/Translation/LoggingTranslator.php +++ b/src/Symfony/Component/Translation/LoggingTranslator.php @@ -49,7 +49,7 @@ class LoggingTranslator implements TranslatorInterface, LegacyTranslatorInterfac /** * {@inheritdoc} */ - public function trans($id, array $parameters = array(), $domain = null, $locale = null) + public function trans($id, array $parameters = [], $domain = null, $locale = null) { $trans = $this->translator->trans($id, $parameters, $domain, $locale); $this->log($id, $domain, $locale); @@ -62,12 +62,12 @@ class LoggingTranslator implements TranslatorInterface, LegacyTranslatorInterfac * * @deprecated since Symfony 4.2, use the trans() method instead with a %count% parameter */ - public function transChoice($id, $number, array $parameters = array(), $domain = null, $locale = null) + public function transChoice($id, $number, array $parameters = [], $domain = null, $locale = null) { @trigger_error(sprintf('The "%s()" method is deprecated since Symfony 4.2, use the trans() one instead with a "%count%" parameter.', __METHOD__), E_USER_DEPRECATED); if ($this->translator instanceof TranslatorInterface) { - $trans = $this->translator->trans($id, array('%count%' => $number) + $parameters, $domain, $locale); + $trans = $this->translator->trans($id, ['%count%' => $number] + $parameters, $domain, $locale); } else { $trans = $this->translator->transChoice($id, $number, $parameters, $domain, $locale); } @@ -112,7 +112,7 @@ class LoggingTranslator implements TranslatorInterface, LegacyTranslatorInterfac return $this->translator->getFallbackLocales(); } - return array(); + return []; } /** @@ -143,9 +143,9 @@ class LoggingTranslator implements TranslatorInterface, LegacyTranslatorInterfac } if ($catalogue->has($id, $domain)) { - $this->logger->debug('Translation use fallback catalogue.', array('id' => $id, 'domain' => $domain, 'locale' => $catalogue->getLocale())); + $this->logger->debug('Translation use fallback catalogue.', ['id' => $id, 'domain' => $domain, 'locale' => $catalogue->getLocale()]); } else { - $this->logger->warning('Translation not found.', array('id' => $id, 'domain' => $domain, 'locale' => $catalogue->getLocale())); + $this->logger->warning('Translation not found.', ['id' => $id, 'domain' => $domain, 'locale' => $catalogue->getLocale()]); } } } diff --git a/src/Symfony/Component/Translation/MessageCatalogue.php b/src/Symfony/Component/Translation/MessageCatalogue.php index 7a7657c0a4..19afb903f7 100644 --- a/src/Symfony/Component/Translation/MessageCatalogue.php +++ b/src/Symfony/Component/Translation/MessageCatalogue.php @@ -19,9 +19,9 @@ use Symfony\Component\Translation\Exception\LogicException; */ class MessageCatalogue implements MessageCatalogueInterface, MetadataAwareInterface { - private $messages = array(); - private $metadata = array(); - private $resources = array(); + private $messages = []; + private $metadata = []; + private $resources = []; private $locale; private $fallbackCatalogue; private $parent; @@ -30,7 +30,7 @@ class MessageCatalogue implements MessageCatalogueInterface, MetadataAwareInterf * @param string $locale The locale * @param array $messages An array of messages classified by domain */ - public function __construct(?string $locale, array $messages = array()) + public function __construct(?string $locale, array $messages = []) { $this->locale = $locale; $this->messages = $messages; @@ -49,7 +49,7 @@ class MessageCatalogue implements MessageCatalogueInterface, MetadataAwareInterf */ public function getDomains() { - $domains = array(); + $domains = []; $suffixLength = \strlen(self::INTL_DOMAIN_SUFFIX); foreach ($this->messages as $domain => $messages) { @@ -68,18 +68,18 @@ class MessageCatalogue implements MessageCatalogueInterface, MetadataAwareInterf public function all($domain = null) { if (null !== $domain) { - return ($this->messages[$domain.self::INTL_DOMAIN_SUFFIX] ?? array()) + ($this->messages[$domain] ?? array()); + return ($this->messages[$domain.self::INTL_DOMAIN_SUFFIX] ?? []) + ($this->messages[$domain] ?? []); } - $allMessages = array(); + $allMessages = []; $suffixLength = \strlen(self::INTL_DOMAIN_SUFFIX); foreach ($this->messages as $domain => $messages) { if (\strlen($domain) > $suffixLength && false !== $i = strpos($domain, self::INTL_DOMAIN_SUFFIX, -$suffixLength)) { $domain = substr($domain, 0, $i); - $allMessages[$domain] = $messages + ($allMessages[$domain] ?? array()); + $allMessages[$domain] = $messages + ($allMessages[$domain] ?? []); } else { - $allMessages[$domain] = ($allMessages[$domain] ?? array()) + $messages; + $allMessages[$domain] = ($allMessages[$domain] ?? []) + $messages; } } @@ -91,7 +91,7 @@ class MessageCatalogue implements MessageCatalogueInterface, MetadataAwareInterf */ public function set($id, $translation, $domain = 'messages') { - $this->add(array($id => $translation), $domain); + $this->add([$id => $translation], $domain); } /** @@ -277,7 +277,7 @@ class MessageCatalogue implements MessageCatalogueInterface, MetadataAwareInterf public function deleteMetadata($key = '', $domain = 'messages') { if ('' == $domain) { - $this->metadata = array(); + $this->metadata = []; } elseif ('' == $key) { unset($this->metadata[$domain]); } else { diff --git a/src/Symfony/Component/Translation/Tests/Catalogue/MergeOperationTest.php b/src/Symfony/Component/Translation/Tests/Catalogue/MergeOperationTest.php index d46e801933..22af86e906 100644 --- a/src/Symfony/Component/Translation/Tests/Catalogue/MergeOperationTest.php +++ b/src/Symfony/Component/Translation/Tests/Catalogue/MergeOperationTest.php @@ -56,13 +56,13 @@ class MergeOperationTest extends AbstractOperationTest public function testGetResultFromIntlDomain() { $this->assertEquals( - new MessageCatalogue('en', array( - 'messages' => array('a' => 'old_a', 'b' => 'old_b'), - 'messages+intl-icu' => array('d' => 'old_d', 'c' => 'new_c'), - )), + new MessageCatalogue('en', [ + 'messages' => ['a' => 'old_a', 'b' => 'old_b'], + 'messages+intl-icu' => ['d' => 'old_d', 'c' => 'new_c'], + ]), $this->createOperation( - new MessageCatalogue('en', array('messages' => array('a' => 'old_a', 'b' => 'old_b'), 'messages+intl-icu' => array('d' => 'old_d'))), - new MessageCatalogue('en', array('messages+intl-icu' => array('a' => 'new_a', 'c' => 'new_c'))) + new MessageCatalogue('en', ['messages' => ['a' => 'old_a', 'b' => 'old_b'], 'messages+intl-icu' => ['d' => 'old_d']]), + new MessageCatalogue('en', ['messages+intl-icu' => ['a' => 'new_a', 'c' => 'new_c']]) )->getResult() ); } diff --git a/src/Symfony/Component/Translation/Tests/Catalogue/TargetOperationTest.php b/src/Symfony/Component/Translation/Tests/Catalogue/TargetOperationTest.php index 70999f4c32..570b503aea 100644 --- a/src/Symfony/Component/Translation/Tests/Catalogue/TargetOperationTest.php +++ b/src/Symfony/Component/Translation/Tests/Catalogue/TargetOperationTest.php @@ -56,13 +56,13 @@ class TargetOperationTest extends AbstractOperationTest public function testGetResultFromIntlDomain() { $this->assertEquals( - new MessageCatalogue('en', array( - 'messages' => array('a' => 'old_a'), - 'messages+intl-icu' => array('c' => 'new_c'), - )), + new MessageCatalogue('en', [ + 'messages' => ['a' => 'old_a'], + 'messages+intl-icu' => ['c' => 'new_c'], + ]), $this->createOperation( - new MessageCatalogue('en', array('messages' => array('a' => 'old_a'), 'messages+intl-icu' => array('b' => 'old_b'))), - new MessageCatalogue('en', array('messages' => array('a' => 'new_a'), 'messages+intl-icu' => array('c' => 'new_c'))) + new MessageCatalogue('en', ['messages' => ['a' => 'old_a'], 'messages+intl-icu' => ['b' => 'old_b']]), + new MessageCatalogue('en', ['messages' => ['a' => 'new_a'], 'messages+intl-icu' => ['c' => 'new_c']]) )->getResult() ); } diff --git a/src/Symfony/Component/Translation/Tests/Command/XliffLintCommandTest.php b/src/Symfony/Component/Translation/Tests/Command/XliffLintCommandTest.php index 04272d4b79..516d98af53 100644 --- a/src/Symfony/Component/Translation/Tests/Command/XliffLintCommandTest.php +++ b/src/Symfony/Component/Translation/Tests/Command/XliffLintCommandTest.php @@ -47,8 +47,8 @@ class XliffLintCommandTest extends TestCase $filename2 = $this->createFile(); $tester->execute( - array('filename' => array($filename1, $filename2)), - array('verbosity' => OutputInterface::VERBOSITY_VERBOSE, 'decorated' => false) + ['filename' => [$filename1, $filename2]], + ['verbosity' => OutputInterface::VERBOSITY_VERBOSE, 'decorated' => false] ); $this->assertEquals(0, $tester->getStatusCode(), 'Returns 0 in case of success'); @@ -64,8 +64,8 @@ class XliffLintCommandTest extends TestCase $filename = $this->createFile('note', $targetLanguage, $fileNamePattern); $tester->execute( - array('filename' => $filename), - array('verbosity' => OutputInterface::VERBOSITY_VERBOSE, 'decorated' => false) + ['filename' => $filename], + ['verbosity' => OutputInterface::VERBOSITY_VERBOSE, 'decorated' => false] ); $this->assertEquals($mustFail ? 1 : 0, $tester->getStatusCode()); @@ -195,13 +195,13 @@ XLIFF; public function provideStrictFilenames() { - yield array(false, 'messages.%locale%.xlf', 'en', false); - yield array(false, 'messages.%locale%.xlf', 'es', true); - yield array(false, '%locale%.messages.xlf', 'en', false); - yield array(false, '%locale%.messages.xlf', 'es', true); - yield array(true, 'messages.%locale%.xlf', 'en', false); - yield array(true, 'messages.%locale%.xlf', 'es', true); - yield array(true, '%locale%.messages.xlf', 'en', true); - yield array(true, '%locale%.messages.xlf', 'es', true); + yield [false, 'messages.%locale%.xlf', 'en', false]; + yield [false, 'messages.%locale%.xlf', 'es', true]; + yield [false, '%locale%.messages.xlf', 'en', false]; + yield [false, '%locale%.messages.xlf', 'es', true]; + yield [true, 'messages.%locale%.xlf', 'en', false]; + yield [true, 'messages.%locale%.xlf', 'es', true]; + yield [true, '%locale%.messages.xlf', 'en', true]; + yield [true, '%locale%.messages.xlf', 'es', true]; } } diff --git a/src/Symfony/Component/Translation/Tests/DataCollectorTranslatorTest.php b/src/Symfony/Component/Translation/Tests/DataCollectorTranslatorTest.php index 19e056c12e..138172e21d 100644 --- a/src/Symfony/Component/Translation/Tests/DataCollectorTranslatorTest.php +++ b/src/Symfony/Component/Translation/Tests/DataCollectorTranslatorTest.php @@ -21,60 +21,60 @@ class DataCollectorTranslatorTest extends TestCase public function testCollectMessages() { $collector = $this->createCollector(); - $collector->setFallbackLocales(array('fr', 'ru')); + $collector->setFallbackLocales(['fr', 'ru']); $collector->trans('foo'); $collector->trans('bar'); - $collector->trans('choice', array('%count%' => 0)); + $collector->trans('choice', ['%count%' => 0]); $collector->trans('bar_ru'); - $collector->trans('bar_ru', array('foo' => 'bar')); + $collector->trans('bar_ru', ['foo' => 'bar']); - $expectedMessages = array(); - $expectedMessages[] = array( + $expectedMessages = []; + $expectedMessages[] = [ 'id' => 'foo', 'translation' => 'foo (en)', 'locale' => 'en', 'domain' => 'messages', 'state' => DataCollectorTranslator::MESSAGE_DEFINED, - 'parameters' => array(), + 'parameters' => [], 'transChoiceNumber' => null, - ); - $expectedMessages[] = array( + ]; + $expectedMessages[] = [ 'id' => 'bar', 'translation' => 'bar (fr)', 'locale' => 'fr', 'domain' => 'messages', 'state' => DataCollectorTranslator::MESSAGE_EQUALS_FALLBACK, - 'parameters' => array(), + 'parameters' => [], 'transChoiceNumber' => null, - ); - $expectedMessages[] = array( + ]; + $expectedMessages[] = [ 'id' => 'choice', 'translation' => 'choice', 'locale' => 'en', 'domain' => 'messages', 'state' => DataCollectorTranslator::MESSAGE_MISSING, - 'parameters' => array('%count%' => 0), + 'parameters' => ['%count%' => 0], 'transChoiceNumber' => 0, - ); - $expectedMessages[] = array( + ]; + $expectedMessages[] = [ 'id' => 'bar_ru', 'translation' => 'bar (ru)', 'locale' => 'ru', 'domain' => 'messages', 'state' => DataCollectorTranslator::MESSAGE_EQUALS_FALLBACK, - 'parameters' => array(), + 'parameters' => [], 'transChoiceNumber' => null, - ); - $expectedMessages[] = array( + ]; + $expectedMessages[] = [ 'id' => 'bar_ru', 'translation' => 'bar (ru)', 'locale' => 'ru', 'domain' => 'messages', 'state' => DataCollectorTranslator::MESSAGE_EQUALS_FALLBACK, - 'parameters' => array('foo' => 'bar'), + 'parameters' => ['foo' => 'bar'], 'transChoiceNumber' => null, - ); + ]; $this->assertEquals($expectedMessages, $collector->getCollectedMessages()); } @@ -85,20 +85,20 @@ class DataCollectorTranslatorTest extends TestCase public function testCollectMessagesTransChoice() { $collector = $this->createCollector(); - $collector->setFallbackLocales(array('fr', 'ru')); + $collector->setFallbackLocales(['fr', 'ru']); $collector->transChoice('choice', 0); - $expectedMessages = array(); + $expectedMessages = []; - $expectedMessages[] = array( + $expectedMessages[] = [ 'id' => 'choice', 'translation' => 'choice', 'locale' => 'en', 'domain' => 'messages', 'state' => DataCollectorTranslator::MESSAGE_MISSING, - 'parameters' => array('%count%' => 0), + 'parameters' => ['%count%' => 0], 'transChoiceNumber' => 0, - ); + ]; $this->assertEquals($expectedMessages, $collector->getCollectedMessages()); } @@ -107,9 +107,9 @@ class DataCollectorTranslatorTest extends TestCase { $translator = new Translator('en'); $translator->addLoader('array', new ArrayLoader()); - $translator->addResource('array', array('foo' => 'foo (en)'), 'en'); - $translator->addResource('array', array('bar' => 'bar (fr)'), 'fr'); - $translator->addResource('array', array('bar_ru' => 'bar (ru)'), 'ru'); + $translator->addResource('array', ['foo' => 'foo (en)'], 'en'); + $translator->addResource('array', ['bar' => 'bar (fr)'], 'fr'); + $translator->addResource('array', ['bar_ru' => 'bar (ru)'], 'ru'); return new DataCollectorTranslator($translator); } diff --git a/src/Symfony/Component/Translation/Tests/Dumper/FileDumperTest.php b/src/Symfony/Component/Translation/Tests/Dumper/FileDumperTest.php index 2691a7877e..20fa918bd6 100644 --- a/src/Symfony/Component/Translation/Tests/Dumper/FileDumperTest.php +++ b/src/Symfony/Component/Translation/Tests/Dumper/FileDumperTest.php @@ -37,13 +37,13 @@ class FileDumperTest extends TestCase $tempDir = sys_get_temp_dir(); $catalogue = new MessageCatalogue('en'); - $catalogue->add(array('foo' => 'bar'), 'd1'); - $catalogue->add(array('bar' => 'foo'), 'd1+intl-icu'); - $catalogue->add(array('bar' => 'foo'), 'd2+intl-icu'); + $catalogue->add(['foo' => 'bar'], 'd1'); + $catalogue->add(['bar' => 'foo'], 'd1+intl-icu'); + $catalogue->add(['bar' => 'foo'], 'd2+intl-icu'); $dumper = new ConcreteFileDumper(); @unlink($tempDir.'/d2.en.concrete'); - $dumper->dump($catalogue, array('path' => $tempDir)); + $dumper->dump($catalogue, ['path' => $tempDir]); $this->assertStringEqualsFile($tempDir.'/d1.en.concrete', 'foo=bar'); @unlink($tempDir.'/d1.en.concrete'); diff --git a/src/Symfony/Component/Translation/Tests/Formatter/IntlFormatterTest.php b/src/Symfony/Component/Translation/Tests/Formatter/IntlFormatterTest.php index 89eaa18f32..45ce6d4f6e 100644 --- a/src/Symfony/Component/Translation/Tests/Formatter/IntlFormatterTest.php +++ b/src/Symfony/Component/Translation/Tests/Formatter/IntlFormatterTest.php @@ -31,7 +31,7 @@ class IntlFormatterTest extends \PHPUnit\Framework\TestCase public function testInvalidFormat() { $this->expectException(InvalidArgumentException::class); - (new IntlFormatter())->formatIntl('{foo', 'en', array(2)); + (new IntlFormatter())->formatIntl('{foo', 'en', [2]); } public function testFormatWithNamedArguments() @@ -59,38 +59,38 @@ class IntlFormatterTest extends \PHPUnit\Framework\TestCase other {{host} invites {guest} as one of the # people invited to their party.}}}} _MSG_; - $message = (new IntlFormatter())->formatIntl($chooseMessage, 'en', array( + $message = (new IntlFormatter())->formatIntl($chooseMessage, 'en', [ 'gender_of_host' => 'male', 'num_guests' => 10, 'host' => 'Fabien', 'guest' => 'Guilherme', - )); + ]); $this->assertEquals('Fabien invites Guilherme as one of the 9 people invited to his party.', $message); } public function provideDataForFormat() { - return array( - array( + return [ + [ 'There is one apple', 'There is one apple', - array(), - ), - array( + [], + ], + [ '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', - array(4560, 123, 4560 / 123), - ), - ); + [4560, 123, 4560 / 123], + ], + ]; } public function testPercentsAndBracketsAreTrimmed() { $formatter = new IntlFormatter(); $this->assertInstanceof(IntlFormatterInterface::class, $formatter); - $this->assertSame('Hello Fab', $formatter->formatIntl('Hello {name}', 'en', array('name' => 'Fab'))); - $this->assertSame('Hello Fab', $formatter->formatIntl('Hello {name}', 'en', array('%name%' => 'Fab'))); - $this->assertSame('Hello Fab', $formatter->formatIntl('Hello {name}', 'en', array('{{ name }}' => 'Fab'))); + $this->assertSame('Hello Fab', $formatter->formatIntl('Hello {name}', 'en', ['name' => 'Fab'])); + $this->assertSame('Hello Fab', $formatter->formatIntl('Hello {name}', 'en', ['%name%' => 'Fab'])); + $this->assertSame('Hello Fab', $formatter->formatIntl('Hello {name}', 'en', ['{{ name }}' => 'Fab'])); } } diff --git a/src/Symfony/Component/Translation/Tests/LoggingTranslatorTest.php b/src/Symfony/Component/Translation/Tests/LoggingTranslatorTest.php index 0e43cbecf4..450e060aab 100644 --- a/src/Symfony/Component/Translation/Tests/LoggingTranslatorTest.php +++ b/src/Symfony/Component/Translation/Tests/LoggingTranslatorTest.php @@ -43,11 +43,11 @@ class LoggingTranslatorTest extends TestCase ; $translator = new Translator('ar'); - $translator->setFallbackLocales(array('en')); + $translator->setFallbackLocales(['en']); $translator->addLoader('array', new ArrayLoader()); - $translator->addResource('array', array('some_message2' => 'one thing|%count% things'), 'en'); + $translator->addResource('array', ['some_message2' => 'one thing|%count% things'], 'en'); $loggableTranslator = new LoggingTranslator($translator, $logger); - $loggableTranslator->transChoice('some_message2', 10, array('%count%' => 10)); + $loggableTranslator->transChoice('some_message2', 10, ['%count%' => 10]); } /** @@ -63,6 +63,6 @@ class LoggingTranslatorTest extends TestCase $translator = new Translator('ar'); $loggableTranslator = new LoggingTranslator($translator, $logger); - $loggableTranslator->transChoice('some_message2', 10, array('%count%' => 10)); + $loggableTranslator->transChoice('some_message2', 10, ['%count%' => 10]); } } diff --git a/src/Symfony/Component/Translation/Tests/MessageCatalogueTest.php b/src/Symfony/Component/Translation/Tests/MessageCatalogueTest.php index 3339f3db20..6fe9368f5c 100644 --- a/src/Symfony/Component/Translation/Tests/MessageCatalogueTest.php +++ b/src/Symfony/Component/Translation/Tests/MessageCatalogueTest.php @@ -25,40 +25,40 @@ class MessageCatalogueTest extends TestCase public function testGetDomains() { - $catalogue = new MessageCatalogue('en', array('domain1' => array(), 'domain2' => array(), 'domain2+intl-icu' => array(), 'domain3+intl-icu' => array())); + $catalogue = new MessageCatalogue('en', ['domain1' => [], 'domain2' => [], 'domain2+intl-icu' => [], 'domain3+intl-icu' => []]); - $this->assertEquals(array('domain1', 'domain2', 'domain3'), $catalogue->getDomains()); + $this->assertEquals(['domain1', 'domain2', 'domain3'], $catalogue->getDomains()); } public function testAll() { - $catalogue = new MessageCatalogue('en', $messages = array('domain1' => array('foo' => 'foo'), 'domain2' => array('bar' => 'bar'))); + $catalogue = new MessageCatalogue('en', $messages = ['domain1' => ['foo' => 'foo'], 'domain2' => ['bar' => 'bar']]); - $this->assertEquals(array('foo' => 'foo'), $catalogue->all('domain1')); - $this->assertEquals(array(), $catalogue->all('domain88')); + $this->assertEquals(['foo' => 'foo'], $catalogue->all('domain1')); + $this->assertEquals([], $catalogue->all('domain88')); $this->assertEquals($messages, $catalogue->all()); - $messages = array('domain1+intl-icu' => array('foo' => 'bar')) + $messages + array( - 'domain2+intl-icu' => array('bar' => 'foo'), - 'domain3+intl-icu' => array('biz' => 'biz'), - ); + $messages = ['domain1+intl-icu' => ['foo' => 'bar']] + $messages + [ + 'domain2+intl-icu' => ['bar' => 'foo'], + 'domain3+intl-icu' => ['biz' => 'biz'], + ]; $catalogue = new MessageCatalogue('en', $messages); - $this->assertEquals(array('foo' => 'bar'), $catalogue->all('domain1')); - $this->assertEquals(array('bar' => 'foo'), $catalogue->all('domain2')); - $this->assertEquals(array('biz' => 'biz'), $catalogue->all('domain3')); + $this->assertEquals(['foo' => 'bar'], $catalogue->all('domain1')); + $this->assertEquals(['bar' => 'foo'], $catalogue->all('domain2')); + $this->assertEquals(['biz' => 'biz'], $catalogue->all('domain3')); - $messages = array( - 'domain1' => array('foo' => 'bar'), - 'domain2' => array('bar' => 'foo'), - 'domain3' => array('biz' => 'biz'), - ); + $messages = [ + 'domain1' => ['foo' => 'bar'], + 'domain2' => ['bar' => 'foo'], + 'domain3' => ['biz' => 'biz'], + ]; $this->assertEquals($messages, $catalogue->all()); } public function testHas() { - $catalogue = new MessageCatalogue('en', array('domain1' => array('foo' => 'foo'), 'domain2+intl-icu' => array('bar' => 'bar'))); + $catalogue = new MessageCatalogue('en', ['domain1' => ['foo' => 'foo'], 'domain2+intl-icu' => ['bar' => 'bar']]); $this->assertTrue($catalogue->has('foo', 'domain1')); $this->assertTrue($catalogue->has('bar', 'domain2')); @@ -68,7 +68,7 @@ class MessageCatalogueTest extends TestCase public function testGetSet() { - $catalogue = new MessageCatalogue('en', array('domain1' => array('foo' => 'foo'), 'domain2' => array('bar' => 'bar'), 'domain2+intl-icu' => array('bar' => 'foo'))); + $catalogue = new MessageCatalogue('en', ['domain1' => ['foo' => 'foo'], 'domain2' => ['bar' => 'bar'], 'domain2+intl-icu' => ['bar' => 'foo']]); $catalogue->set('foo1', 'foo1', 'domain1'); $this->assertEquals('foo', $catalogue->get('foo', 'domain1')); @@ -78,24 +78,24 @@ class MessageCatalogueTest extends TestCase public function testAdd() { - $catalogue = new MessageCatalogue('en', array('domain1' => array('foo' => 'foo'), 'domain2' => array('bar' => 'bar'))); - $catalogue->add(array('foo1' => 'foo1'), 'domain1'); + $catalogue = new MessageCatalogue('en', ['domain1' => ['foo' => 'foo'], 'domain2' => ['bar' => 'bar']]); + $catalogue->add(['foo1' => 'foo1'], 'domain1'); $this->assertEquals('foo', $catalogue->get('foo', 'domain1')); $this->assertEquals('foo1', $catalogue->get('foo1', 'domain1')); - $catalogue->add(array('foo' => 'bar'), 'domain1'); + $catalogue->add(['foo' => 'bar'], 'domain1'); $this->assertEquals('bar', $catalogue->get('foo', 'domain1')); $this->assertEquals('foo1', $catalogue->get('foo1', 'domain1')); - $catalogue->add(array('foo' => 'bar'), 'domain88'); + $catalogue->add(['foo' => 'bar'], 'domain88'); $this->assertEquals('bar', $catalogue->get('foo', 'domain88')); } public function testReplace() { - $catalogue = new MessageCatalogue('en', array('domain1' => array('foo' => 'foo'), 'domain1+intl-icu' => array('bar' => 'bar'))); - $catalogue->replace($messages = array('foo1' => 'foo1'), 'domain1'); + $catalogue = new MessageCatalogue('en', ['domain1' => ['foo' => 'foo'], 'domain1+intl-icu' => ['bar' => 'bar']]); + $catalogue->replace($messages = ['foo1' => 'foo1'], 'domain1'); $this->assertEquals($messages, $catalogue->all('domain1')); } @@ -108,10 +108,10 @@ class MessageCatalogueTest extends TestCase $r1 = $this->getMockBuilder('Symfony\Component\Config\Resource\ResourceInterface')->getMock(); $r1->expects($this->any())->method('__toString')->will($this->returnValue('r1')); - $catalogue = new MessageCatalogue('en', array('domain1' => array('foo' => 'foo'))); + $catalogue = new MessageCatalogue('en', ['domain1' => ['foo' => 'foo']]); $catalogue->addResource($r); - $catalogue1 = new MessageCatalogue('en', array('domain1' => array('foo1' => 'foo1'), 'domain2+intl-icu' => array('bar' => 'bar'))); + $catalogue1 = new MessageCatalogue('en', ['domain1' => ['foo1' => 'foo1'], 'domain2+intl-icu' => ['bar' => 'bar']]); $catalogue1->addResource($r1); $catalogue->addCatalogue($catalogue1); @@ -121,7 +121,7 @@ class MessageCatalogueTest extends TestCase $this->assertEquals('bar', $catalogue->get('bar', 'domain2')); $this->assertEquals('bar', $catalogue->get('bar', 'domain2+intl-icu')); - $this->assertEquals(array($r, $r1), $catalogue->getResources()); + $this->assertEquals([$r, $r1], $catalogue->getResources()); } public function testAddFallbackCatalogue() @@ -135,10 +135,10 @@ class MessageCatalogueTest extends TestCase $r2 = $this->getMockBuilder('Symfony\Component\Config\Resource\ResourceInterface')->getMock(); $r2->expects($this->any())->method('__toString')->will($this->returnValue('r2')); - $catalogue = new MessageCatalogue('fr_FR', array('domain1' => array('foo' => 'foo'), 'domain2' => array('bar' => 'bar'))); + $catalogue = new MessageCatalogue('fr_FR', ['domain1' => ['foo' => 'foo'], 'domain2' => ['bar' => 'bar']]); $catalogue->addResource($r); - $catalogue1 = new MessageCatalogue('fr', array('domain1' => array('foo' => 'bar', 'foo1' => 'foo1'))); + $catalogue1 = new MessageCatalogue('fr', ['domain1' => ['foo' => 'bar', 'foo1' => 'foo1']]); $catalogue1->addResource($r1); $catalogue2 = new MessageCatalogue('en'); @@ -150,7 +150,7 @@ class MessageCatalogueTest extends TestCase $this->assertEquals('foo', $catalogue->get('foo', 'domain1')); $this->assertEquals('foo1', $catalogue->get('foo1', 'domain1')); - $this->assertEquals(array($r, $r1, $r2), $catalogue->getResources()); + $this->assertEquals([$r, $r1, $r2], $catalogue->getResources()); } /** @@ -185,7 +185,7 @@ class MessageCatalogueTest extends TestCase public function testAddCatalogueWhenLocaleIsNotTheSameAsTheCurrentOne() { $catalogue = new MessageCatalogue('en'); - $catalogue->addCatalogue(new MessageCatalogue('fr', array())); + $catalogue->addCatalogue(new MessageCatalogue('fr', [])); } public function testGetAddResource() @@ -199,13 +199,13 @@ class MessageCatalogueTest extends TestCase $r1->expects($this->any())->method('__toString')->will($this->returnValue('r1')); $catalogue->addResource($r1); - $this->assertEquals(array($r, $r1), $catalogue->getResources()); + $this->assertEquals([$r, $r1], $catalogue->getResources()); } public function testMetadataDelete() { $catalogue = new MessageCatalogue('en'); - $this->assertEquals(array(), $catalogue->getMetadata('', ''), 'Metadata is empty'); + $this->assertEquals([], $catalogue->getMetadata('', ''), 'Metadata is empty'); $catalogue->deleteMetadata('key', 'messages'); $catalogue->deleteMetadata('', 'messages'); $catalogue->deleteMetadata(); @@ -217,8 +217,8 @@ class MessageCatalogueTest extends TestCase $catalogue->setMetadata('key', 'value'); $this->assertEquals('value', $catalogue->getMetadata('key', 'messages'), "Metadata 'key' = 'value'"); - $catalogue->setMetadata('key2', array()); - $this->assertEquals(array(), $catalogue->getMetadata('key2', 'messages'), 'Metadata key2 is array'); + $catalogue->setMetadata('key2', []); + $this->assertEquals([], $catalogue->getMetadata('key2', 'messages'), 'Metadata key2 is array'); $catalogue->deleteMetadata('key2', 'messages'); $this->assertNull($catalogue->getMetadata('key2', 'messages'), 'Metadata key2 should is deleted.'); @@ -231,13 +231,13 @@ class MessageCatalogueTest extends TestCase { $cat1 = new MessageCatalogue('en'); $cat1->setMetadata('a', 'b'); - $this->assertEquals(array('messages' => array('a' => 'b')), $cat1->getMetadata('', ''), 'Cat1 contains messages metadata.'); + $this->assertEquals(['messages' => ['a' => 'b']], $cat1->getMetadata('', ''), 'Cat1 contains messages metadata.'); $cat2 = new MessageCatalogue('en'); $cat2->setMetadata('b', 'c', 'domain'); - $this->assertEquals(array('domain' => array('b' => 'c')), $cat2->getMetadata('', ''), 'Cat2 contains domain metadata.'); + $this->assertEquals(['domain' => ['b' => 'c']], $cat2->getMetadata('', ''), 'Cat2 contains domain metadata.'); $cat1->addCatalogue($cat2); - $this->assertEquals(array('messages' => array('a' => 'b'), 'domain' => array('b' => 'c')), $cat1->getMetadata('', ''), 'Cat1 contains merged metadata.'); + $this->assertEquals(['messages' => ['a' => 'b'], 'domain' => ['b' => 'c']], $cat1->getMetadata('', ''), 'Cat1 contains merged metadata.'); } } diff --git a/src/Symfony/Component/Translation/Tests/TranslatorCacheTest.php b/src/Symfony/Component/Translation/Tests/TranslatorCacheTest.php index 77c264b491..58e1936ed3 100644 --- a/src/Symfony/Component/Translation/Tests/TranslatorCacheTest.php +++ b/src/Symfony/Component/Translation/Tests/TranslatorCacheTest.php @@ -65,18 +65,18 @@ class TranslatorCacheTest extends TestCase // Prime the cache $translator = new Translator($locale, null, $this->tmpDir, $debug); $translator->addLoader($format, new ArrayLoader()); - $translator->addResource($format, array($msgid => 'OK'), $locale); - $translator->addResource($format, array($msgid.'+intl' => 'OK'), $locale, 'messages+intl-icu'); + $translator->addResource($format, [$msgid => 'OK'], $locale); + $translator->addResource($format, [$msgid.'+intl' => 'OK'], $locale, 'messages+intl-icu'); $translator->trans($msgid); - $translator->trans($msgid.'+intl', array(), 'messages+intl-icu'); + $translator->trans($msgid.'+intl', [], 'messages+intl-icu'); // Try again and see we get a valid result whilst no loader can be used $translator = new Translator($locale, null, $this->tmpDir, $debug); $translator->addLoader($format, $this->createFailingLoader()); - $translator->addResource($format, array($msgid => 'OK'), $locale); - $translator->addResource($format, array($msgid.'+intl' => 'OK'), $locale, 'messages+intl-icu'); + $translator->addResource($format, [$msgid => 'OK'], $locale); + $translator->addResource($format, [$msgid.'+intl' => 'OK'], $locale, 'messages+intl-icu'); $this->assertEquals('OK', $translator->trans($msgid), '-> caching does not work in '.($debug ? 'debug' : 'production')); - $this->assertEquals('OK', $translator->trans($msgid.'+intl', array(), 'messages+intl-icu')); + $this->assertEquals('OK', $translator->trans($msgid.'+intl', [], 'messages+intl-icu')); } public function testCatalogueIsReloadedWhenResourcesAreNoLongerFresh() @@ -96,7 +96,7 @@ class TranslatorCacheTest extends TestCase $format = 'some_format'; $msgid = 'test'; - $catalogue = new MessageCatalogue($locale, array()); + $catalogue = new MessageCatalogue($locale, []); $catalogue->addResource(new StaleResource()); // better use a helper class than a mock, because it gets serialized in the cache and re-loaded /** @var LoaderInterface|\PHPUnit_Framework_MockObject_MockObject $loader */ @@ -137,26 +137,26 @@ class TranslatorCacheTest extends TestCase // Create a Translator and prime its cache $translator = new Translator($locale, null, $this->tmpDir, $debug); $translator->addLoader($format, new ArrayLoader()); - $translator->addResource($format, array($msgid => 'OK'), $locale); + $translator->addResource($format, [$msgid => 'OK'], $locale); $translator->trans($msgid); // Create another Translator with a different catalogue for the same locale $translator = new Translator($locale, null, $this->tmpDir, $debug); $translator->addLoader($format, new ArrayLoader()); - $translator->addResource($format, array($msgid => 'FAIL'), $locale); + $translator->addResource($format, [$msgid => 'FAIL'], $locale); $translator->trans($msgid); // Now the first translator must still have a usable cache. $translator = new Translator($locale, null, $this->tmpDir, $debug); $translator->addLoader($format, $this->createFailingLoader()); - $translator->addResource($format, array($msgid => 'OK'), $locale); + $translator->addResource($format, [$msgid => 'OK'], $locale); $this->assertEquals('OK', $translator->trans($msgid), '-> the cache was overwritten by another translator instance in '.($debug ? 'debug' : 'production')); } public function testGeneratedCacheFilesAreOnlyBelongRequestedLocales() { $translator = new Translator('a', null, $this->tmpDir); - $translator->setFallbackLocales(array('b')); + $translator->setFallbackLocales(['b']); $translator->trans('bar'); $cachedFiles = glob($this->tmpDir.'/*.php'); @@ -172,24 +172,24 @@ class TranslatorCacheTest extends TestCase * loading a catalogue from the cache. */ $translator = new Translator('a', null, $this->tmpDir); - $translator->setFallbackLocales(array('b')); + $translator->setFallbackLocales(['b']); $translator->addLoader('array', new ArrayLoader()); - $translator->addResource('array', array('foo' => 'foo (a)'), 'a'); - $translator->addResource('array', array('bar' => 'bar (b)'), 'b'); + $translator->addResource('array', ['foo' => 'foo (a)'], 'a'); + $translator->addResource('array', ['bar' => 'bar (b)'], 'b'); $this->assertEquals('bar (b)', $translator->trans('bar')); // Remove fallback locale - $translator->setFallbackLocales(array()); + $translator->setFallbackLocales([]); $this->assertEquals('bar', $translator->trans('bar')); // Use a fresh translator with no fallback locales, result should be the same $translator = new Translator('a', null, $this->tmpDir); $translator->addLoader('array', new ArrayLoader()); - $translator->addResource('array', array('foo' => 'foo (a)'), 'a'); - $translator->addResource('array', array('bar' => 'bar (b)'), 'b'); + $translator->addResource('array', ['foo' => 'foo (a)'], 'a'); + $translator->addResource('array', ['bar' => 'bar (b)'], 'b'); $this->assertEquals('bar', $translator->trans('bar')); } @@ -210,13 +210,13 @@ class TranslatorCacheTest extends TestCase * The catalogues contain distinct sets of messages. */ $translator = new Translator('a', null, $this->tmpDir); - $translator->setFallbackLocales(array('b')); + $translator->setFallbackLocales(['b']); $translator->addLoader('array', new ArrayLoader()); - $translator->addResource('array', array('foo' => 'foo (a)'), 'a'); - $translator->addResource('array', array('foo' => 'foo (b)'), 'b'); - $translator->addResource('array', array('bar' => 'bar (b)'), 'b'); - $translator->addResource('array', array('baz' => 'baz (b)'), 'b', 'messages+intl-icu'); + $translator->addResource('array', ['foo' => 'foo (a)'], 'a'); + $translator->addResource('array', ['foo' => 'foo (b)'], 'b'); + $translator->addResource('array', ['bar' => 'bar (b)'], 'b'); + $translator->addResource('array', ['baz' => 'baz (b)'], 'b', 'messages+intl-icu'); $catalogue = $translator->getCatalogue('a'); $this->assertFalse($catalogue->defines('bar')); // Sure, the "a" catalogue does not contain that message. @@ -229,13 +229,13 @@ class TranslatorCacheTest extends TestCase * Behind the scenes, the cache is used. But that should not matter, right? */ $translator = new Translator('a', null, $this->tmpDir); - $translator->setFallbackLocales(array('b')); + $translator->setFallbackLocales(['b']); $translator->addLoader('array', new ArrayLoader()); - $translator->addResource('array', array('foo' => 'foo (a)'), 'a'); - $translator->addResource('array', array('foo' => 'foo (b)'), 'b'); - $translator->addResource('array', array('bar' => 'bar (b)'), 'b'); - $translator->addResource('array', array('baz' => 'baz (b)'), 'b', 'messages+intl-icu'); + $translator->addResource('array', ['foo' => 'foo (a)'], 'a'); + $translator->addResource('array', ['foo' => 'foo (b)'], 'b'); + $translator->addResource('array', ['bar' => 'bar (b)'], 'b'); + $translator->addResource('array', ['baz' => 'baz (b)'], 'b', 'messages+intl-icu'); $catalogue = $translator->getCatalogue('a'); $this->assertFalse($catalogue->defines('bar')); @@ -253,7 +253,7 @@ class TranslatorCacheTest extends TestCase $loader ->expects($this->exactly(2)) ->method('load') - ->will($this->returnValue($this->getCatalogue('fr', array(), array($resource)))); + ->will($this->returnValue($this->getCatalogue('fr', [], [$resource]))); // prime the cache $translator = new Translator('fr', null, $this->tmpDir, true); @@ -268,7 +268,7 @@ class TranslatorCacheTest extends TestCase $translator->trans('foo'); } - protected function getCatalogue($locale, $messages, $resources = array()) + protected function getCatalogue($locale, $messages, $resources = []) { $catalogue = new MessageCatalogue($locale); foreach ($messages as $key => $translation) { @@ -283,7 +283,7 @@ class TranslatorCacheTest extends TestCase public function runForDebugAndProduction() { - return array(array(true), array(false)); + return [[true], [false]]; } /** diff --git a/src/Symfony/Component/Translation/Tests/TranslatorTest.php b/src/Symfony/Component/Translation/Tests/TranslatorTest.php index bbc8ce2d21..51c4a0a048 100644 --- a/src/Symfony/Component/Translation/Tests/TranslatorTest.php +++ b/src/Symfony/Component/Translation/Tests/TranslatorTest.php @@ -97,8 +97,8 @@ class TranslatorTest extends TestCase $translator = new Translator($locale); $translator->addLoader('loader-a', new ArrayLoader()); $translator->addLoader('loader-b', new ArrayLoader()); - $translator->addResource('loader-a', array('foo' => 'foofoo'), $locale, 'domain-a'); - $translator->addResource('loader-b', array('bar' => 'foobar'), $locale, 'domain-b'); + $translator->addResource('loader-a', ['foo' => 'foofoo'], $locale, 'domain-a'); + $translator->addResource('loader-b', ['bar' => 'foobar'], $locale, 'domain-b'); /* * Test that we get a single catalogue comprising messages @@ -113,13 +113,13 @@ class TranslatorTest extends TestCase { $translator = new Translator('en'); $translator->addLoader('array', new ArrayLoader()); - $translator->addResource('array', array('foo' => 'foofoo'), 'en'); - $translator->addResource('array', array('bar' => 'foobar'), 'fr'); + $translator->addResource('array', ['foo' => 'foofoo'], 'en'); + $translator->addResource('array', ['bar' => 'foobar'], 'fr'); // force catalogue loading $translator->trans('bar'); - $translator->setFallbackLocales(array('fr')); + $translator->setFallbackLocales(['fr']); $this->assertEquals('foobar', $translator->trans('bar')); } @@ -127,13 +127,13 @@ class TranslatorTest extends TestCase { $translator = new Translator('en'); $translator->addLoader('array', new ArrayLoader()); - $translator->addResource('array', array('foo' => 'foo (en)'), 'en'); - $translator->addResource('array', array('bar' => 'bar (fr)'), 'fr'); + $translator->addResource('array', ['foo' => 'foo (en)'], 'en'); + $translator->addResource('array', ['bar' => 'bar (fr)'], 'fr'); // force catalogue loading $translator->trans('bar'); - $translator->setFallbackLocales(array('fr_FR', 'fr')); + $translator->setFallbackLocales(['fr_FR', 'fr']); $this->assertEquals('bar (fr)', $translator->trans('bar')); } @@ -144,7 +144,7 @@ class TranslatorTest extends TestCase public function testSetFallbackInvalidLocales($locale) { $translator = new Translator('fr'); - $translator->setFallbackLocales(array('fr', $locale)); + $translator->setFallbackLocales(['fr', $locale]); } /** @@ -153,7 +153,7 @@ class TranslatorTest extends TestCase public function testSetFallbackValidLocales($locale) { $translator = new Translator($locale); - $translator->setFallbackLocales(array('fr', $locale)); + $translator->setFallbackLocales(['fr', $locale]); // no assertion. this method just asserts that no exception is thrown $this->addToAssertionCount(1); } @@ -161,10 +161,10 @@ class TranslatorTest extends TestCase public function testTransWithFallbackLocale() { $translator = new Translator('fr_FR'); - $translator->setFallbackLocales(array('en')); + $translator->setFallbackLocales(['en']); $translator->addLoader('array', new ArrayLoader()); - $translator->addResource('array', array('bar' => 'foobar'), 'en'); + $translator->addResource('array', ['bar' => 'foobar'], 'en'); $this->assertEquals('foobar', $translator->trans('bar')); } @@ -176,7 +176,7 @@ class TranslatorTest extends TestCase public function testAddResourceInvalidLocales($locale) { $translator = new Translator('fr'); - $translator->addResource('array', array('foo' => 'foofoo'), $locale); + $translator->addResource('array', ['foo' => 'foofoo'], $locale); } /** @@ -185,7 +185,7 @@ class TranslatorTest extends TestCase public function testAddResourceValidLocales($locale) { $translator = new Translator('fr'); - $translator->addResource('array', array('foo' => 'foofoo'), $locale); + $translator->addResource('array', ['foo' => 'foofoo'], $locale); // no assertion. this method just asserts that no exception is thrown $this->addToAssertionCount(1); } @@ -195,12 +195,12 @@ class TranslatorTest extends TestCase $translator = new Translator('fr'); $translator->addLoader('array', new ArrayLoader()); - $translator->setFallbackLocales(array('en')); + $translator->setFallbackLocales(['en']); - $translator->addResource('array', array('foo' => 'foofoo'), 'en'); + $translator->addResource('array', ['foo' => 'foofoo'], 'en'); $this->assertEquals('foofoo', $translator->trans('foo')); - $translator->addResource('array', array('bar' => 'foobar'), 'en'); + $translator->addResource('array', ['bar' => 'foobar'], 'en'); $this->assertEquals('foobar', $translator->trans('bar')); } @@ -231,16 +231,16 @@ class TranslatorTest extends TestCase $translator->addResource($format, __DIR__.'/fixtures/non-existing', 'en_GB'); $translator->addResource($format, __DIR__.'/fixtures/resources.'.$format, 'en', 'resources'); - $this->assertEquals('bar', $translator->trans('foo', array(), 'resources')); + $this->assertEquals('bar', $translator->trans('foo', [], 'resources')); } public function testTransWithIcuFallbackLocale() { $translator = new Translator('en_GB'); $translator->addLoader('array', new ArrayLoader()); - $translator->addResource('array', array('foo' => 'foofoo'), 'en_GB'); - $translator->addResource('array', array('bar' => 'foobar'), 'en_001'); - $translator->addResource('array', array('baz' => 'foobaz'), 'en'); + $translator->addResource('array', ['foo' => 'foofoo'], 'en_GB'); + $translator->addResource('array', ['bar' => 'foobar'], 'en_001'); + $translator->addResource('array', ['baz' => 'foobaz'], 'en'); $this->assertSame('foofoo', $translator->trans('foo')); $this->assertSame('foobar', $translator->trans('bar')); $this->assertSame('foobaz', $translator->trans('baz')); @@ -250,10 +250,10 @@ class TranslatorTest extends TestCase { $translator = new Translator('en_GB_scouse'); $translator->addLoader('array', new ArrayLoader()); - $translator->addResource('array', array('foo' => 'foofoo'), 'en_GB_scouse'); - $translator->addResource('array', array('bar' => 'foobar'), 'en_GB'); - $translator->addResource('array', array('baz' => 'foobaz'), 'en_001'); - $translator->addResource('array', array('qux' => 'fooqux'), 'en'); + $translator->addResource('array', ['foo' => 'foofoo'], 'en_GB_scouse'); + $translator->addResource('array', ['bar' => 'foobar'], 'en_GB'); + $translator->addResource('array', ['baz' => 'foobaz'], 'en_001'); + $translator->addResource('array', ['qux' => 'fooqux'], 'en'); $this->assertSame('foofoo', $translator->trans('foo')); $this->assertSame('foobar', $translator->trans('bar')); $this->assertSame('foobaz', $translator->trans('baz')); @@ -264,8 +264,8 @@ class TranslatorTest extends TestCase { $translator = new Translator('az_Cyrl'); $translator->addLoader('array', new ArrayLoader()); - $translator->addResource('array', array('foo' => 'foofoo'), 'az_Cyrl'); - $translator->addResource('array', array('bar' => 'foobar'), 'az'); + $translator->addResource('array', ['foo' => 'foofoo'], 'az_Cyrl'); + $translator->addResource('array', ['bar' => 'foobar'], 'az'); $this->assertSame('foofoo', $translator->trans('foo')); $this->assertSame('bar', $translator->trans('bar')); } @@ -274,8 +274,8 @@ class TranslatorTest extends TestCase { $translator = new Translator('en_US'); $translator->addLoader('array', new ArrayLoader()); - $translator->addResource('array', array('foo' => 'foofoo'), 'en_US'); - $translator->addResource('array', array('bar' => 'foobar'), 'en'); + $translator->addResource('array', ['foo' => 'foofoo'], 'en_US'); + $translator->addResource('array', ['bar' => 'foobar'], 'en'); $this->assertEquals('foobar', $translator->trans('bar')); } @@ -283,10 +283,10 @@ class TranslatorTest extends TestCase { $translator = new Translator('fr_FR'); $translator->addLoader('array', new ArrayLoader()); - $translator->addResource('array', array('foo' => 'foo (en_US)'), 'en_US'); - $translator->addResource('array', array('bar' => 'bar (en)'), 'en'); + $translator->addResource('array', ['foo' => 'foo (en_US)'], 'en_US'); + $translator->addResource('array', ['bar' => 'bar (en)'], 'en'); - $translator->setFallbackLocales(array('en_US', 'en')); + $translator->setFallbackLocales(['en_US', 'en']); $this->assertEquals('foo (en_US)', $translator->trans('foo')); $this->assertEquals('bar (en)', $translator->trans('bar')); @@ -295,7 +295,7 @@ class TranslatorTest extends TestCase public function testTransNonExistentWithFallback() { $translator = new Translator('fr'); - $translator->setFallbackLocales(array('en')); + $translator->setFallbackLocales(['en']); $translator->addLoader('array', new ArrayLoader()); $this->assertEquals('non-existent', $translator->trans('non-existent')); } @@ -306,7 +306,7 @@ class TranslatorTest extends TestCase public function testWhenAResourceHasNoRegisteredLoader() { $translator = new Translator('en'); - $translator->addResource('array', array('foo' => 'foofoo'), 'en'); + $translator->addResource('array', ['foo' => 'foofoo'], 'en'); $translator->trans('foo'); } @@ -314,7 +314,7 @@ class TranslatorTest extends TestCase public function testNestedFallbackCatalogueWhenUsingMultipleLocales() { $translator = new Translator('fr'); - $translator->setFallbackLocales(array('ru', 'en')); + $translator->setFallbackLocales(['ru', 'en']); $translator->getCatalogue('fr'); @@ -329,7 +329,7 @@ class TranslatorTest extends TestCase $translator->addResource('yml', __DIR__.'/fixtures/resources.yml', 'en'); // force catalogue loading - $this->assertEquals('bar', $translator->trans('foo', array())); + $this->assertEquals('bar', $translator->trans('foo', [])); $resources = $translator->getCatalogue('en')->getResources(); $this->assertCount(1, $resources); @@ -348,7 +348,7 @@ class TranslatorTest extends TestCase { $translator = new Translator('en'); $translator->addLoader('array', new ArrayLoader()); - $translator->addResource('array', array((string) $id => $translation), $locale, $domain); + $translator->addResource('array', [(string) $id => $translation], $locale, $domain); $this->assertEquals($expected, $translator->trans($id, $parameters, $domain, $locale)); } @@ -361,9 +361,9 @@ class TranslatorTest extends TestCase { $translator = new Translator('en'); $translator->addLoader('array', new ArrayLoader()); - $translator->addResource('array', array('foo' => 'foofoo'), 'en'); + $translator->addResource('array', ['foo' => 'foofoo'], 'en'); - $translator->trans('foo', array(), '', $locale); + $translator->trans('foo', [], '', $locale); } /** @@ -373,10 +373,10 @@ class TranslatorTest extends TestCase { $translator = new Translator($locale); $translator->addLoader('array', new ArrayLoader()); - $translator->addResource('array', array('test' => 'OK'), $locale); + $translator->addResource('array', ['test' => 'OK'], $locale); $this->assertEquals('OK', $translator->trans('test')); - $this->assertEquals('OK', $translator->trans('test', array(), null, $locale)); + $this->assertEquals('OK', $translator->trans('test', [], null, $locale)); } /** @@ -388,7 +388,7 @@ class TranslatorTest extends TestCase $translator->addLoader('array', new ArrayLoader()); $translator->addResource('array', $messages, 'fr', ''); - $this->assertEquals($expected, $translator->trans($id, array(), '', 'fr')); + $this->assertEquals($expected, $translator->trans($id, [], '', 'fr')); } /** @@ -399,7 +399,7 @@ class TranslatorTest extends TestCase { $translator = new Translator('en'); $translator->addLoader('array', new ArrayLoader()); - $translator->addResource('array', array((string) $id => $translation), $locale, $domain); + $translator->addResource('array', [(string) $id => $translation], $locale, $domain); $this->assertEquals($expected, $translator->transChoice($id, $number, $parameters, $domain, $locale)); } @@ -413,9 +413,9 @@ class TranslatorTest extends TestCase { $translator = new Translator('en'); $translator->addLoader('array', new ArrayLoader()); - $translator->addResource('array', array('foo' => 'foofoo'), 'en'); + $translator->addResource('array', ['foo' => 'foofoo'], 'en'); - $translator->transChoice('foo', 1, array(), '', $locale); + $translator->transChoice('foo', 1, [], '', $locale); } /** @@ -426,118 +426,118 @@ class TranslatorTest extends TestCase { $translator = new Translator('en'); $translator->addLoader('array', new ArrayLoader()); - $translator->addResource('array', array('foo' => 'foofoo'), 'en'); + $translator->addResource('array', ['foo' => 'foofoo'], 'en'); - $translator->transChoice('foo', 1, array(), '', $locale); + $translator->transChoice('foo', 1, [], '', $locale); // no assertion. this method just asserts that no exception is thrown $this->addToAssertionCount(1); } public function getTransFileTests() { - return array( - array('csv', 'CsvFileLoader'), - array('ini', 'IniFileLoader'), - array('mo', 'MoFileLoader'), - array('po', 'PoFileLoader'), - array('php', 'PhpFileLoader'), - array('ts', 'QtFileLoader'), - array('xlf', 'XliffFileLoader'), - array('yml', 'YamlFileLoader'), - array('json', 'JsonFileLoader'), - ); + return [ + ['csv', 'CsvFileLoader'], + ['ini', 'IniFileLoader'], + ['mo', 'MoFileLoader'], + ['po', 'PoFileLoader'], + ['php', 'PhpFileLoader'], + ['ts', 'QtFileLoader'], + ['xlf', 'XliffFileLoader'], + ['yml', 'YamlFileLoader'], + ['json', 'JsonFileLoader'], + ]; } public function getTransTests() { - return array( - array('Symfony est super !', 'Symfony is great!', 'Symfony est super !', array(), 'fr', ''), - array('Symfony est awesome !', 'Symfony is %what%!', 'Symfony est %what% !', array('%what%' => 'awesome'), 'fr', ''), - array('Symfony est super !', new StringClass('Symfony is great!'), 'Symfony est super !', array(), 'fr', ''), - ); + return [ + ['Symfony est super !', 'Symfony is great!', 'Symfony est super !', [], 'fr', ''], + ['Symfony est awesome !', 'Symfony is %what%!', 'Symfony est %what% !', ['%what%' => 'awesome'], 'fr', ''], + ['Symfony est super !', new StringClass('Symfony is great!'), 'Symfony est super !', [], 'fr', ''], + ]; } public function getFlattenedTransTests() { - $messages = array( - 'symfony' => array( - 'is' => array( + $messages = [ + 'symfony' => [ + 'is' => [ 'great' => 'Symfony est super!', - ), - ), - 'foo' => array( - 'bar' => array( + ], + ], + 'foo' => [ + 'bar' => [ 'baz' => 'Foo Bar Baz', - ), + ], 'baz' => 'Foo Baz', - ), - ); + ], + ]; - return array( - array('Symfony est super!', $messages, 'symfony.is.great'), - array('Foo Bar Baz', $messages, 'foo.bar.baz'), - array('Foo Baz', $messages, 'foo.baz'), - ); + return [ + ['Symfony est super!', $messages, 'symfony.is.great'], + ['Foo Bar Baz', $messages, 'foo.bar.baz'], + ['Foo Baz', $messages, 'foo.baz'], + ]; } public function getTransChoiceTests() { - return array( - array('Il y a 0 pomme', '{0} There are no appless|{1} There is one apple|]1,Inf] There is %count% apples', '[0,1] Il y a %count% pomme|]1,Inf] Il y a %count% pommes', 0, array(), 'fr', ''), - array('Il y a 1 pomme', '{0} There are no appless|{1} There is one apple|]1,Inf] There is %count% apples', '[0,1] Il y a %count% pomme|]1,Inf] Il y a %count% pommes', 1, array(), 'fr', ''), - array('Il y a 10 pommes', '{0} There are no appless|{1} There is one apple|]1,Inf] There is %count% apples', '[0,1] Il y a %count% pomme|]1,Inf] Il y a %count% pommes', 10, array(), 'fr', ''), + return [ + ['Il y a 0 pomme', '{0} There are no appless|{1} There is one apple|]1,Inf] There is %count% apples', '[0,1] Il y a %count% pomme|]1,Inf] Il y a %count% pommes', 0, [], 'fr', ''], + ['Il y a 1 pomme', '{0} There are no appless|{1} There is one apple|]1,Inf] There is %count% apples', '[0,1] Il y a %count% pomme|]1,Inf] Il y a %count% pommes', 1, [], 'fr', ''], + ['Il y a 10 pommes', '{0} There are no appless|{1} There is one apple|]1,Inf] There is %count% apples', '[0,1] Il y a %count% pomme|]1,Inf] Il y a %count% pommes', 10, [], 'fr', ''], - array('Il y a 0 pomme', 'There is one apple|There is %count% apples', 'Il y a %count% pomme|Il y a %count% pommes', 0, array(), 'fr', ''), - array('Il y a 1 pomme', 'There is one apple|There is %count% apples', 'Il y a %count% pomme|Il y a %count% pommes', 1, array(), 'fr', ''), - array('Il y a 10 pommes', 'There is one apple|There is %count% apples', 'Il y a %count% pomme|Il y a %count% pommes', 10, array(), 'fr', ''), + ['Il y a 0 pomme', 'There is one apple|There is %count% apples', 'Il y a %count% pomme|Il y a %count% pommes', 0, [], 'fr', ''], + ['Il y a 1 pomme', 'There is one apple|There is %count% apples', 'Il y a %count% pomme|Il y a %count% pommes', 1, [], 'fr', ''], + ['Il y a 10 pommes', 'There is one apple|There is %count% apples', 'Il y a %count% pomme|Il y a %count% pommes', 10, [], 'fr', ''], - array('Il y a 0 pomme', 'one: There is one apple|more: There is %count% apples', 'one: Il y a %count% pomme|more: Il y a %count% pommes', 0, array(), 'fr', ''), - array('Il y a 1 pomme', 'one: There is one apple|more: There is %count% apples', 'one: Il y a %count% pomme|more: Il y a %count% pommes', 1, array(), 'fr', ''), - array('Il y a 10 pommes', 'one: There is one apple|more: There is %count% apples', 'one: Il y a %count% pomme|more: Il y a %count% pommes', 10, array(), 'fr', ''), + ['Il y a 0 pomme', 'one: There is one apple|more: There is %count% apples', 'one: Il y a %count% pomme|more: Il y a %count% pommes', 0, [], 'fr', ''], + ['Il y a 1 pomme', 'one: There is one apple|more: There is %count% apples', 'one: Il y a %count% pomme|more: Il y a %count% pommes', 1, [], 'fr', ''], + ['Il y a 10 pommes', 'one: There is one apple|more: There is %count% apples', 'one: Il y a %count% pomme|more: Il y a %count% pommes', 10, [], 'fr', ''], - array('Il n\'y a aucune pomme', '{0} There are no apples|one: There is one apple|more: There is %count% apples', '{0} Il n\'y a aucune pomme|one: Il y a %count% pomme|more: Il y a %count% pommes', 0, array(), 'fr', ''), - array('Il y a 1 pomme', '{0} There are no apples|one: There is one apple|more: There is %count% apples', '{0} Il n\'y a aucune pomme|one: Il y a %count% pomme|more: Il y a %count% pommes', 1, array(), 'fr', ''), - array('Il y a 10 pommes', '{0} There are no apples|one: There is one apple|more: There is %count% apples', '{0} Il n\'y a aucune pomme|one: Il y a %count% pomme|more: Il y a %count% pommes', 10, array(), 'fr', ''), + ['Il n\'y a aucune pomme', '{0} There are no apples|one: There is one apple|more: There is %count% apples', '{0} Il n\'y a aucune pomme|one: Il y a %count% pomme|more: Il y a %count% pommes', 0, [], 'fr', ''], + ['Il y a 1 pomme', '{0} There are no apples|one: There is one apple|more: There is %count% apples', '{0} Il n\'y a aucune pomme|one: Il y a %count% pomme|more: Il y a %count% pommes', 1, [], 'fr', ''], + ['Il y a 10 pommes', '{0} There are no apples|one: There is one apple|more: There is %count% apples', '{0} Il n\'y a aucune pomme|one: Il y a %count% pomme|more: Il y a %count% pommes', 10, [], 'fr', ''], - array('Il y a 0 pomme', new StringClass('{0} There are no appless|{1} There is one apple|]1,Inf] There is %count% apples'), '[0,1] Il y a %count% pomme|]1,Inf] Il y a %count% pommes', 0, array(), 'fr', ''), + ['Il y a 0 pomme', new StringClass('{0} There are no appless|{1} There is one apple|]1,Inf] There is %count% apples'), '[0,1] Il y a %count% pomme|]1,Inf] Il y a %count% pommes', 0, [], 'fr', ''], // Override %count% with a custom value - array('Il y a quelques pommes', 'one: There is one apple|more: There are %count% apples', 'one: Il y a %count% pomme|more: Il y a quelques pommes', 2, array('%count%' => 'quelques'), 'fr', ''), - ); + ['Il y a quelques pommes', 'one: There is one apple|more: There are %count% apples', 'one: Il y a %count% pomme|more: Il y a quelques pommes', 2, ['%count%' => 'quelques'], 'fr', ''], + ]; } public function getInvalidLocalesTests() { - return array( - array('fr FR'), - array('français'), - array('fr+en'), - array('utf#8'), - array('fr&en'), - array('fr~FR'), - array(' fr'), - array('fr '), - array('fr*'), - array('fr/FR'), - array('fr\\FR'), - ); + return [ + ['fr FR'], + ['français'], + ['fr+en'], + ['utf#8'], + ['fr&en'], + ['fr~FR'], + [' fr'], + ['fr '], + ['fr*'], + ['fr/FR'], + ['fr\\FR'], + ]; } public function getValidLocalesTests() { - return array( - array(''), - array(null), - array('fr'), - array('francais'), - array('FR'), - array('frFR'), - array('fr-FR'), - array('fr_FR'), - array('fr.FR'), - array('fr-FR.UTF8'), - array('sr@latin'), - ); + return [ + [''], + [null], + ['fr'], + ['francais'], + ['FR'], + ['frFR'], + ['fr-FR'], + ['fr_FR'], + ['fr.FR'], + ['fr-FR.UTF8'], + ['sr@latin'], + ]; } /** @@ -548,11 +548,11 @@ class TranslatorTest extends TestCase $translator = new Translator('en'); $translator->addLoader('array', new ArrayLoader()); - $translator->addResource('array', array('some_message' => 'Hello %name%'), 'en'); - $this->assertSame('Hello Bob', $translator->trans('some_message', array('%name%' => 'Bob'))); + $translator->addResource('array', ['some_message' => 'Hello %name%'], 'en'); + $this->assertSame('Hello Bob', $translator->trans('some_message', ['%name%' => 'Bob'])); - $translator->addResource('array', array('some_message' => 'Hi {name}'), 'en', 'messages+intl-icu'); - $this->assertSame('Hi Bob', $translator->trans('some_message', array('%name%' => 'Bob'))); + $translator->addResource('array', ['some_message' => 'Hi {name}'], 'en', 'messages+intl-icu'); + $this->assertSame('Hi Bob', $translator->trans('some_message', ['%name%' => 'Bob'])); } /** @@ -561,11 +561,11 @@ class TranslatorTest extends TestCase public function testTransChoiceFallback() { $translator = new Translator('ru'); - $translator->setFallbackLocales(array('en')); + $translator->setFallbackLocales(['en']); $translator->addLoader('array', new ArrayLoader()); - $translator->addResource('array', array('some_message2' => 'one thing|%count% things'), 'en'); + $translator->addResource('array', ['some_message2' => 'one thing|%count% things'], 'en'); - $this->assertEquals('10 things', $translator->transChoice('some_message2', 10, array('%count%' => 10))); + $this->assertEquals('10 things', $translator->transChoice('some_message2', 10, ['%count%' => 10])); } /** @@ -574,11 +574,11 @@ class TranslatorTest extends TestCase public function testTransChoiceFallbackBis() { $translator = new Translator('ru'); - $translator->setFallbackLocales(array('en_US', 'en')); + $translator->setFallbackLocales(['en_US', 'en']); $translator->addLoader('array', new ArrayLoader()); - $translator->addResource('array', array('some_message2' => 'one thing|%count% things'), 'en_US'); + $translator->addResource('array', ['some_message2' => 'one thing|%count% things'], 'en_US'); - $this->assertEquals('10 things', $translator->transChoice('some_message2', 10, array('%count%' => 10))); + $this->assertEquals('10 things', $translator->transChoice('some_message2', 10, ['%count%' => 10])); } /** @@ -587,12 +587,12 @@ class TranslatorTest extends TestCase public function testTransChoiceFallbackWithNoTranslation() { $translator = new Translator('ru'); - $translator->setFallbackLocales(array('en')); + $translator->setFallbackLocales(['en']); $translator->addLoader('array', new ArrayLoader()); // consistent behavior with Translator::trans(), which returns the string // unchanged if it can't be found - $this->assertEquals('some_message2', $translator->transChoice('some_message2', 10, array('%count%' => 10))); + $this->assertEquals('some_message2', $translator->transChoice('some_message2', 10, ['%count%' => 10])); } } diff --git a/src/Symfony/Component/Translation/Translator.php b/src/Symfony/Component/Translation/Translator.php index 7fcb77853d..8a2b2dd9d0 100644 --- a/src/Symfony/Component/Translation/Translator.php +++ b/src/Symfony/Component/Translation/Translator.php @@ -34,7 +34,7 @@ class Translator implements LegacyTranslatorInterface, TranslatorInterface, Tran /** * @var MessageCatalogueInterface[] */ - protected $catalogues = array(); + protected $catalogues = []; /** * @var string @@ -44,17 +44,17 @@ class Translator implements LegacyTranslatorInterface, TranslatorInterface, Tran /** * @var array */ - private $fallbackLocales = array(); + private $fallbackLocales = []; /** * @var LoaderInterface[] */ - private $loaders = array(); + private $loaders = []; /** * @var array */ - private $resources = array(); + private $resources = []; /** * @var MessageFormatterInterface @@ -134,10 +134,10 @@ class Translator implements LegacyTranslatorInterface, TranslatorInterface, Tran $this->assertValidLocale($locale); - $this->resources[$locale][] = array($format, $resource, $domain); + $this->resources[$locale][] = [$format, $resource, $domain]; if (\in_array($locale, $this->fallbackLocales)) { - $this->catalogues = array(); + $this->catalogues = []; } else { unset($this->catalogues[$locale]); } @@ -170,7 +170,7 @@ class Translator implements LegacyTranslatorInterface, TranslatorInterface, Tran public function setFallbackLocales(array $locales) { // needed as the fallback locales are linked to the already loaded catalogues - $this->catalogues = array(); + $this->catalogues = []; foreach ($locales as $locale) { $this->assertValidLocale($locale); @@ -194,7 +194,7 @@ class Translator implements LegacyTranslatorInterface, TranslatorInterface, Tran /** * {@inheritdoc} */ - public function trans($id, array $parameters = array(), $domain = null, $locale = null) + public function trans($id, array $parameters = [], $domain = null, $locale = null) { if (null === $domain) { $domain = 'messages'; @@ -224,7 +224,7 @@ class Translator implements LegacyTranslatorInterface, TranslatorInterface, Tran * * @deprecated since Symfony 4.2, use the trans() method instead with a %count% parameter */ - public function transChoice($id, $number, array $parameters = array(), $domain = null, $locale = null) + public function transChoice($id, $number, array $parameters = [], $domain = null, $locale = null) { @trigger_error(sprintf('The "%s()" method is deprecated since Symfony 4.2, use the trans() one instead with a "%%count%%" parameter.', __METHOD__), E_USER_DEPRECATED); @@ -249,7 +249,7 @@ class Translator implements LegacyTranslatorInterface, TranslatorInterface, Tran } if ($this->hasIntlFormatter && $catalogue->defines($id, $domain.MessageCatalogue::INTL_DOMAIN_SUFFIX)) { - return $this->formatter->formatIntl($catalogue->get($id, $domain), $locale, array('%count%' => $number) + $parameters); + return $this->formatter->formatIntl($catalogue->get($id, $domain), $locale, ['%count%' => $number] + $parameters); } return $this->formatter->choiceFormat($catalogue->get($id, $domain), $number, $locale, $parameters); @@ -433,7 +433,7 @@ EOF $parentLocales = \json_decode(\file_get_contents(__DIR__.'/Resources/data/parents.json'), true); } - $locales = array(); + $locales = []; foreach ($this->fallbackLocales as $fallback) { if ($fallback === $locale) { continue; @@ -490,7 +490,7 @@ EOF private function getAllMessages(MessageCatalogueInterface $catalogue): array { - $allMessages = array(); + $allMessages = []; foreach ($catalogue->all() as $domain => $messages) { if ($intlMessages = $catalogue->all($domain.MessageCatalogue::INTL_DOMAIN_SUFFIX)) { diff --git a/src/Symfony/Component/Translation/Util/XliffUtils.php b/src/Symfony/Component/Translation/Util/XliffUtils.php index 9f024e5985..3ace285bfa 100644 --- a/src/Symfony/Component/Translation/Util/XliffUtils.php +++ b/src/Symfony/Component/Translation/Util/XliffUtils.php @@ -77,7 +77,7 @@ class XliffUtils libxml_clear_errors(); libxml_use_internal_errors($internalErrors); - return array(); + return []; } public static function getErrorsAsString(array $xmlErrors): string @@ -143,16 +143,16 @@ class XliffUtils */ private static function getXmlErrors(bool $internalErrors): array { - $errors = array(); + $errors = []; foreach (libxml_get_errors() as $error) { - $errors[] = array( + $errors[] = [ 'level' => LIBXML_ERR_WARNING == $error->level ? 'WARNING' : 'ERROR', 'code' => $error->code, 'message' => trim($error->message), 'file' => $error->file ?: 'n/a', 'line' => $error->line, 'column' => $error->column, - ); + ]; } libxml_clear_errors(); diff --git a/src/Symfony/Component/Validator/Constraints/DivisibleBy.php b/src/Symfony/Component/Validator/Constraints/DivisibleBy.php index c438f273c0..e806a77b55 100644 --- a/src/Symfony/Component/Validator/Constraints/DivisibleBy.php +++ b/src/Symfony/Component/Validator/Constraints/DivisibleBy.php @@ -21,9 +21,9 @@ class DivisibleBy extends AbstractComparison { const NOT_DIVISIBLE_BY = '6d99d6c3-1464-4ccf-bdc7-14d083cf455c'; - protected static $errorNames = array( + protected static $errorNames = [ self::NOT_DIVISIBLE_BY => 'NOT_DIVISIBLE_BY', - ); + ]; public $message = 'This value should be a multiple of {{ compared_value }}.'; } diff --git a/src/Symfony/Component/Validator/DependencyInjection/AddValidatorInitializersPass.php b/src/Symfony/Component/Validator/DependencyInjection/AddValidatorInitializersPass.php index 4539e27bd3..dcc02ca694 100644 --- a/src/Symfony/Component/Validator/DependencyInjection/AddValidatorInitializersPass.php +++ b/src/Symfony/Component/Validator/DependencyInjection/AddValidatorInitializersPass.php @@ -40,16 +40,16 @@ class AddValidatorInitializersPass implements CompilerPassInterface return; } - $initializers = array(); + $initializers = []; foreach ($container->findTaggedServiceIds($this->initializerTag, true) as $id => $attributes) { $initializers[] = new Reference($id); } - $container->getDefinition($this->builderService)->addMethodCall('addObjectInitializers', array($initializers)); + $container->getDefinition($this->builderService)->addMethodCall('addObjectInitializers', [$initializers]); // @deprecated logic, to be removed in Symfony 5.0 $builder = $container->getDefinition($this->builderService); - $calls = array(); + $calls = []; foreach ($builder->getMethodCalls() as list($method, $arguments)) { if ('setTranslator' === $method) { @@ -70,7 +70,7 @@ class AddValidatorInitializersPass implements CompilerPassInterface } } - $calls[] = array($method, $arguments); + $calls[] = [$method, $arguments]; } $builder->setMethodCalls($calls); diff --git a/src/Symfony/Component/Validator/Tests/Constraints/BicValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/BicValidatorTest.php index 231843a792..6820f2c507 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/BicValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/BicValidatorTest.php @@ -57,14 +57,14 @@ class BicValidatorTest extends ConstraintValidatorTestCase public function getValidBics() { // http://formvalidation.io/validators/bic/ - return array( - array('ASPKAT2LXXX'), - array('ASPKAT2L'), - array('DSBACNBXSHA'), - array('UNCRIT2B912'), - array('DABADKKK'), - array('RZOOAT2L303'), - ); + return [ + ['ASPKAT2LXXX'], + ['ASPKAT2L'], + ['DSBACNBXSHA'], + ['UNCRIT2B912'], + ['DABADKKK'], + ['RZOOAT2L303'], + ]; } /** @@ -72,9 +72,9 @@ class BicValidatorTest extends ConstraintValidatorTestCase */ public function testInvalidBics($bic, $code) { - $constraint = new Bic(array( + $constraint = new Bic([ 'message' => 'myMessage', - )); + ]); $this->validator->validate($bic, $constraint); @@ -86,31 +86,31 @@ class BicValidatorTest extends ConstraintValidatorTestCase public function getInvalidBics() { - return array( - array('DEUTD', Bic::INVALID_LENGTH_ERROR), - array('ASPKAT2LXX', Bic::INVALID_LENGTH_ERROR), - array('ASPKAT2LX', Bic::INVALID_LENGTH_ERROR), - array('ASPKAT2LXXX1', Bic::INVALID_LENGTH_ERROR), - array('DABADKK', Bic::INVALID_LENGTH_ERROR), - array('1SBACNBXSHA', Bic::INVALID_BANK_CODE_ERROR), - array('RZ00AT2L303', Bic::INVALID_BANK_CODE_ERROR), - array('D2BACNBXSHA', Bic::INVALID_BANK_CODE_ERROR), - array('DS3ACNBXSHA', Bic::INVALID_BANK_CODE_ERROR), - array('DSB4CNBXSHA', Bic::INVALID_BANK_CODE_ERROR), - array('DEUT12HH', Bic::INVALID_COUNTRY_CODE_ERROR), - array('DSBAC6BXSHA', Bic::INVALID_COUNTRY_CODE_ERROR), - array('DSBA5NBXSHA', Bic::INVALID_COUNTRY_CODE_ERROR), - array('DSBAAABXSHA', Bic::INVALID_COUNTRY_CODE_ERROR), + return [ + ['DEUTD', Bic::INVALID_LENGTH_ERROR], + ['ASPKAT2LXX', Bic::INVALID_LENGTH_ERROR], + ['ASPKAT2LX', Bic::INVALID_LENGTH_ERROR], + ['ASPKAT2LXXX1', Bic::INVALID_LENGTH_ERROR], + ['DABADKK', Bic::INVALID_LENGTH_ERROR], + ['1SBACNBXSHA', Bic::INVALID_BANK_CODE_ERROR], + ['RZ00AT2L303', Bic::INVALID_BANK_CODE_ERROR], + ['D2BACNBXSHA', Bic::INVALID_BANK_CODE_ERROR], + ['DS3ACNBXSHA', Bic::INVALID_BANK_CODE_ERROR], + ['DSB4CNBXSHA', Bic::INVALID_BANK_CODE_ERROR], + ['DEUT12HH', Bic::INVALID_COUNTRY_CODE_ERROR], + ['DSBAC6BXSHA', Bic::INVALID_COUNTRY_CODE_ERROR], + ['DSBA5NBXSHA', Bic::INVALID_COUNTRY_CODE_ERROR], + ['DSBAAABXSHA', Bic::INVALID_COUNTRY_CODE_ERROR], // branch code error - array('THISSVAL1D]', Bic::INVALID_CHARACTERS_ERROR), + ['THISSVAL1D]', Bic::INVALID_CHARACTERS_ERROR], // location code error - array('DEUTDEF]', Bic::INVALID_CHARACTERS_ERROR), + ['DEUTDEF]', Bic::INVALID_CHARACTERS_ERROR], // lower case values are invalid - array('DeutAT2LXXX', Bic::INVALID_CASE_ERROR), - array('DEUTAT2lxxx', Bic::INVALID_CASE_ERROR), - ); + ['DeutAT2LXXX', Bic::INVALID_CASE_ERROR], + ['DEUTAT2lxxx', Bic::INVALID_CASE_ERROR], + ]; } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/DivisibleByValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/DivisibleByValidatorTest.php index 3c770a9f9b..e2d50574a7 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/DivisibleByValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/DivisibleByValidatorTest.php @@ -39,16 +39,16 @@ class DivisibleByValidatorTest extends AbstractComparisonValidatorTestCase */ public function provideValidComparisons() { - return array( - array(-7, 1), - array(0, 3.1415), - array(42, 42), - array(42, 21), - array(3.25, 0.25), - array('100', '10'), - array(4.1, 0.1), - array(-4.1, 0.1), - ); + return [ + [-7, 1], + [0, 3.1415], + [42, 42], + [42, 21], + [3.25, 0.25], + ['100', '10'], + [4.1, 0.1], + [-4.1, 0.1], + ]; } /** @@ -56,9 +56,9 @@ class DivisibleByValidatorTest extends AbstractComparisonValidatorTestCase */ public function provideValidComparisonsToPropertyPath() { - return array( - array(25), - ); + return [ + [25], + ]; } /** @@ -66,13 +66,13 @@ class DivisibleByValidatorTest extends AbstractComparisonValidatorTestCase */ public function provideInvalidComparisons() { - return array( - array(1, '1', 2, '2', 'integer'), - array(10, '10', 3, '3', 'integer'), - array(10, '10', 0, '0', 'integer'), - array(42, '42', INF, 'INF', 'double'), - array(4.15, '4.15', 0.1, '0.1', 'double'), - array('22', '"22"', '10', '"10"', 'string'), - ); + return [ + [1, '1', 2, '2', 'integer'], + [10, '10', 3, '3', 'integer'], + [10, '10', 0, '0', 'integer'], + [42, '42', INF, 'INF', 'double'], + [4.15, '4.15', 0.1, '0.1', 'double'], + ['22', '"22"', '10', '"10"', 'string'], + ]; } } diff --git a/src/Symfony/Component/Validator/Tests/DependencyInjection/AddValidatorInitializersPassTest.php b/src/Symfony/Component/Validator/Tests/DependencyInjection/AddValidatorInitializersPassTest.php index 5cc3b0c921..42d7553e13 100644 --- a/src/Symfony/Component/Validator/Tests/DependencyInjection/AddValidatorInitializersPassTest.php +++ b/src/Symfony/Component/Validator/Tests/DependencyInjection/AddValidatorInitializersPassTest.php @@ -59,7 +59,7 @@ class AddValidatorInitializersPassTest extends TestCase $container = new ContainerBuilder(); $container ->register('validator.builder') - ->addMethodCall('setTranslator', array(new Reference('translator'))) + ->addMethodCall('setTranslator', [new Reference('translator')]) ; $container->register('translator', TestTranslator::class); @@ -67,7 +67,7 @@ class AddValidatorInitializersPassTest extends TestCase (new AddValidatorInitializersPass())->process($container); $this->assertEquals( - array(array('setTranslator', array((new Definition(LegacyTranslatorProxy::class))->addArgument(new Reference('translator'))))), + [['setTranslator', [(new Definition(LegacyTranslatorProxy::class))->addArgument(new Reference('translator'))]]], $container->getDefinition('validator.builder')->removeMethodCall('addObjectInitializers')->getMethodCalls() ); } diff --git a/src/Symfony/Component/Validator/Util/LegacyTranslatorProxy.php b/src/Symfony/Component/Validator/Util/LegacyTranslatorProxy.php index f87c1fbbb3..51218e7c57 100644 --- a/src/Symfony/Component/Validator/Util/LegacyTranslatorProxy.php +++ b/src/Symfony/Component/Validator/Util/LegacyTranslatorProxy.php @@ -54,7 +54,7 @@ class LegacyTranslatorProxy implements LegacyTranslatorInterface, TranslatorInte /** * {@inheritdoc} */ - public function trans($id, array $parameters = array(), $domain = null, $locale = null) + public function trans($id, array $parameters = [], $domain = null, $locale = null) { return $this->translator->trans($id, $parameters, $domain, $locale); } @@ -62,8 +62,8 @@ class LegacyTranslatorProxy implements LegacyTranslatorInterface, TranslatorInte /** * {@inheritdoc} */ - public function transChoice($id, $number, array $parameters = array(), $domain = null, $locale = null) + public function transChoice($id, $number, array $parameters = [], $domain = null, $locale = null) { - return $this->translator->trans($id, array('%count%' => $number) + $parameters, $domain, $locale); + return $this->translator->trans($id, ['%count%' => $number] + $parameters, $domain, $locale); } } diff --git a/src/Symfony/Component/Validator/ValidatorBuilder.php b/src/Symfony/Component/Validator/ValidatorBuilder.php index 8e4de01267..fb64332712 100644 --- a/src/Symfony/Component/Validator/ValidatorBuilder.php +++ b/src/Symfony/Component/Validator/ValidatorBuilder.php @@ -43,11 +43,11 @@ use Symfony\Contracts\Translation\TranslatorTrait; */ class ValidatorBuilder implements ValidatorBuilderInterface { - private $initializers = array(); - private $loaders = array(); - private $xmlMappings = array(); - private $yamlMappings = array(); - private $methodMappings = array(); + private $initializers = []; + private $loaders = []; + private $xmlMappings = []; + private $yamlMappings = []; + private $methodMappings = []; /** * @var Reader|null @@ -288,7 +288,7 @@ class ValidatorBuilder implements ValidatorBuilderInterface */ public function getLoaders() { - $loaders = array(); + $loaders = []; foreach ($this->xmlMappings as $xmlMapping) { $loaders[] = new XmlFileLoader($xmlMapping); diff --git a/src/Symfony/Component/Validator/Violation/ConstraintViolationBuilder.php b/src/Symfony/Component/Validator/Violation/ConstraintViolationBuilder.php index abca36a536..c5b1d0b83f 100644 --- a/src/Symfony/Component/Validator/Violation/ConstraintViolationBuilder.php +++ b/src/Symfony/Component/Validator/Violation/ConstraintViolationBuilder.php @@ -157,7 +157,7 @@ class ConstraintViolationBuilder implements ConstraintViolationBuilderInterface } elseif ($this->translator instanceof TranslatorInterface) { $translatedMessage = $this->translator->trans( $this->message, - array('%count%' => $this->plural) + $this->parameters, + ['%count%' => $this->plural] + $this->parameters, $this->translationDomain ); } else { diff --git a/src/Symfony/Component/VarDumper/Caster/ClassStub.php b/src/Symfony/Component/VarDumper/Caster/ClassStub.php index d067d83168..b655ae960e 100644 --- a/src/Symfony/Component/VarDumper/Caster/ClassStub.php +++ b/src/Symfony/Component/VarDumper/Caster/ClassStub.php @@ -62,7 +62,7 @@ class ClassStub extends ConstStub } if (null !== $callable && $r instanceof \ReflectionFunctionAbstract) { - $s = ReflectionCaster::castFunctionAbstract($r, array(), new Stub(), true); + $s = ReflectionCaster::castFunctionAbstract($r, [], new Stub(), true); $s = ReflectionCaster::getSignature($s); if ('()' === substr($identifier, -2)) { diff --git a/src/Symfony/Component/VarDumper/Caster/IntlCaster.php b/src/Symfony/Component/VarDumper/Caster/IntlCaster.php index a69813079c..7794d6cbcc 100644 --- a/src/Symfony/Component/VarDumper/Caster/IntlCaster.php +++ b/src/Symfony/Component/VarDumper/Caster/IntlCaster.php @@ -21,20 +21,20 @@ class IntlCaster { public static function castMessageFormatter(\MessageFormatter $c, array $a, Stub $stub, $isNested) { - $a += array( + $a += [ Caster::PREFIX_VIRTUAL.'locale' => $c->getLocale(), Caster::PREFIX_VIRTUAL.'pattern' => $c->getPattern(), - ); + ]; return self::castError($c, $a); } public static function castNumberFormatter(\NumberFormatter $c, array $a, Stub $stub, $isNested, $filter = 0) { - $a += array( + $a += [ Caster::PREFIX_VIRTUAL.'locale' => $c->getLocale(), Caster::PREFIX_VIRTUAL.'pattern' => $c->getPattern(), - ); + ]; if ($filter & Caster::EXCLUDE_VERBOSE) { $stub->cut += 3; @@ -42,9 +42,9 @@ class IntlCaster return self::castError($c, $a); } - $a += array( + $a += [ Caster::PREFIX_VIRTUAL.'attributes' => new EnumStub( - array( + [ 'PARSE_INT_ONLY' => $c->getAttribute(\NumberFormatter::PARSE_INT_ONLY), 'GROUPING_USED' => $c->getAttribute(\NumberFormatter::GROUPING_USED), 'DECIMAL_ALWAYS_SHOWN' => $c->getAttribute(\NumberFormatter::DECIMAL_ALWAYS_SHOWN), @@ -65,10 +65,10 @@ class IntlCaster 'MIN_SIGNIFICANT_DIGITS' => $c->getAttribute(\NumberFormatter::MIN_SIGNIFICANT_DIGITS), 'MAX_SIGNIFICANT_DIGITS' => $c->getAttribute(\NumberFormatter::MAX_SIGNIFICANT_DIGITS), 'LENIENT_PARSE' => $c->getAttribute(\NumberFormatter::LENIENT_PARSE), - ) + ] ), Caster::PREFIX_VIRTUAL.'text_attributes' => new EnumStub( - array( + [ 'POSITIVE_PREFIX' => $c->getTextAttribute(\NumberFormatter::POSITIVE_PREFIX), 'POSITIVE_SUFFIX' => $c->getTextAttribute(\NumberFormatter::POSITIVE_SUFFIX), 'NEGATIVE_PREFIX' => $c->getTextAttribute(\NumberFormatter::NEGATIVE_PREFIX), @@ -77,10 +77,10 @@ class IntlCaster 'CURRENCY_CODE' => $c->getTextAttribute(\NumberFormatter::CURRENCY_CODE), 'DEFAULT_RULESET' => $c->getTextAttribute(\NumberFormatter::DEFAULT_RULESET), 'PUBLIC_RULESETS' => $c->getTextAttribute(\NumberFormatter::PUBLIC_RULESETS), - ) + ] ), Caster::PREFIX_VIRTUAL.'symbols' => new EnumStub( - array( + [ 'DECIMAL_SEPARATOR_SYMBOL' => $c->getSymbol(\NumberFormatter::DECIMAL_SEPARATOR_SYMBOL), 'GROUPING_SEPARATOR_SYMBOL' => $c->getSymbol(\NumberFormatter::GROUPING_SEPARATOR_SYMBOL), 'PATTERN_SEPARATOR_SYMBOL' => $c->getSymbol(\NumberFormatter::PATTERN_SEPARATOR_SYMBOL), @@ -99,25 +99,25 @@ class IntlCaster 'NAN_SYMBOL' => $c->getSymbol(\NumberFormatter::NAN_SYMBOL), 'SIGNIFICANT_DIGIT_SYMBOL' => $c->getSymbol(\NumberFormatter::SIGNIFICANT_DIGIT_SYMBOL), 'MONETARY_GROUPING_SEPARATOR_SYMBOL' => $c->getSymbol(\NumberFormatter::MONETARY_GROUPING_SEPARATOR_SYMBOL), - ) + ] ), - ); + ]; return self::castError($c, $a); } public static function castIntlTimeZone(\IntlTimeZone $c, array $a, Stub $stub, $isNested) { - $a += array( + $a += [ Caster::PREFIX_VIRTUAL.'display_name' => $c->getDisplayName(), Caster::PREFIX_VIRTUAL.'id' => $c->getID(), Caster::PREFIX_VIRTUAL.'raw_offset' => $c->getRawOffset(), - ); + ]; if ($c->useDaylightTime()) { - $a += array( + $a += [ Caster::PREFIX_VIRTUAL.'dst_savings' => $c->getDSTSavings(), - ); + ]; } return self::castError($c, $a); @@ -125,7 +125,7 @@ class IntlCaster public static function castIntlCalendar(\IntlCalendar $c, array $a, Stub $stub, $isNested, $filter = 0) { - $a += array( + $a += [ Caster::PREFIX_VIRTUAL.'type' => $c->getType(), Caster::PREFIX_VIRTUAL.'first_day_of_week' => $c->getFirstDayOfWeek(), Caster::PREFIX_VIRTUAL.'minimal_days_in_first_week' => $c->getMinimalDaysInFirstWeek(), @@ -136,14 +136,14 @@ class IntlCaster Caster::PREFIX_VIRTUAL.'in_daylight_time' => $c->inDaylightTime(), Caster::PREFIX_VIRTUAL.'is_lenient' => $c->isLenient(), Caster::PREFIX_VIRTUAL.'time_zone' => ($filter & Caster::EXCLUDE_VERBOSE) ? new CutStub($c->getTimeZone()) : $c->getTimeZone(), - ); + ]; return self::castError($c, $a); } public static function castIntlDateFormatter(\IntlDateFormatter $c, array $a, Stub $stub, $isNested, $filter = 0) { - $a += array( + $a += [ Caster::PREFIX_VIRTUAL.'locale' => $c->getLocale(), Caster::PREFIX_VIRTUAL.'pattern' => $c->getPattern(), Caster::PREFIX_VIRTUAL.'calendar' => $c->getCalendar(), @@ -152,7 +152,7 @@ class IntlCaster Caster::PREFIX_VIRTUAL.'date_type' => $c->getDateType(), Caster::PREFIX_VIRTUAL.'calendar_object' => ($filter & Caster::EXCLUDE_VERBOSE) ? new CutStub($c->getCalendarObject()) : $c->getCalendarObject(), Caster::PREFIX_VIRTUAL.'time_zone' => ($filter & Caster::EXCLUDE_VERBOSE) ? new CutStub($c->getTimeZone()) : $c->getTimeZone(), - ); + ]; return self::castError($c, $a); } @@ -160,10 +160,10 @@ class IntlCaster private static function castError($c, array $a): array { if ($errorCode = $c->getErrorCode()) { - $a += array( + $a += [ Caster::PREFIX_VIRTUAL.'error_code' => $errorCode, Caster::PREFIX_VIRTUAL.'error_message' => $c->getErrorMessage(), - ); + ]; } return $a; diff --git a/src/Symfony/Component/VarDumper/Caster/MemcachedCaster.php b/src/Symfony/Component/VarDumper/Caster/MemcachedCaster.php index 99a33bca63..a32654683d 100644 --- a/src/Symfony/Component/VarDumper/Caster/MemcachedCaster.php +++ b/src/Symfony/Component/VarDumper/Caster/MemcachedCaster.php @@ -23,12 +23,12 @@ class MemcachedCaster public static function castMemcached(\Memcached $c, array $a, Stub $stub, $isNested) { - $a += array( + $a += [ Caster::PREFIX_VIRTUAL.'servers' => $c->getServerList(), Caster::PREFIX_VIRTUAL.'options' => new EnumStub( self::getNonDefaultOptions($c) ), - ); + ]; return $a; } @@ -38,7 +38,7 @@ class MemcachedCaster self::$defaultOptions = self::$defaultOptions ?? self::discoverDefaultOptions(); self::$optionConstants = self::$optionConstants ?? self::getOptionConstants(); - $nonDefaultOptions = array(); + $nonDefaultOptions = []; foreach (self::$optionConstants as $constantKey => $value) { if (self::$defaultOptions[$constantKey] !== $option = $c->getOption($value)) { $nonDefaultOptions[$constantKey] = $option; @@ -53,7 +53,7 @@ class MemcachedCaster $defaultMemcached = new \Memcached(); $defaultMemcached->addServer('127.0.0.1', 11211); - $defaultOptions = array(); + $defaultOptions = []; self::$optionConstants = self::$optionConstants ?? self::getOptionConstants(); foreach (self::$optionConstants as $constantKey => $value) { @@ -67,7 +67,7 @@ class MemcachedCaster { $reflectedMemcached = new \ReflectionClass(\Memcached::class); - $optionConstants = array(); + $optionConstants = []; foreach ($reflectedMemcached->getConstants() as $constantKey => $value) { if (0 === strpos($constantKey, 'OPT_')) { $optionConstants[$constantKey] = $value; diff --git a/src/Symfony/Component/VarDumper/Caster/RedisCaster.php b/src/Symfony/Component/VarDumper/Caster/RedisCaster.php index 0fcd9d96fd..558a0804d5 100644 --- a/src/Symfony/Component/VarDumper/Caster/RedisCaster.php +++ b/src/Symfony/Component/VarDumper/Caster/RedisCaster.php @@ -20,43 +20,43 @@ use Symfony\Component\VarDumper\Cloner\Stub; */ class RedisCaster { - private static $serializer = array( + private static $serializer = [ \Redis::SERIALIZER_NONE => 'NONE', \Redis::SERIALIZER_PHP => 'PHP', 2 => 'IGBINARY', // Optional Redis::SERIALIZER_IGBINARY - ); + ]; - private static $mode = array( + private static $mode = [ \Redis::ATOMIC => 'ATOMIC', \Redis::MULTI => 'MULTI', \Redis::PIPELINE => 'PIPELINE', - ); + ]; - private static $compression = array( + private static $compression = [ 0 => 'NONE', // Redis::COMPRESSION_NONE 1 => 'LZF', // Redis::COMPRESSION_LZF - ); + ]; - private static $failover = array( + private static $failover = [ \RedisCluster::FAILOVER_NONE => 'NONE', \RedisCluster::FAILOVER_ERROR => 'ERROR', \RedisCluster::FAILOVER_DISTRIBUTE => 'DISTRIBUTE', \RedisCluster::FAILOVER_DISTRIBUTE_SLAVES => 'DISTRIBUTE_SLAVES', - ); + ]; public static function castRedis(\Redis $c, array $a, Stub $stub, $isNested) { $prefix = Caster::PREFIX_VIRTUAL; if (!$connected = $c->isConnected()) { - return $a + array( + return $a + [ $prefix.'isConnected' => $connected, - ); + ]; } $mode = $c->getMode(); - return $a + array( + return $a + [ $prefix.'isConnected' => $connected, $prefix.'host' => $c->getHost(), $prefix.'port' => $c->getPort(), @@ -67,19 +67,19 @@ class RedisCaster $prefix.'lastError' => $c->getLastError(), $prefix.'persistentId' => $c->getPersistentID(), $prefix.'options' => self::getRedisOptions($c), - ); + ]; } public static function castRedisArray(\RedisArray $c, array $a, Stub $stub, $isNested) { $prefix = Caster::PREFIX_VIRTUAL; - return $a + array( + return $a + [ $prefix.'hosts' => $c->_hosts(), $prefix.'function' => ClassStub::wrapCallable($c->_function()), $prefix.'lastError' => $c->getLastError(), $prefix.'options' => self::getRedisOptions($c), - ); + ]; } public static function castRedisCluster(\RedisCluster $c, array $a, Stub $stub, $isNested) @@ -87,15 +87,15 @@ class RedisCaster $prefix = Caster::PREFIX_VIRTUAL; $failover = $c->getOption(\RedisCluster::OPT_SLAVE_FAILOVER); - $a += array( + $a += [ $prefix.'_masters' => $c->_masters(), $prefix.'_redir' => $c->_redir(), $prefix.'mode' => new ConstStub($c->getMode() ? 'MULTI' : 'ATOMIC', $c->getMode()), $prefix.'lastError' => $c->getLastError(), - $prefix.'options' => self::getRedisOptions($c, array( + $prefix.'options' => self::getRedisOptions($c, [ 'SLAVE_FAILOVER' => isset(self::$failover[$failover]) ? new ConstStub(self::$failover[$failover], $failover) : $failover, - )), - ); + ]), + ]; return $a; } @@ -103,7 +103,7 @@ class RedisCaster /** * @param \Redis|\RedisArray|\RedisCluster $redis */ - private static function getRedisOptions($redis, array $options = array()): EnumStub + private static function getRedisOptions($redis, array $options = []): EnumStub { $serializer = $redis->getOption(\Redis::OPT_SERIALIZER); if (\is_array($serializer)) { @@ -136,14 +136,14 @@ class RedisCaster $retry = new ConstStub($retry ? 'RETRY' : 'NORETRY', $retry); } - $options += array( + $options += [ 'TCP_KEEPALIVE' => \defined('Redis::OPT_TCP_KEEPALIVE') ? $redis->getOption(\Redis::OPT_TCP_KEEPALIVE) : 0, 'READ_TIMEOUT' => $redis->getOption(\Redis::OPT_READ_TIMEOUT), 'COMPRESSION' => $compression, 'SERIALIZER' => $serializer, 'PREFIX' => $redis->getOption(\Redis::OPT_PREFIX), 'SCAN' => $retry, - ); + ]; return new EnumStub($options); } diff --git a/src/Symfony/Component/VarDumper/Caster/ReflectionCaster.php b/src/Symfony/Component/VarDumper/Caster/ReflectionCaster.php index ff19be7096..1ecfa2d2d1 100644 --- a/src/Symfony/Component/VarDumper/Caster/ReflectionCaster.php +++ b/src/Symfony/Component/VarDumper/Caster/ReflectionCaster.php @@ -49,7 +49,7 @@ class ReflectionCaster if ($filter & Caster::EXCLUDE_VERBOSE) { $stub->cut += ($c->getFileName() ? 2 : 0) + \count($a); - return array(); + return []; } if (isset($a[$prefix.'parameters'])) { diff --git a/src/Symfony/Component/VarDumper/Cloner/AbstractCloner.php b/src/Symfony/Component/VarDumper/Cloner/AbstractCloner.php index 9c8ec92bea..bf2e679cef 100644 --- a/src/Symfony/Component/VarDumper/Cloner/AbstractCloner.php +++ b/src/Symfony/Component/VarDumper/Cloner/AbstractCloner.php @@ -21,133 +21,133 @@ use Symfony\Component\VarDumper\Exception\ThrowingCasterException; */ abstract class AbstractCloner implements ClonerInterface { - public static $defaultCasters = array( - '__PHP_Incomplete_Class' => array('Symfony\Component\VarDumper\Caster\Caster', 'castPhpIncompleteClass'), + public static $defaultCasters = [ + '__PHP_Incomplete_Class' => ['Symfony\Component\VarDumper\Caster\Caster', 'castPhpIncompleteClass'], - 'Symfony\Component\VarDumper\Caster\CutStub' => array('Symfony\Component\VarDumper\Caster\StubCaster', 'castStub'), - 'Symfony\Component\VarDumper\Caster\CutArrayStub' => array('Symfony\Component\VarDumper\Caster\StubCaster', 'castCutArray'), - 'Symfony\Component\VarDumper\Caster\ConstStub' => array('Symfony\Component\VarDumper\Caster\StubCaster', 'castStub'), - 'Symfony\Component\VarDumper\Caster\EnumStub' => array('Symfony\Component\VarDumper\Caster\StubCaster', 'castEnum'), + 'Symfony\Component\VarDumper\Caster\CutStub' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'castStub'], + 'Symfony\Component\VarDumper\Caster\CutArrayStub' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'castCutArray'], + 'Symfony\Component\VarDumper\Caster\ConstStub' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'castStub'], + 'Symfony\Component\VarDumper\Caster\EnumStub' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'castEnum'], - 'Closure' => array('Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castClosure'), - 'Generator' => array('Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castGenerator'), - 'ReflectionType' => array('Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castType'), - 'ReflectionGenerator' => array('Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castReflectionGenerator'), - 'ReflectionClass' => array('Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castClass'), - 'ReflectionFunctionAbstract' => array('Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castFunctionAbstract'), - 'ReflectionMethod' => array('Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castMethod'), - 'ReflectionParameter' => array('Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castParameter'), - 'ReflectionProperty' => array('Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castProperty'), - 'ReflectionExtension' => array('Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castExtension'), - 'ReflectionZendExtension' => array('Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castZendExtension'), + 'Closure' => ['Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castClosure'], + 'Generator' => ['Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castGenerator'], + 'ReflectionType' => ['Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castType'], + 'ReflectionGenerator' => ['Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castReflectionGenerator'], + 'ReflectionClass' => ['Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castClass'], + 'ReflectionFunctionAbstract' => ['Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castFunctionAbstract'], + 'ReflectionMethod' => ['Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castMethod'], + 'ReflectionParameter' => ['Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castParameter'], + 'ReflectionProperty' => ['Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castProperty'], + 'ReflectionExtension' => ['Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castExtension'], + 'ReflectionZendExtension' => ['Symfony\Component\VarDumper\Caster\ReflectionCaster', 'castZendExtension'], - 'Doctrine\Common\Persistence\ObjectManager' => array('Symfony\Component\VarDumper\Caster\StubCaster', 'cutInternals'), - 'Doctrine\Common\Proxy\Proxy' => array('Symfony\Component\VarDumper\Caster\DoctrineCaster', 'castCommonProxy'), - 'Doctrine\ORM\Proxy\Proxy' => array('Symfony\Component\VarDumper\Caster\DoctrineCaster', 'castOrmProxy'), - 'Doctrine\ORM\PersistentCollection' => array('Symfony\Component\VarDumper\Caster\DoctrineCaster', 'castPersistentCollection'), + 'Doctrine\Common\Persistence\ObjectManager' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'cutInternals'], + 'Doctrine\Common\Proxy\Proxy' => ['Symfony\Component\VarDumper\Caster\DoctrineCaster', 'castCommonProxy'], + 'Doctrine\ORM\Proxy\Proxy' => ['Symfony\Component\VarDumper\Caster\DoctrineCaster', 'castOrmProxy'], + 'Doctrine\ORM\PersistentCollection' => ['Symfony\Component\VarDumper\Caster\DoctrineCaster', 'castPersistentCollection'], - 'DOMException' => array('Symfony\Component\VarDumper\Caster\DOMCaster', 'castException'), - 'DOMStringList' => array('Symfony\Component\VarDumper\Caster\DOMCaster', 'castLength'), - 'DOMNameList' => array('Symfony\Component\VarDumper\Caster\DOMCaster', 'castLength'), - 'DOMImplementation' => array('Symfony\Component\VarDumper\Caster\DOMCaster', 'castImplementation'), - 'DOMImplementationList' => array('Symfony\Component\VarDumper\Caster\DOMCaster', 'castLength'), - 'DOMNode' => array('Symfony\Component\VarDumper\Caster\DOMCaster', 'castNode'), - 'DOMNameSpaceNode' => array('Symfony\Component\VarDumper\Caster\DOMCaster', 'castNameSpaceNode'), - 'DOMDocument' => array('Symfony\Component\VarDumper\Caster\DOMCaster', 'castDocument'), - 'DOMNodeList' => array('Symfony\Component\VarDumper\Caster\DOMCaster', 'castLength'), - 'DOMNamedNodeMap' => array('Symfony\Component\VarDumper\Caster\DOMCaster', 'castLength'), - 'DOMCharacterData' => array('Symfony\Component\VarDumper\Caster\DOMCaster', 'castCharacterData'), - 'DOMAttr' => array('Symfony\Component\VarDumper\Caster\DOMCaster', 'castAttr'), - 'DOMElement' => array('Symfony\Component\VarDumper\Caster\DOMCaster', 'castElement'), - 'DOMText' => array('Symfony\Component\VarDumper\Caster\DOMCaster', 'castText'), - 'DOMTypeinfo' => array('Symfony\Component\VarDumper\Caster\DOMCaster', 'castTypeinfo'), - 'DOMDomError' => array('Symfony\Component\VarDumper\Caster\DOMCaster', 'castDomError'), - 'DOMLocator' => array('Symfony\Component\VarDumper\Caster\DOMCaster', 'castLocator'), - 'DOMDocumentType' => array('Symfony\Component\VarDumper\Caster\DOMCaster', 'castDocumentType'), - 'DOMNotation' => array('Symfony\Component\VarDumper\Caster\DOMCaster', 'castNotation'), - 'DOMEntity' => array('Symfony\Component\VarDumper\Caster\DOMCaster', 'castEntity'), - 'DOMProcessingInstruction' => array('Symfony\Component\VarDumper\Caster\DOMCaster', 'castProcessingInstruction'), - 'DOMXPath' => array('Symfony\Component\VarDumper\Caster\DOMCaster', 'castXPath'), + 'DOMException' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castException'], + 'DOMStringList' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castLength'], + 'DOMNameList' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castLength'], + 'DOMImplementation' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castImplementation'], + 'DOMImplementationList' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castLength'], + 'DOMNode' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castNode'], + 'DOMNameSpaceNode' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castNameSpaceNode'], + 'DOMDocument' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castDocument'], + 'DOMNodeList' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castLength'], + 'DOMNamedNodeMap' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castLength'], + 'DOMCharacterData' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castCharacterData'], + 'DOMAttr' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castAttr'], + 'DOMElement' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castElement'], + 'DOMText' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castText'], + 'DOMTypeinfo' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castTypeinfo'], + 'DOMDomError' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castDomError'], + 'DOMLocator' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castLocator'], + 'DOMDocumentType' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castDocumentType'], + 'DOMNotation' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castNotation'], + 'DOMEntity' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castEntity'], + 'DOMProcessingInstruction' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castProcessingInstruction'], + 'DOMXPath' => ['Symfony\Component\VarDumper\Caster\DOMCaster', 'castXPath'], - 'XmlReader' => array('Symfony\Component\VarDumper\Caster\XmlReaderCaster', 'castXmlReader'), + 'XmlReader' => ['Symfony\Component\VarDumper\Caster\XmlReaderCaster', 'castXmlReader'], - 'ErrorException' => array('Symfony\Component\VarDumper\Caster\ExceptionCaster', 'castErrorException'), - 'Exception' => array('Symfony\Component\VarDumper\Caster\ExceptionCaster', 'castException'), - 'Error' => array('Symfony\Component\VarDumper\Caster\ExceptionCaster', 'castError'), - 'Symfony\Component\DependencyInjection\ContainerInterface' => array('Symfony\Component\VarDumper\Caster\StubCaster', 'cutInternals'), - 'Symfony\Component\HttpFoundation\Request' => array('Symfony\Component\VarDumper\Caster\SymfonyCaster', 'castRequest'), - 'Symfony\Component\VarDumper\Exception\ThrowingCasterException' => array('Symfony\Component\VarDumper\Caster\ExceptionCaster', 'castThrowingCasterException'), - 'Symfony\Component\VarDumper\Caster\TraceStub' => array('Symfony\Component\VarDumper\Caster\ExceptionCaster', 'castTraceStub'), - 'Symfony\Component\VarDumper\Caster\FrameStub' => array('Symfony\Component\VarDumper\Caster\ExceptionCaster', 'castFrameStub'), - 'Symfony\Component\Debug\Exception\SilencedErrorContext' => array('Symfony\Component\VarDumper\Caster\ExceptionCaster', 'castSilencedErrorContext'), + 'ErrorException' => ['Symfony\Component\VarDumper\Caster\ExceptionCaster', 'castErrorException'], + 'Exception' => ['Symfony\Component\VarDumper\Caster\ExceptionCaster', 'castException'], + 'Error' => ['Symfony\Component\VarDumper\Caster\ExceptionCaster', 'castError'], + 'Symfony\Component\DependencyInjection\ContainerInterface' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'cutInternals'], + 'Symfony\Component\HttpFoundation\Request' => ['Symfony\Component\VarDumper\Caster\SymfonyCaster', 'castRequest'], + 'Symfony\Component\VarDumper\Exception\ThrowingCasterException' => ['Symfony\Component\VarDumper\Caster\ExceptionCaster', 'castThrowingCasterException'], + 'Symfony\Component\VarDumper\Caster\TraceStub' => ['Symfony\Component\VarDumper\Caster\ExceptionCaster', 'castTraceStub'], + 'Symfony\Component\VarDumper\Caster\FrameStub' => ['Symfony\Component\VarDumper\Caster\ExceptionCaster', 'castFrameStub'], + 'Symfony\Component\Debug\Exception\SilencedErrorContext' => ['Symfony\Component\VarDumper\Caster\ExceptionCaster', 'castSilencedErrorContext'], - 'ProxyManager\Proxy\ProxyInterface' => array('Symfony\Component\VarDumper\Caster\ProxyManagerCaster', 'castProxy'), - 'PHPUnit_Framework_MockObject_MockObject' => array('Symfony\Component\VarDumper\Caster\StubCaster', 'cutInternals'), - 'Prophecy\Prophecy\ProphecySubjectInterface' => array('Symfony\Component\VarDumper\Caster\StubCaster', 'cutInternals'), - 'Mockery\MockInterface' => array('Symfony\Component\VarDumper\Caster\StubCaster', 'cutInternals'), + 'ProxyManager\Proxy\ProxyInterface' => ['Symfony\Component\VarDumper\Caster\ProxyManagerCaster', 'castProxy'], + 'PHPUnit_Framework_MockObject_MockObject' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'cutInternals'], + 'Prophecy\Prophecy\ProphecySubjectInterface' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'cutInternals'], + 'Mockery\MockInterface' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'cutInternals'], - 'PDO' => array('Symfony\Component\VarDumper\Caster\PdoCaster', 'castPdo'), - 'PDOStatement' => array('Symfony\Component\VarDumper\Caster\PdoCaster', 'castPdoStatement'), + 'PDO' => ['Symfony\Component\VarDumper\Caster\PdoCaster', 'castPdo'], + 'PDOStatement' => ['Symfony\Component\VarDumper\Caster\PdoCaster', 'castPdoStatement'], - 'AMQPConnection' => array('Symfony\Component\VarDumper\Caster\AmqpCaster', 'castConnection'), - 'AMQPChannel' => array('Symfony\Component\VarDumper\Caster\AmqpCaster', 'castChannel'), - 'AMQPQueue' => array('Symfony\Component\VarDumper\Caster\AmqpCaster', 'castQueue'), - 'AMQPExchange' => array('Symfony\Component\VarDumper\Caster\AmqpCaster', 'castExchange'), - 'AMQPEnvelope' => array('Symfony\Component\VarDumper\Caster\AmqpCaster', 'castEnvelope'), + 'AMQPConnection' => ['Symfony\Component\VarDumper\Caster\AmqpCaster', 'castConnection'], + 'AMQPChannel' => ['Symfony\Component\VarDumper\Caster\AmqpCaster', 'castChannel'], + 'AMQPQueue' => ['Symfony\Component\VarDumper\Caster\AmqpCaster', 'castQueue'], + 'AMQPExchange' => ['Symfony\Component\VarDumper\Caster\AmqpCaster', 'castExchange'], + 'AMQPEnvelope' => ['Symfony\Component\VarDumper\Caster\AmqpCaster', 'castEnvelope'], - 'ArrayObject' => array('Symfony\Component\VarDumper\Caster\SplCaster', 'castArrayObject'), - 'ArrayIterator' => array('Symfony\Component\VarDumper\Caster\SplCaster', 'castArrayIterator'), - 'SplDoublyLinkedList' => array('Symfony\Component\VarDumper\Caster\SplCaster', 'castDoublyLinkedList'), - 'SplFileInfo' => array('Symfony\Component\VarDumper\Caster\SplCaster', 'castFileInfo'), - 'SplFileObject' => array('Symfony\Component\VarDumper\Caster\SplCaster', 'castFileObject'), - 'SplFixedArray' => array('Symfony\Component\VarDumper\Caster\SplCaster', 'castFixedArray'), - 'SplHeap' => array('Symfony\Component\VarDumper\Caster\SplCaster', 'castHeap'), - 'SplObjectStorage' => array('Symfony\Component\VarDumper\Caster\SplCaster', 'castObjectStorage'), - 'SplPriorityQueue' => array('Symfony\Component\VarDumper\Caster\SplCaster', 'castHeap'), - 'OuterIterator' => array('Symfony\Component\VarDumper\Caster\SplCaster', 'castOuterIterator'), + 'ArrayObject' => ['Symfony\Component\VarDumper\Caster\SplCaster', 'castArrayObject'], + 'ArrayIterator' => ['Symfony\Component\VarDumper\Caster\SplCaster', 'castArrayIterator'], + 'SplDoublyLinkedList' => ['Symfony\Component\VarDumper\Caster\SplCaster', 'castDoublyLinkedList'], + 'SplFileInfo' => ['Symfony\Component\VarDumper\Caster\SplCaster', 'castFileInfo'], + 'SplFileObject' => ['Symfony\Component\VarDumper\Caster\SplCaster', 'castFileObject'], + 'SplFixedArray' => ['Symfony\Component\VarDumper\Caster\SplCaster', 'castFixedArray'], + 'SplHeap' => ['Symfony\Component\VarDumper\Caster\SplCaster', 'castHeap'], + 'SplObjectStorage' => ['Symfony\Component\VarDumper\Caster\SplCaster', 'castObjectStorage'], + 'SplPriorityQueue' => ['Symfony\Component\VarDumper\Caster\SplCaster', 'castHeap'], + 'OuterIterator' => ['Symfony\Component\VarDumper\Caster\SplCaster', 'castOuterIterator'], - 'Redis' => array('Symfony\Component\VarDumper\Caster\RedisCaster', 'castRedis'), - 'RedisArray' => array('Symfony\Component\VarDumper\Caster\RedisCaster', 'castRedisArray'), - 'RedisCluster' => array('Symfony\Component\VarDumper\Caster\RedisCaster', 'castRedisCluster'), + 'Redis' => ['Symfony\Component\VarDumper\Caster\RedisCaster', 'castRedis'], + 'RedisArray' => ['Symfony\Component\VarDumper\Caster\RedisCaster', 'castRedisArray'], + 'RedisCluster' => ['Symfony\Component\VarDumper\Caster\RedisCaster', 'castRedisCluster'], - 'DateTimeInterface' => array('Symfony\Component\VarDumper\Caster\DateCaster', 'castDateTime'), - 'DateInterval' => array('Symfony\Component\VarDumper\Caster\DateCaster', 'castInterval'), - 'DateTimeZone' => array('Symfony\Component\VarDumper\Caster\DateCaster', 'castTimeZone'), - 'DatePeriod' => array('Symfony\Component\VarDumper\Caster\DateCaster', 'castPeriod'), + 'DateTimeInterface' => ['Symfony\Component\VarDumper\Caster\DateCaster', 'castDateTime'], + 'DateInterval' => ['Symfony\Component\VarDumper\Caster\DateCaster', 'castInterval'], + 'DateTimeZone' => ['Symfony\Component\VarDumper\Caster\DateCaster', 'castTimeZone'], + 'DatePeriod' => ['Symfony\Component\VarDumper\Caster\DateCaster', 'castPeriod'], - 'GMP' => array('Symfony\Component\VarDumper\Caster\GmpCaster', 'castGmp'), + 'GMP' => ['Symfony\Component\VarDumper\Caster\GmpCaster', 'castGmp'], - 'MessageFormatter' => array('Symfony\Component\VarDumper\Caster\IntlCaster', 'castMessageFormatter'), - 'NumberFormatter' => array('Symfony\Component\VarDumper\Caster\IntlCaster', 'castNumberFormatter'), - 'IntlTimeZone' => array('Symfony\Component\VarDumper\Caster\IntlCaster', 'castIntlTimeZone'), - 'IntlCalendar' => array('Symfony\Component\VarDumper\Caster\IntlCaster', 'castIntlCalendar'), - 'IntlDateFormatter' => array('Symfony\Component\VarDumper\Caster\IntlCaster', 'castIntlDateFormatter'), + 'MessageFormatter' => ['Symfony\Component\VarDumper\Caster\IntlCaster', 'castMessageFormatter'], + 'NumberFormatter' => ['Symfony\Component\VarDumper\Caster\IntlCaster', 'castNumberFormatter'], + 'IntlTimeZone' => ['Symfony\Component\VarDumper\Caster\IntlCaster', 'castIntlTimeZone'], + 'IntlCalendar' => ['Symfony\Component\VarDumper\Caster\IntlCaster', 'castIntlCalendar'], + 'IntlDateFormatter' => ['Symfony\Component\VarDumper\Caster\IntlCaster', 'castIntlDateFormatter'], - 'Memcached' => array('Symfony\Component\VarDumper\Caster\MemcachedCaster', 'castMemcached'), + 'Memcached' => ['Symfony\Component\VarDumper\Caster\MemcachedCaster', 'castMemcached'], - ':curl' => array('Symfony\Component\VarDumper\Caster\ResourceCaster', 'castCurl'), - ':dba' => array('Symfony\Component\VarDumper\Caster\ResourceCaster', 'castDba'), - ':dba persistent' => array('Symfony\Component\VarDumper\Caster\ResourceCaster', 'castDba'), - ':gd' => array('Symfony\Component\VarDumper\Caster\ResourceCaster', 'castGd'), - ':mysql link' => array('Symfony\Component\VarDumper\Caster\ResourceCaster', 'castMysqlLink'), - ':pgsql large object' => array('Symfony\Component\VarDumper\Caster\PgSqlCaster', 'castLargeObject'), - ':pgsql link' => array('Symfony\Component\VarDumper\Caster\PgSqlCaster', 'castLink'), - ':pgsql link persistent' => array('Symfony\Component\VarDumper\Caster\PgSqlCaster', 'castLink'), - ':pgsql result' => array('Symfony\Component\VarDumper\Caster\PgSqlCaster', 'castResult'), - ':process' => array('Symfony\Component\VarDumper\Caster\ResourceCaster', 'castProcess'), - ':stream' => array('Symfony\Component\VarDumper\Caster\ResourceCaster', 'castStream'), - ':persistent stream' => array('Symfony\Component\VarDumper\Caster\ResourceCaster', 'castStream'), - ':stream-context' => array('Symfony\Component\VarDumper\Caster\ResourceCaster', 'castStreamContext'), - ':xml' => array('Symfony\Component\VarDumper\Caster\XmlResourceCaster', 'castXml'), - ); + ':curl' => ['Symfony\Component\VarDumper\Caster\ResourceCaster', 'castCurl'], + ':dba' => ['Symfony\Component\VarDumper\Caster\ResourceCaster', 'castDba'], + ':dba persistent' => ['Symfony\Component\VarDumper\Caster\ResourceCaster', 'castDba'], + ':gd' => ['Symfony\Component\VarDumper\Caster\ResourceCaster', 'castGd'], + ':mysql link' => ['Symfony\Component\VarDumper\Caster\ResourceCaster', 'castMysqlLink'], + ':pgsql large object' => ['Symfony\Component\VarDumper\Caster\PgSqlCaster', 'castLargeObject'], + ':pgsql link' => ['Symfony\Component\VarDumper\Caster\PgSqlCaster', 'castLink'], + ':pgsql link persistent' => ['Symfony\Component\VarDumper\Caster\PgSqlCaster', 'castLink'], + ':pgsql result' => ['Symfony\Component\VarDumper\Caster\PgSqlCaster', 'castResult'], + ':process' => ['Symfony\Component\VarDumper\Caster\ResourceCaster', 'castProcess'], + ':stream' => ['Symfony\Component\VarDumper\Caster\ResourceCaster', 'castStream'], + ':persistent stream' => ['Symfony\Component\VarDumper\Caster\ResourceCaster', 'castStream'], + ':stream-context' => ['Symfony\Component\VarDumper\Caster\ResourceCaster', 'castStreamContext'], + ':xml' => ['Symfony\Component\VarDumper\Caster\XmlResourceCaster', 'castXml'], + ]; protected $maxItems = 2500; protected $maxString = -1; protected $minDepth = 1; - private $casters = array(); + private $casters = []; private $prevErrorHandler; - private $classInfo = array(); + private $classInfo = []; private $filter = 0; /** @@ -221,7 +221,7 @@ abstract class AbstractCloner implements ClonerInterface */ public function cloneVar($var, $filter = 0) { - $this->prevErrorHandler = set_error_handler(function ($type, $msg, $file, $line, $context = array()) { + $this->prevErrorHandler = set_error_handler(function ($type, $msg, $file, $line, $context = []) { if (E_RECOVERABLE_ERROR === $type || E_USER_ERROR === $type) { // Cloner never dies throw new \ErrorException($msg, 0, $type, $file, $line); @@ -278,7 +278,7 @@ abstract class AbstractCloner implements ClonerInterface list($i, $parents, $hasDebugInfo) = $this->classInfo[$class]; } else { $i = 2; - $parents = array(strtolower($class)); + $parents = [strtolower($class)]; $hasDebugInfo = method_exists($class, '__debugInfo'); foreach (class_parents($class) as $p) { @@ -291,7 +291,7 @@ abstract class AbstractCloner implements ClonerInterface } $parents[] = '*'; - $this->classInfo[$class] = array($i, $parents, $hasDebugInfo); + $this->classInfo[$class] = [$i, $parents, $hasDebugInfo]; } $a = Caster::castObject($obj, $class, $hasDebugInfo); @@ -305,7 +305,7 @@ abstract class AbstractCloner implements ClonerInterface } } } catch (\Exception $e) { - $a = array((Stub::TYPE_OBJECT === $stub->type ? Caster::PREFIX_VIRTUAL : '').'⚠' => new ThrowingCasterException($e)) + $a; + $a = [(Stub::TYPE_OBJECT === $stub->type ? Caster::PREFIX_VIRTUAL : '').'⚠' => new ThrowingCasterException($e)] + $a; } return $a; @@ -321,7 +321,7 @@ abstract class AbstractCloner implements ClonerInterface */ protected function castResource(Stub $stub, $isNested) { - $a = array(); + $a = []; $res = $stub->value; $type = $stub->class; @@ -332,7 +332,7 @@ abstract class AbstractCloner implements ClonerInterface } } } catch (\Exception $e) { - $a = array((Stub::TYPE_OBJECT === $stub->type ? Caster::PREFIX_VIRTUAL : '').'⚠' => new ThrowingCasterException($e)) + $a; + $a = [(Stub::TYPE_OBJECT === $stub->type ? Caster::PREFIX_VIRTUAL : '').'⚠' => new ThrowingCasterException($e)] + $a; } return $a; diff --git a/src/Symfony/Component/VarDumper/Dumper/HtmlDumper.php b/src/Symfony/Component/VarDumper/Dumper/HtmlDumper.php index e15a2b644e..03502bbd8f 100644 --- a/src/Symfony/Component/VarDumper/Dumper/HtmlDumper.php +++ b/src/Symfony/Component/VarDumper/Dumper/HtmlDumper.php @@ -23,8 +23,8 @@ class HtmlDumper extends CliDumper { public static $defaultOutput = 'php://output'; - protected static $themes = array( - 'dark' => array( + protected static $themes = [ + 'dark' => [ 'default' => 'background-color:#18171B; color:#FF8400; line-height:1.2em; font:12px Menlo, Monaco, Consolas, monospace; word-wrap: break-word; white-space: pre-wrap; position:relative; z-index:99999; word-break: break-all', 'num' => 'font-weight:bold; color:#1299DA', 'const' => 'font-weight:bold', @@ -39,8 +39,8 @@ class HtmlDumper extends CliDumper 'index' => 'color:#1299DA', 'ellipsis' => 'color:#FF8400', 'ns' => 'user-select:none;', - ), - 'light' => array( + ], + 'light' => [ 'default' => 'background:none; color:#CC7832; line-height:1.2em; font:12px Menlo, Monaco, Consolas, monospace; word-wrap: break-word; white-space: pre-wrap; position:relative; z-index:99999; word-break: break-all', 'num' => 'font-weight:bold; color:#1299DA', 'const' => 'font-weight:bold', @@ -55,8 +55,8 @@ class HtmlDumper extends CliDumper 'index' => 'color:#1299DA', 'ellipsis' => 'color:#CC7832', 'ns' => 'user-select:none;', - ), - ); + ], + ]; protected $dumpHeader; protected $dumpPrefix = '
';
@@ -67,12 +67,12 @@ class HtmlDumper extends CliDumper
     protected $lastDepth = -1;
     protected $styles;
 
-    private $displayOptions = array(
+    private $displayOptions = [
         'maxDepth' => 1,
         'maxStringLength' => 160,
         'fileLinkFormat' => null,
-    );
-    private $extraDisplayOptions = array();
+    ];
+    private $extraDisplayOptions = [];
 
     /**
      * {@inheritdoc}
@@ -139,7 +139,7 @@ class HtmlDumper extends CliDumper
     /**
      * {@inheritdoc}
      */
-    public function dump(Data $data, $output = null, array $extraDisplayOptions = array())
+    public function dump(Data $data, $output = null, array $extraDisplayOptions = [])
     {
         $this->extraDisplayOptions = $extraDisplayOptions;
         $result = parent::dump($data, $output);
@@ -819,7 +819,7 @@ EOHTML
     /**
      * {@inheritdoc}
      */
-    protected function style($style, $value, $attr = array())
+    protected function style($style, $value, $attr = [])
     {
         if ('' === $value) {
             return '';
@@ -919,7 +919,7 @@ EOHTML
         }
 
         if (-1 === $depth) {
-            $args = array('"'.$this->dumpId.'"');
+            $args = ['"'.$this->dumpId.'"'];
             if ($this->extraDisplayOptions) {
                 $args[] = json_encode($this->extraDisplayOptions, JSON_FORCE_OBJECT);
             }
@@ -941,7 +941,7 @@ EOHTML
         $options = $this->extraDisplayOptions + $this->displayOptions;
 
         if ($fmt = $options['fileLinkFormat']) {
-            return \is_string($fmt) ? strtr($fmt, array('%f' => $file, '%l' => $line)) : $fmt->format($file, $line);
+            return \is_string($fmt) ? strtr($fmt, ['%f' => $file, '%l' => $line]) : $fmt->format($file, $line);
         }
 
         return false;
diff --git a/src/Symfony/Component/VarDumper/Tests/Caster/StubCasterTest.php b/src/Symfony/Component/VarDumper/Tests/Caster/StubCasterTest.php
index 26c276ad55..8056f703b6 100644
--- a/src/Symfony/Component/VarDumper/Tests/Caster/StubCasterTest.php
+++ b/src/Symfony/Component/VarDumper/Tests/Caster/StubCasterTest.php
@@ -192,14 +192,14 @@ EODUMP;
 
     public function testClassStubWithAnonymousClass()
     {
-        $var = array(new ClassStub(\get_class(new class() extends \Exception {
-        })));
+        $var = [new ClassStub(\get_class(new class() extends \Exception {
+        }))];
 
         $cloner = new VarCloner();
         $dumper = new HtmlDumper();
         $dumper->setDumpHeader('');
         $dumper->setDumpBoundaries('', '');
-        $dump = $dumper->dump($cloner->cloneVar($var), true, array('fileLinkFormat' => '%f:%l'));
+        $dump = $dumper->dump($cloner->cloneVar($var), true, ['fileLinkFormat' => '%f:%l']);
 
         $expectedDump = <<<'EODUMP'
 array:1 [
diff --git a/src/Symfony/Component/VarDumper/VarDumper.php b/src/Symfony/Component/VarDumper/VarDumper.php
index 7c302a21ff..4271e63965 100644
--- a/src/Symfony/Component/VarDumper/VarDumper.php
+++ b/src/Symfony/Component/VarDumper/VarDumper.php
@@ -33,7 +33,7 @@ class VarDumper
             if (isset($_SERVER['VAR_DUMPER_FORMAT'])) {
                 $dumper = 'html' === $_SERVER['VAR_DUMPER_FORMAT'] ? new HtmlDumper() : new CliDumper();
             } else {
-                $dumper = \in_array(\PHP_SAPI, array('cli', 'phpdbg')) ? new CliDumper() : new HtmlDumper();
+                $dumper = \in_array(\PHP_SAPI, ['cli', 'phpdbg']) ? new CliDumper() : new HtmlDumper();
             }
 
             self::$handler = function ($var) use ($cloner, $dumper) {
diff --git a/src/Symfony/Component/VarExporter/Instantiator.php b/src/Symfony/Component/VarExporter/Instantiator.php
index 0061d76e78..7eefc3c2d2 100644
--- a/src/Symfony/Component/VarExporter/Instantiator.php
+++ b/src/Symfony/Component/VarExporter/Instantiator.php
@@ -57,20 +57,20 @@ final class Instantiator
      *
      * @throws ExceptionInterface When the instance cannot be created
      */
-    public static function instantiate(string $class, array $properties = array(), array $privateProperties = array())
+    public static function instantiate(string $class, array $properties = [], array $privateProperties = [])
     {
         $reflector = Registry::$reflectors[$class] ?? Registry::getClassReflector($class);
 
         if (Registry::$cloneable[$class]) {
-            $wrappedInstance = array(clone Registry::$prototypes[$class]);
+            $wrappedInstance = [clone Registry::$prototypes[$class]];
         } elseif (Registry::$instantiableWithoutConstructor[$class]) {
-            $wrappedInstance = array($reflector->newInstanceWithoutConstructor());
+            $wrappedInstance = [$reflector->newInstanceWithoutConstructor()];
         } elseif (null === Registry::$prototypes[$class]) {
             throw new NotInstantiableTypeException($class);
         } elseif ($reflector->implementsInterface('Serializable')) {
-            $wrappedInstance = array(unserialize('C:'.\strlen($class).':"'.$class.'":0:{}'));
+            $wrappedInstance = [unserialize('C:'.\strlen($class).':"'.$class.'":0:{}')];
         } else {
-            $wrappedInstance = array(unserialize('O:'.\strlen($class).':"'.$class.'":0:{}'));
+            $wrappedInstance = [unserialize('O:'.\strlen($class).':"'.$class.'":0:{}')];
         }
 
         if ($properties) {
@@ -84,7 +84,7 @@ final class Instantiator
             foreach ($properties as $name => $value) {
                 // because they're also used for "unserialization", hydrators
                 // deal with array of instances, so we need to wrap values
-                $properties[$name] = array($value);
+                $properties[$name] = [$value];
             }
             (Hydrator::$hydrators[$class] ?? Hydrator::getHydrator($class))($properties, $wrappedInstance);
         }
diff --git a/src/Symfony/Component/VarExporter/Internal/Exporter.php b/src/Symfony/Component/VarExporter/Internal/Exporter.php
index 38a8e25088..fae9084ca0 100644
--- a/src/Symfony/Component/VarExporter/Internal/Exporter.php
+++ b/src/Symfony/Component/VarExporter/Internal/Exporter.php
@@ -53,7 +53,7 @@ class Exporter
                     ++$value->count;
                     continue;
                 }
-                $refsPool[] = array(&$refs[$k], $value, &$value);
+                $refsPool[] = [&$refs[$k], $value, &$value];
                 $refs[$k] = $values[$k] = new Reference(-\count($refsPool), $value);
             }
 
@@ -74,7 +74,7 @@ class Exporter
             }
 
             $class = \get_class($value);
-            $properties = array();
+            $properties = [];
             $sleep = null;
             $arrayValue = (array) $value;
             $reflector = Registry::$reflectors[$class] ?? Registry::getClassReflector($class);
@@ -94,10 +94,10 @@ class Exporter
                     $properties[] = $v;
                     $properties[] = $value[$v];
                 }
-                $properties = array('SplObjectStorage' => array("\0" => $properties));
+                $properties = ['SplObjectStorage' => ["\0" => $properties]];
             } elseif ($value instanceof \Serializable || $value instanceof \__PHP_Incomplete_Class) {
                 ++$objectsCount;
-                $objectsPool[$value] = array($id = \count($objectsPool), serialize($value), array(), 0);
+                $objectsPool[$value] = [$id = \count($objectsPool), serialize($value), [], 0];
                 $value = new Reference($id);
                 goto handle_value;
             }
@@ -154,10 +154,10 @@ class Exporter
                 }
             }
 
-            $objectsPool[$value] = array($id = \count($objectsPool));
+            $objectsPool[$value] = [$id = \count($objectsPool)];
             $properties = self::prepare($properties, $objectsPool, $refsPool, $objectsCount, $valueIsStatic);
             ++$objectsCount;
-            $objectsPool[$value] = array($id, $class, $properties, \method_exists($class, '__wakeup') ? $objectsCount : 0);
+            $objectsPool[$value] = [$id, $class, $properties, \method_exists($class, '__wakeup') ? $objectsCount : 0];
 
             $value = new Reference($id);
 
@@ -177,7 +177,7 @@ class Exporter
     {
         switch (true) {
             case \is_int($value) || \is_float($value): return var_export($value, true);
-            case array() === $value: return '[]';
+            case [] === $value: return '[]';
             case false === $value: return 'false';
             case true === $value: return 'true';
             case null === $value: return 'null';
@@ -201,11 +201,11 @@ class Exporter
             $code = var_export($value, true);
 
             if (false !== strpos($value, "\n") || false !== strpos($value, "\r")) {
-                $code = strtr($code, array(
+                $code = strtr($code, [
                     "\r\n" => "'.\"\\r\\n\"\n".$subIndent.".'",
                     "\r" => "'.\"\\r\"\n".$subIndent.".'",
                     "\n" => "'.\"\\n\"\n".$subIndent.".'",
-                ));
+                ]);
             }
 
             if (false !== strpos($value, "\0")) {
@@ -264,8 +264,8 @@ class Exporter
     private static function exportRegistry(Registry $value, string $indent, string $subIndent): string
     {
         $code = '';
-        $serializables = array();
-        $seen = array();
+        $serializables = [];
+        $seen = [];
         $prototypesAccess = 0;
         $factoriesAccess = 0;
         $r = '\\'.Registry::class;
@@ -340,13 +340,13 @@ class Exporter
             $code .= $subIndent.'    '.self::export($class).' => '.self::export($properties, $subIndent.'    ').",\n";
         }
 
-        $code = array(
+        $code = [
             self::export($value->registry, $subIndent),
             self::export($value->values, $subIndent),
             '' !== $code ? "[\n".$code.$subIndent.']' : '[]',
             self::export($value->value, $subIndent),
             self::export($value->wakeups, $subIndent),
-        );
+        ];
 
         return '\\'.\get_class($value)."::hydrate(\n".$subIndent.implode(",\n".$subIndent, $code)."\n".$indent.')';
     }
@@ -360,11 +360,11 @@ class Exporter
         $reflector = $value instanceof \ArrayIterator ? 'ArrayIterator' : 'ArrayObject';
         $reflector = Registry::$reflectors[$reflector] ?? Registry::getClassReflector($reflector);
 
-        $properties = array(
+        $properties = [
             $arrayValue,
             $reflector->getMethod('getFlags')->invoke($value),
             $value instanceof \ArrayObject ? $reflector->getMethod('getIteratorClass')->invoke($value) : 'ArrayIterator',
-        );
+        ];
 
         $reflector = $reflector->getMethod('setFlags');
         $reflector->invoke($proto, \ArrayObject::STD_PROP_LIST);
@@ -378,13 +378,13 @@ class Exporter
         }
         $reflector->invoke($value, $properties[1]);
 
-        if (array(array(), 0, 'ArrayIterator') === $properties) {
-            $properties = array();
+        if ([[], 0, 'ArrayIterator'] === $properties) {
+            $properties = [];
         } else {
             if ('ArrayIterator' === $properties[2]) {
                 unset($properties[2]);
             }
-            $properties = array($reflector->class => array("\0" => $properties));
+            $properties = [$reflector->class => ["\0" => $properties]];
         }
 
         return $properties;
diff --git a/src/Symfony/Component/VarExporter/Internal/Hydrator.php b/src/Symfony/Component/VarExporter/Internal/Hydrator.php
index a1a60112d9..07721df428 100644
--- a/src/Symfony/Component/VarExporter/Internal/Hydrator.php
+++ b/src/Symfony/Component/VarExporter/Internal/Hydrator.php
@@ -20,7 +20,7 @@ use Symfony\Component\VarExporter\Exception\ClassNotFoundException;
  */
 class Hydrator
 {
-    public static $hydrators = array();
+    public static $hydrators = [];
 
     public $registry;
     public $values;
@@ -77,7 +77,7 @@ class Hydrator
         switch ($class) {
             case 'ArrayIterator':
             case 'ArrayObject':
-                $constructor = \Closure::fromCallable(array($classReflector->getConstructor(), 'invokeArgs'));
+                $constructor = \Closure::fromCallable([$classReflector->getConstructor(), 'invokeArgs']);
 
                 return self::$hydrators[$class] = static function ($properties, $objects) use ($constructor) {
                     foreach ($properties as $name => $values) {
@@ -87,7 +87,7 @@ class Hydrator
                             }
                         }
                     }
-                    foreach ($properties["\0"] ?? array() as $i => $v) {
+                    foreach ($properties["\0"] ?? [] as $i => $v) {
                         $constructor($objects[$i], $v);
                     }
                 };
@@ -118,11 +118,11 @@ class Hydrator
                 };
         }
 
-        $propertySetters = array();
+        $propertySetters = [];
         foreach ($classReflector->getProperties() as $propertyReflector) {
             if (!$propertyReflector->isStatic()) {
                 $propertyReflector->setAccessible(true);
-                $propertySetters[$propertyReflector->name] = \Closure::fromCallable(array($propertyReflector, 'setValue'));
+                $propertySetters[$propertyReflector->name] = \Closure::fromCallable([$propertyReflector, 'setValue']);
             }
         }
 
diff --git a/src/Symfony/Component/VarExporter/Internal/Registry.php b/src/Symfony/Component/VarExporter/Internal/Registry.php
index 705722650a..629836b00b 100644
--- a/src/Symfony/Component/VarExporter/Internal/Registry.php
+++ b/src/Symfony/Component/VarExporter/Internal/Registry.php
@@ -21,11 +21,11 @@ use Symfony\Component\VarExporter\Exception\NotInstantiableTypeException;
  */
 class Registry
 {
-    public static $reflectors = array();
-    public static $prototypes = array();
-    public static $factories = array();
-    public static $cloneable = array();
-    public static $instantiableWithoutConstructor = array();
+    public static $reflectors = [];
+    public static $prototypes = [];
+    public static $factories = [];
+    public static $cloneable = [];
+    public static $instantiableWithoutConstructor = [];
 
     public function __construct(array $classes)
     {
@@ -60,7 +60,7 @@ class Registry
     {
         $reflector = self::$reflectors[$class] ?? self::getClassReflector($class, true, false);
 
-        return self::$factories[$class] = \Closure::fromCallable(array($reflector, 'newInstanceWithoutConstructor'));
+        return self::$factories[$class] = \Closure::fromCallable([$reflector, 'newInstanceWithoutConstructor']);
     }
 
     public static function getClassReflector($class, $instantiableWithoutConstructor = false, $cloneable = null)
@@ -118,17 +118,17 @@ class Registry
             static $setTrace;
 
             if (null === $setTrace) {
-                $setTrace = array(
+                $setTrace = [
                     new \ReflectionProperty(\Error::class, 'trace'),
                     new \ReflectionProperty(\Exception::class, 'trace'),
-                );
+                ];
                 $setTrace[0]->setAccessible(true);
                 $setTrace[1]->setAccessible(true);
-                $setTrace[0] = \Closure::fromCallable(array($setTrace[0], 'setValue'));
-                $setTrace[1] = \Closure::fromCallable(array($setTrace[1], 'setValue'));
+                $setTrace[0] = \Closure::fromCallable([$setTrace[0], 'setValue']);
+                $setTrace[1] = \Closure::fromCallable([$setTrace[1], 'setValue']);
             }
 
-            $setTrace[$proto instanceof \Exception]($proto, array());
+            $setTrace[$proto instanceof \Exception]($proto, []);
         }
 
         return self::$reflectors[$class] = $reflector;
diff --git a/src/Symfony/Component/VarExporter/Tests/InstantiatorTest.php b/src/Symfony/Component/VarExporter/Tests/InstantiatorTest.php
index 2cb8e7a359..cae10e3b44 100644
--- a/src/Symfony/Component/VarExporter/Tests/InstantiatorTest.php
+++ b/src/Symfony/Component/VarExporter/Tests/InstantiatorTest.php
@@ -37,30 +37,30 @@ class InstantiatorTest extends TestCase
 
     public function provideFailingInstantiation()
     {
-        yield array('ReflectionClass');
-        yield array('SplHeap');
-        yield array('Throwable');
-        yield array('Closure');
-        yield array('SplFileInfo');
+        yield ['ReflectionClass'];
+        yield ['SplHeap'];
+        yield ['Throwable'];
+        yield ['Closure'];
+        yield ['SplFileInfo'];
     }
 
     public function testInstantiate()
     {
-        $this->assertEquals((object) array('p' => 123), Instantiator::instantiate('stdClass', array('p' => 123)));
-        $this->assertEquals((object) array('p' => 123), Instantiator::instantiate('STDcLASS', array('p' => 123)));
-        $this->assertEquals(new \ArrayObject(array(123)), Instantiator::instantiate(\ArrayObject::class, array("\0" => array(array(123)))));
+        $this->assertEquals((object) ['p' => 123], Instantiator::instantiate('stdClass', ['p' => 123]));
+        $this->assertEquals((object) ['p' => 123], Instantiator::instantiate('STDcLASS', ['p' => 123]));
+        $this->assertEquals(new \ArrayObject([123]), Instantiator::instantiate(\ArrayObject::class, ["\0" => [[123]]]));
 
-        $expected = array(
+        $expected = [
             "\0".__NAMESPACE__."\Bar\0priv" => 123,
             "\0".__NAMESPACE__."\Foo\0priv" => 234,
-        );
+        ];
 
-        $this->assertSame($expected, (array) Instantiator::instantiate(Bar::class, array('priv' => 123), array(Foo::class => array('priv' => 234))));
+        $this->assertSame($expected, (array) Instantiator::instantiate(Bar::class, ['priv' => 123], [Foo::class => ['priv' => 234]]));
 
-        $e = Instantiator::instantiate('Exception', array('foo' => 123, 'trace' => array(234)));
+        $e = Instantiator::instantiate('Exception', ['foo' => 123, 'trace' => [234]]);
 
         $this->assertSame(123, $e->foo);
-        $this->assertSame(array(234), $e->getTrace());
+        $this->assertSame([234], $e->getTrace());
     }
 }
 
diff --git a/src/Symfony/Component/VarExporter/Tests/VarExporterTest.php b/src/Symfony/Component/VarExporter/Tests/VarExporterTest.php
index c34a7e4fb7..5bb03d8ce1 100644
--- a/src/Symfony/Component/VarExporter/Tests/VarExporterTest.php
+++ b/src/Symfony/Component/VarExporter/Tests/VarExporterTest.php
@@ -28,7 +28,7 @@ class VarExporterTest extends TestCase
     {
         $unserializeCallback = ini_set('unserialize_callback_func', 'var_dump');
         try {
-            Registry::unserialize(array(), array('O:20:"SomeNotExistingClass":0:{}'));
+            Registry::unserialize([], ['O:20:"SomeNotExistingClass":0:{}']);
         } finally {
             $this->assertSame('var_dump', ini_set('unserialize_callback_func', $unserializeCallback));
         }
@@ -51,25 +51,25 @@ class VarExporterTest extends TestCase
 
     public function provideFailingSerialization()
     {
-        yield array(hash_init('md5'));
-        yield array(new \ReflectionClass('stdClass'));
-        yield array((new \ReflectionFunction(function (): int {}))->getReturnType());
-        yield array(new \ReflectionGenerator((function () { yield 123; })()));
-        yield array(function () {});
-        yield array(function () { yield 123; });
-        yield array(new \SplFileInfo(__FILE__));
-        yield array($h = fopen(__FILE__, 'r'));
-        yield array(array($h));
+        yield [hash_init('md5')];
+        yield [new \ReflectionClass('stdClass')];
+        yield [(new \ReflectionFunction(function (): int {}))->getReturnType()];
+        yield [new \ReflectionGenerator((function () { yield 123; })())];
+        yield [function () {}];
+        yield [function () { yield 123; }];
+        yield [new \SplFileInfo(__FILE__)];
+        yield [$h = fopen(__FILE__, 'r')];
+        yield [[$h]];
 
         $a = new class() {
         };
 
-        yield array($a);
+        yield [$a];
 
-        $a = array(null, $h);
+        $a = [null, $h];
         $a[0] = &$a;
 
-        yield array($a);
+        yield [$a];
     }
 
     /**
@@ -108,26 +108,26 @@ class VarExporterTest extends TestCase
 
     public function provideExport()
     {
-        yield array('multiline-string', array("\0\0\r\nA" => "B\rC\n\n"), true);
+        yield ['multiline-string', ["\0\0\r\nA" => "B\rC\n\n"], true];
 
-        yield array('bool', true, true);
-        yield array('simple-array', array(123, array('abc')), true);
-        yield array('partially-indexed-array', array(5 => true, 1 => true, 2 => true, 6 => true), true);
-        yield array('datetime', \DateTime::createFromFormat('U', 0));
+        yield ['bool', true, true];
+        yield ['simple-array', [123, ['abc']], true];
+        yield ['partially-indexed-array', [5 => true, 1 => true, 2 => true, 6 => true], true];
+        yield ['datetime', \DateTime::createFromFormat('U', 0)];
 
         $value = new \ArrayObject();
         $value[0] = 1;
         $value->foo = new \ArrayObject();
         $value[1] = $value;
 
-        yield array('array-object', $value);
+        yield ['array-object', $value];
 
-        yield array('array-iterator', new \ArrayIterator(array(123), 1));
-        yield array('array-object-custom', new MyArrayObject(array(234)));
+        yield ['array-iterator', new \ArrayIterator([123], 1)];
+        yield ['array-object-custom', new MyArrayObject([234])];
 
         $value = new MySerializable();
 
-        yield array('serializable', array($value, $value));
+        yield ['serializable', [$value, $value]];
 
         $value = new MyWakeup();
         $value->sub = new MyWakeup();
@@ -135,33 +135,33 @@ class VarExporterTest extends TestCase
         $value->sub->bis = 123;
         $value->sub->baz = 123;
 
-        yield array('wakeup', $value);
+        yield ['wakeup', $value];
 
-        yield array('clone', array(new MyCloneable(), new MyNotCloneable()));
+        yield ['clone', [new MyCloneable(), new MyNotCloneable()]];
 
-        yield array('private', array(new MyPrivateValue(123, 234), new MyPrivateChildValue(123, 234)));
+        yield ['private', [new MyPrivateValue(123, 234), new MyPrivateChildValue(123, 234)]];
 
         $value = new \SplObjectStorage();
         $value[new \stdClass()] = 345;
 
-        yield array('spl-object-storage', $value);
+        yield ['spl-object-storage', $value];
 
-        yield array('incomplete-class', unserialize('O:20:"SomeNotExistingClass":0:{}'));
+        yield ['incomplete-class', unserialize('O:20:"SomeNotExistingClass":0:{}')];
 
-        $value = array((object) array());
+        $value = [(object) []];
         $value[1] = &$value[0];
         $value[2] = $value[0];
 
-        yield array('hard-references', $value);
+        yield ['hard-references', $value];
 
-        $value = array();
+        $value = [];
         $value[0] = &$value;
 
-        yield array('hard-references-recursive', $value);
+        yield ['hard-references-recursive', $value];
 
-        static $value = array(123);
+        static $value = [123];
 
-        yield array('external-references', array(&$value), true);
+        yield ['external-references', [&$value], true];
 
         unset($value);
 
@@ -169,34 +169,34 @@ class VarExporterTest extends TestCase
 
         $rt = new \ReflectionProperty('Error', 'trace');
         $rt->setAccessible(true);
-        $rt->setValue($value, array('file' => __FILE__, 'line' => 123));
+        $rt->setValue($value, ['file' => __FILE__, 'line' => 123]);
 
         $rl = new \ReflectionProperty('Error', 'line');
         $rl->setAccessible(true);
         $rl->setValue($value, 234);
 
-        yield array('error', $value);
+        yield ['error', $value];
 
-        yield array('var-on-sleep', new GoodNight());
+        yield ['var-on-sleep', new GoodNight()];
 
         $value = new FinalError(false);
-        $rt->setValue($value, array());
+        $rt->setValue($value, []);
         $rl->setValue($value, 123);
 
-        yield array('final-error', $value);
+        yield ['final-error', $value];
 
-        yield array('final-array-iterator', new FinalArrayIterator());
+        yield ['final-array-iterator', new FinalArrayIterator()];
 
-        yield array('final-stdclass', new FinalStdClass());
+        yield ['final-stdclass', new FinalStdClass()];
 
         $value = new MyWakeup();
         $value->bis = new \ReflectionClass($value);
 
-        yield array('wakeup-refl', $value);
+        yield ['wakeup-refl', $value];
 
-        yield array('abstract-parent', new ConcreteClass());
+        yield ['abstract-parent', new ConcreteClass()];
 
-        yield array('foo-serializable', new FooSerializable('bar'));
+        yield ['foo-serializable', new FooSerializable('bar')];
     }
 }
 
@@ -222,7 +222,7 @@ class MyWakeup
 
     public function __sleep()
     {
-        return array('sub', 'baz');
+        return ['sub', 'baz'];
     }
 
     public function __wakeup()
@@ -287,7 +287,7 @@ class GoodNight
     {
         $this->good = 'night';
 
-        return array('good');
+        return ['good'];
     }
 }
 
@@ -305,7 +305,7 @@ final class FinalArrayIterator extends \ArrayIterator
 {
     public function serialize()
     {
-        return serialize(array(123, parent::serialize()));
+        return serialize([123, parent::serialize()]);
     }
 
     public function unserialize($data)
@@ -362,7 +362,7 @@ class FooSerializable implements \Serializable
 
     public function serialize(): string
     {
-        return serialize(array($this->getFoo()));
+        return serialize([$this->getFoo()]);
     }
 
     public function unserialize($str)
diff --git a/src/Symfony/Component/VarExporter/VarExporter.php b/src/Symfony/Component/VarExporter/VarExporter.php
index ffe44a3db1..45ef7446b1 100644
--- a/src/Symfony/Component/VarExporter/VarExporter.php
+++ b/src/Symfony/Component/VarExporter/VarExporter.php
@@ -48,13 +48,13 @@ final class VarExporter
         }
 
         $objectsPool = new \SplObjectStorage();
-        $refsPool = array();
+        $refsPool = [];
         $objectsCount = 0;
 
         try {
-            $value = Exporter::prepare(array($value), $objectsPool, $refsPool, $objectsCount, $isStaticValue)[0];
+            $value = Exporter::prepare([$value], $objectsPool, $refsPool, $objectsCount, $isStaticValue)[0];
         } finally {
-            $references = array();
+            $references = [];
             foreach ($refsPool as $i => $v) {
                 if ($v[0]->count) {
                     $references[1 + $i] = $v[2];
@@ -67,9 +67,9 @@ final class VarExporter
             return Exporter::export($value);
         }
 
-        $classes = array();
-        $values = array();
-        $wakeups = array();
+        $classes = [];
+        $values = [];
+        $wakeups = [];
         foreach ($objectsPool as $i => $v) {
             list(, $classes[], $values[], $wakeup) = $objectsPool[$v];
             if ($wakeup) {
@@ -78,7 +78,7 @@ final class VarExporter
         }
         ksort($wakeups);
 
-        $properties = array();
+        $properties = [];
         foreach ($values as $i => $vars) {
             foreach ($vars as $class => $values) {
                 foreach ($values as $name => $v) {
diff --git a/src/Symfony/Component/Workflow/Dumper/GraphvizDumper.php b/src/Symfony/Component/Workflow/Dumper/GraphvizDumper.php
index b7c7d8fd4f..f8c0fa5457 100644
--- a/src/Symfony/Component/Workflow/Dumper/GraphvizDumper.php
+++ b/src/Symfony/Component/Workflow/Dumper/GraphvizDumper.php
@@ -26,11 +26,11 @@ use Symfony\Component\Workflow\Marking;
  */
 class GraphvizDumper implements DumperInterface
 {
-    protected static $defaultOptions = array(
-        'graph' => array('ratio' => 'compress', 'rankdir' => 'LR'),
-        'node' => array('fontsize' => 9, 'fontname' => 'Arial', 'color' => '#333333', 'fillcolor' => 'lightblue', 'fixedsize' => 'false', 'width' => 1),
-        'edge' => array('fontsize' => 9, 'fontname' => 'Arial', 'color' => '#333333', 'arrowhead' => 'normal', 'arrowsize' => 0.5),
-    );
+    protected static $defaultOptions = [
+        'graph' => ['ratio' => 'compress', 'rankdir' => 'LR'],
+        'node' => ['fontsize' => 9, 'fontname' => 'Arial', 'color' => '#333333', 'fillcolor' => 'lightblue', 'fixedsize' => 'false', 'width' => 1],
+        'edge' => ['fontsize' => 9, 'fontname' => 'Arial', 'color' => '#333333', 'arrowhead' => 'normal', 'arrowsize' => 0.5],
+    ];
 
     /**
      * {@inheritdoc}
@@ -43,7 +43,7 @@ class GraphvizDumper implements DumperInterface
      *  * node: The default options for nodes (places + transitions)
      *  * edge: The default options for edges
      */
-    public function dump(Definition $definition, Marking $marking = null, array $options = array())
+    public function dump(Definition $definition, Marking $marking = null, array $options = [])
     {
         $places = $this->findPlaces($definition, $marking);
         $transitions = $this->findTransitions($definition);
@@ -63,10 +63,10 @@ class GraphvizDumper implements DumperInterface
      */
     protected function findPlaces(Definition $definition, Marking $marking = null)
     {
-        $places = array();
+        $places = [];
 
         foreach ($definition->getPlaces() as $place) {
-            $attributes = array();
+            $attributes = [];
             if ($place === $definition->getInitialPlace()) {
                 $attributes['style'] = 'filled';
             }
@@ -74,9 +74,9 @@ class GraphvizDumper implements DumperInterface
                 $attributes['color'] = '#FF0000';
                 $attributes['shape'] = 'doublecircle';
             }
-            $places[$place] = array(
+            $places[$place] = [
                 'attributes' => $attributes,
-            );
+            ];
         }
 
         return $places;
@@ -87,13 +87,13 @@ class GraphvizDumper implements DumperInterface
      */
     protected function findTransitions(Definition $definition)
     {
-        $transitions = array();
+        $transitions = [];
 
         foreach ($definition->getTransitions() as $transition) {
-            $transitions[] = array(
-                'attributes' => array('shape' => 'box', 'regular' => true),
+            $transitions[] = [
+                'attributes' => ['shape' => 'box', 'regular' => true],
                 'name' => $transition->getName(),
-            );
+            ];
         }
 
         return $transitions;
@@ -132,22 +132,22 @@ class GraphvizDumper implements DumperInterface
      */
     protected function findEdges(Definition $definition)
     {
-        $dotEdges = array();
+        $dotEdges = [];
 
         foreach ($definition->getTransitions() as $transition) {
             foreach ($transition->getFroms() as $from) {
-                $dotEdges[] = array(
+                $dotEdges[] = [
                     'from' => $from,
                     'to' => $transition->getName(),
                     'direction' => 'from',
-                );
+                ];
             }
             foreach ($transition->getTos() as $to) {
-                $dotEdges[] = array(
+                $dotEdges[] = [
                     'from' => $transition->getName(),
                     'to' => $to,
                     'direction' => 'to',
-                );
+                ];
             }
         }
 
@@ -211,7 +211,7 @@ class GraphvizDumper implements DumperInterface
 
     private function addAttributes(array $attributes): string
     {
-        $code = array();
+        $code = [];
 
         foreach ($attributes as $k => $v) {
             $code[] = sprintf('%s="%s"', $k, $this->escape($v));
@@ -222,7 +222,7 @@ class GraphvizDumper implements DumperInterface
 
     private function addOptions(array $options): string
     {
-        $code = array();
+        $code = [];
 
         foreach ($options as $k => $v) {
             $code[] = sprintf('%s="%s"', $k, $v);
diff --git a/src/Symfony/Component/Yaml/Command/LintCommand.php b/src/Symfony/Component/Yaml/Command/LintCommand.php
index a8cdc318be..77d449cbf8 100644
--- a/src/Symfony/Component/Yaml/Command/LintCommand.php
+++ b/src/Symfony/Component/Yaml/Command/LintCommand.php
@@ -92,10 +92,10 @@ EOF
                 throw new RuntimeException('Please provide a filename or pipe file content to STDIN.');
             }
 
-            return $this->display($io, array($this->validate($stdin, $flags)));
+            return $this->display($io, [$this->validate($stdin, $flags)]);
         }
 
-        $filesInfo = array();
+        $filesInfo = [];
         foreach ($filenames as $filename) {
             if (!$this->isReadable($filename)) {
                 throw new RuntimeException(sprintf('File or directory "%s" is not readable.', $filename));
@@ -122,12 +122,12 @@ EOF
         try {
             $this->getParser()->parse($content, Yaml::PARSE_CONSTANT | $flags);
         } catch (ParseException $e) {
-            return array('file' => $file, 'line' => $e->getParsedLine(), 'valid' => false, 'message' => $e->getMessage());
+            return ['file' => $file, 'line' => $e->getParsedLine(), 'valid' => false, 'message' => $e->getMessage()];
         } finally {
             restore_error_handler();
         }
 
-        return array('file' => $file, 'valid' => true);
+        return ['file' => $file, 'valid' => true];
     }
 
     private function display(SymfonyStyle $io, array $files)
@@ -191,7 +191,7 @@ EOF
         }
 
         foreach ($this->getDirectoryIterator($fileOrDirectory) as $file) {
-            if (!\in_array($file->getExtension(), array('yml', 'yaml'))) {
+            if (!\in_array($file->getExtension(), ['yml', 'yaml'])) {
                 continue;
             }
 
diff --git a/src/Symfony/Component/Yaml/Parser.php b/src/Symfony/Component/Yaml/Parser.php
index 485c46b315..d63467084b 100644
--- a/src/Symfony/Component/Yaml/Parser.php
+++ b/src/Symfony/Component/Yaml/Parser.php
@@ -659,7 +659,7 @@ class Parser
             return $this->refs[$value];
         }
 
-        if (\in_array($value[0], array('!', '|', '>'), true) && self::preg_match('/^(?:'.self::TAG_PATTERN.' +)?'.self::BLOCK_SCALAR_HEADER_PATTERN.'$/', $value, $matches)) {
+        if (\in_array($value[0], ['!', '|', '>'], true) && self::preg_match('/^(?:'.self::TAG_PATTERN.' +)?'.self::BLOCK_SCALAR_HEADER_PATTERN.'$/', $value, $matches)) {
             $modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : '';
 
             $data = $this->parseBlockScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), (int) abs($modifiers));
diff --git a/src/Symfony/Component/Yaml/Tests/Command/LintCommandTest.php b/src/Symfony/Component/Yaml/Tests/Command/LintCommandTest.php
index c1e2736486..b0e1e26af5 100644
--- a/src/Symfony/Component/Yaml/Tests/Command/LintCommandTest.php
+++ b/src/Symfony/Component/Yaml/Tests/Command/LintCommandTest.php
@@ -43,7 +43,7 @@ class LintCommandTest extends TestCase
         $filename1 = $this->createFile('foo: bar');
         $filename2 = $this->createFile('bar: baz');
 
-        $ret = $tester->execute(array('filename' => array($filename1, $filename2)), array('verbosity' => OutputInterface::VERBOSITY_VERBOSE, 'decorated' => false));
+        $ret = $tester->execute(['filename' => [$filename1, $filename2]], ['verbosity' => OutputInterface::VERBOSITY_VERBOSE, 'decorated' => false]);
 
         $this->assertEquals(0, $ret, 'Returns 0 in case of success');
         $this->assertRegExp('/^\/\/ OK in /', trim($tester->getDisplay()));
diff --git a/src/Symfony/Contracts/Cache/CacheTrait.php b/src/Symfony/Contracts/Cache/CacheTrait.php
index d82d96530b..918d5559b7 100644
--- a/src/Symfony/Contracts/Cache/CacheTrait.php
+++ b/src/Symfony/Contracts/Cache/CacheTrait.php
@@ -46,7 +46,7 @@ trait CacheTrait
 
         $item = $pool->getItem($key);
         $recompute = !$item->isHit() || INF === $beta;
-        $metadata = $item instanceof ItemInterface ? $item->getMetadata() : array();
+        $metadata = $item instanceof ItemInterface ? $item->getMetadata() : [];
 
         if (!$recompute && $metadata) {
             $expiry = $metadata[ItemInterface::METADATA_EXPIRY] ?? false;
diff --git a/src/Symfony/Contracts/Service/ServiceLocatorTrait.php b/src/Symfony/Contracts/Service/ServiceLocatorTrait.php
index 8ffa2b4f10..eed44f5d33 100644
--- a/src/Symfony/Contracts/Service/ServiceLocatorTrait.php
+++ b/src/Symfony/Contracts/Service/ServiceLocatorTrait.php
@@ -23,7 +23,7 @@ use Psr\Container\NotFoundExceptionInterface;
 trait ServiceLocatorTrait
 {
     private $factories;
-    private $loading = array();
+    private $loading = [];
 
     /**
      * @param callable[] $factories
diff --git a/src/Symfony/Contracts/Service/ServiceSubscriberTrait.php b/src/Symfony/Contracts/Service/ServiceSubscriberTrait.php
index 457ffb26b7..ceaef6fa14 100644
--- a/src/Symfony/Contracts/Service/ServiceSubscriberTrait.php
+++ b/src/Symfony/Contracts/Service/ServiceSubscriberTrait.php
@@ -32,7 +32,7 @@ trait ServiceSubscriberTrait
             return $services;
         }
 
-        $services = \is_callable(array('parent', __FUNCTION__)) ? parent::getSubscribedServices() : array();
+        $services = \is_callable(['parent', __FUNCTION__]) ? parent::getSubscribedServices() : [];
 
         foreach ((new \ReflectionClass(self::class))->getMethods() as $method) {
             if ($method->isStatic() || $method->isAbstract() || $method->isGenerator() || $method->isInternal() || $method->getNumberOfRequiredParameters()) {
@@ -54,7 +54,7 @@ trait ServiceSubscriberTrait
     {
         $this->container = $container;
 
-        if (\is_callable(array('parent', __FUNCTION__))) {
+        if (\is_callable(['parent', __FUNCTION__])) {
             return parent::setContainer($container);
         }
     }
diff --git a/src/Symfony/Contracts/Tests/Cache/CacheTraitTest.php b/src/Symfony/Contracts/Tests/Cache/CacheTraitTest.php
index 5134a9339f..f77d103c93 100644
--- a/src/Symfony/Contracts/Tests/Cache/CacheTraitTest.php
+++ b/src/Symfony/Contracts/Tests/Cache/CacheTraitTest.php
@@ -34,7 +34,7 @@ class CacheTraitTest extends TestCase
             ->with('computed data');
 
         $cache = $this->getMockBuilder(TestPool::class)
-            ->setMethods(array('getItem', 'save'))
+            ->setMethods(['getItem', 'save'])
             ->getMock();
         $cache->expects($this->once())
             ->method('getItem')
@@ -60,7 +60,7 @@ class CacheTraitTest extends TestCase
             ->method('set');
 
         $cache = $this->getMockBuilder(TestPool::class)
-            ->setMethods(array('getItem', 'save'))
+            ->setMethods(['getItem', 'save'])
             ->getMock();
 
         $cache->expects($this->once())
@@ -91,7 +91,7 @@ class CacheTraitTest extends TestCase
             ->with('computed data');
 
         $cache = $this->getMockBuilder(TestPool::class)
-            ->setMethods(array('getItem', 'save'))
+            ->setMethods(['getItem', 'save'])
             ->getMock();
 
         $cache->expects($this->once())
@@ -111,7 +111,7 @@ class CacheTraitTest extends TestCase
     public function testExceptionOnNegativeBeta()
     {
         $cache = $this->getMockBuilder(TestPool::class)
-            ->setMethods(array('getItem', 'save'))
+            ->setMethods(['getItem', 'save'])
             ->getMock();
 
         $callback = function (CacheItemInterface $item) {
@@ -135,7 +135,7 @@ class TestPool implements CacheItemPoolInterface
     {
     }
 
-    public function deleteItems(array $keys = array())
+    public function deleteItems(array $keys = [])
     {
     }
 
@@ -143,7 +143,7 @@ class TestPool implements CacheItemPoolInterface
     {
     }
 
-    public function getItems(array $key = array())
+    public function getItems(array $key = [])
     {
     }
 
diff --git a/src/Symfony/Contracts/Tests/Service/ServiceLocatorTest.php b/src/Symfony/Contracts/Tests/Service/ServiceLocatorTest.php
index 265af909df..22487a8992 100644
--- a/src/Symfony/Contracts/Tests/Service/ServiceLocatorTest.php
+++ b/src/Symfony/Contracts/Tests/Service/ServiceLocatorTest.php
@@ -26,11 +26,11 @@ class ServiceLocatorTest extends TestCase
 
     public function testHas()
     {
-        $locator = $this->getServiceLocator(array(
+        $locator = $this->getServiceLocator([
             'foo' => function () { return 'bar'; },
             'bar' => function () { return 'baz'; },
             function () { return 'dummy'; },
-        ));
+        ]);
 
         $this->assertTrue($locator->has('foo'));
         $this->assertTrue($locator->has('bar'));
@@ -39,10 +39,10 @@ class ServiceLocatorTest extends TestCase
 
     public function testGet()
     {
-        $locator = $this->getServiceLocator(array(
+        $locator = $this->getServiceLocator([
             'foo' => function () { return 'bar'; },
             'bar' => function () { return 'baz'; },
-        ));
+        ]);
 
         $this->assertSame('bar', $locator->get('foo'));
         $this->assertSame('baz', $locator->get('bar'));
@@ -51,13 +51,13 @@ class ServiceLocatorTest extends TestCase
     public function testGetDoesNotMemoize()
     {
         $i = 0;
-        $locator = $this->getServiceLocator(array(
+        $locator = $this->getServiceLocator([
             'foo' => function () use (&$i) {
                 ++$i;
 
                 return 'bar';
             },
-        ));
+        ]);
 
         $this->assertSame('bar', $locator->get('foo'));
         $this->assertSame('bar', $locator->get('foo'));
@@ -70,9 +70,9 @@ class ServiceLocatorTest extends TestCase
      */
     public function testThrowsOnUndefinedInternalService()
     {
-        $locator = $this->getServiceLocator(array(
+        $locator = $this->getServiceLocator([
             'foo' => function () use (&$locator) { return $locator->get('bar'); },
-        ));
+        ]);
 
         $locator->get('foo');
     }
@@ -83,11 +83,11 @@ class ServiceLocatorTest extends TestCase
      */
     public function testThrowsOnCircularReference()
     {
-        $locator = $this->getServiceLocator(array(
+        $locator = $this->getServiceLocator([
             'foo' => function () use (&$locator) { return $locator->get('bar'); },
             'bar' => function () use (&$locator) { return $locator->get('baz'); },
             'baz' => function () use (&$locator) { return $locator->get('bar'); },
-        ));
+        ]);
 
         $locator->get('foo');
     }
diff --git a/src/Symfony/Contracts/Tests/Service/ServiceSubscriberTraitTest.php b/src/Symfony/Contracts/Tests/Service/ServiceSubscriberTraitTest.php
index c7742c65d4..344bba8772 100644
--- a/src/Symfony/Contracts/Tests/Service/ServiceSubscriberTraitTest.php
+++ b/src/Symfony/Contracts/Tests/Service/ServiceSubscriberTraitTest.php
@@ -21,14 +21,14 @@ class ServiceSubscriberTraitTest extends TestCase
 {
     public function testMethodsOnParentsAndChildrenAreIgnoredInGetSubscribedServices()
     {
-        $expected = array(TestService::class.'::aService' => '?Symfony\Contracts\Tests\Service\Service2');
+        $expected = [TestService::class.'::aService' => '?Symfony\Contracts\Tests\Service\Service2'];
 
         $this->assertEquals($expected, ChildTestService::getSubscribedServices());
     }
 
     public function testSetContainerIsCalledOnParent()
     {
-        $container = new class(array()) implements ContainerInterface {
+        $container = new class([]) implements ContainerInterface {
             use ServiceLocatorTrait;
         };
 
diff --git a/src/Symfony/Contracts/Tests/Translation/TranslatorTest.php b/src/Symfony/Contracts/Tests/Translation/TranslatorTest.php
index a3b67dfe5e..ac5f9c7aeb 100644
--- a/src/Symfony/Contracts/Tests/Translation/TranslatorTest.php
+++ b/src/Symfony/Contracts/Tests/Translation/TranslatorTest.php
@@ -55,7 +55,7 @@ class TranslatorTest extends TestCase
         $translator = $this->getTranslator();
         $translator->setLocale('en');
 
-        $this->assertEquals($expected, $translator->trans($id, array('%count%' => $number)));
+        $this->assertEquals($expected, $translator->trans($id, ['%count%' => $number]));
     }
 
     /**
@@ -67,7 +67,7 @@ class TranslatorTest extends TestCase
 
         $translator = $this->getTranslator();
 
-        $this->assertEquals($expected, $translator->trans($id, array('%count%' => $number)));
+        $this->assertEquals($expected, $translator->trans($id, ['%count%' => $number]));
     }
 
     public function testGetSetLocale()
@@ -94,24 +94,24 @@ class TranslatorTest extends TestCase
 
     public function getTransTests()
     {
-        return array(
-            array('Symfony is great!', 'Symfony is great!', array()),
-            array('Symfony is awesome!', 'Symfony is %what%!', array('%what%' => 'awesome')),
-        );
+        return [
+            ['Symfony is great!', 'Symfony is great!', []],
+            ['Symfony is awesome!', 'Symfony is %what%!', ['%what%' => 'awesome']],
+        ];
     }
 
     public function getTransChoiceTests()
     {
-        return array(
-            array('There are no apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 0),
-            array('There is one apple', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 1),
-            array('There are 10 apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 10),
-            array('There are 0 apples', 'There is 1 apple|There are %count% apples', 0),
-            array('There is 1 apple', 'There is 1 apple|There are %count% apples', 1),
-            array('There are 10 apples', 'There is 1 apple|There are %count% apples', 10),
+        return [
+            ['There are no apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 0],
+            ['There is one apple', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 1],
+            ['There are 10 apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 10],
+            ['There are 0 apples', 'There is 1 apple|There are %count% apples', 0],
+            ['There is 1 apple', 'There is 1 apple|There are %count% apples', 1],
+            ['There are 10 apples', 'There is 1 apple|There are %count% apples', 10],
             // custom validation messages may be coded with a fixed value
-            array('There are 2 apples', 'There are 2 apples', 2),
-        );
+            ['There are 2 apples', 'There are 2 apples', 2],
+        ];
     }
 
     /**
@@ -121,22 +121,22 @@ class TranslatorTest extends TestCase
     {
         $translator = $this->getTranslator();
 
-        $this->assertEquals($expected, $translator->trans($interval.' foo|[1,Inf[ bar', array('%count%' => $number)));
+        $this->assertEquals($expected, $translator->trans($interval.' foo|[1,Inf[ bar', ['%count%' => $number]));
     }
 
     public function getInternal()
     {
-        return array(
-            array('foo', 3, '{1,2, 3 ,4}'),
-            array('bar', 10, '{1,2, 3 ,4}'),
-            array('bar', 3, '[1,2]'),
-            array('foo', 1, '[1,2]'),
-            array('foo', 2, '[1,2]'),
-            array('bar', 1, ']1,2['),
-            array('bar', 2, ']1,2['),
-            array('foo', log(0), '[-Inf,2['),
-            array('foo', -log(0), '[-2,+Inf]'),
-        );
+        return [
+            ['foo', 3, '{1,2, 3 ,4}'],
+            ['bar', 10, '{1,2, 3 ,4}'],
+            ['bar', 3, '[1,2]'],
+            ['foo', 1, '[1,2]'],
+            ['foo', 2, '[1,2]'],
+            ['bar', 1, ']1,2['],
+            ['bar', 2, ']1,2['],
+            ['foo', log(0), '[-Inf,2['],
+            ['foo', -log(0), '[-2,+Inf]'],
+        ];
     }
 
     /**
@@ -146,14 +146,14 @@ class TranslatorTest extends TestCase
     {
         $translator = $this->getTranslator();
 
-        $this->assertEquals($expected, $translator->trans($id, array('%count%' => $number)));
+        $this->assertEquals($expected, $translator->trans($id, ['%count%' => $number]));
     }
 
     public function testReturnMessageIfExactlyOneStandardRuleIsGiven()
     {
         $translator = $this->getTranslator();
 
-        $this->assertEquals('There are two apples', $translator->trans('There are two apples', array('%count%' => 2)));
+        $this->assertEquals('There are two apples', $translator->trans('There are two apples', ['%count%' => 2]));
     }
 
     /**
@@ -164,98 +164,98 @@ class TranslatorTest extends TestCase
     {
         $translator = $this->getTranslator();
 
-        $translator->trans($id, array('%count%' => $number));
+        $translator->trans($id, ['%count%' => $number]);
     }
 
     public function getNonMatchingMessages()
     {
-        return array(
-            array('{0} There are no apples|{1} There is one apple', 2),
-            array('{1} There is one apple|]1,Inf] There are %count% apples', 0),
-            array('{1} There is one apple|]2,Inf] There are %count% apples', 2),
-            array('{0} There are no apples|There is one apple', 2),
-        );
+        return [
+            ['{0} There are no apples|{1} There is one apple', 2],
+            ['{1} There is one apple|]1,Inf] There are %count% apples', 0],
+            ['{1} There is one apple|]2,Inf] There are %count% apples', 2],
+            ['{0} There are no apples|There is one apple', 2],
+        ];
     }
 
     public function getChooseTests()
     {
-        return array(
-            array('There are no apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 0),
-            array('There are no apples', '{0}     There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 0),
-            array('There are no apples', '{0}There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 0),
+        return [
+            ['There are no apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 0],
+            ['There are no apples', '{0}     There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 0],
+            ['There are no apples', '{0}There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 0],
 
-            array('There is one apple', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 1),
+            ['There is one apple', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 1],
 
-            array('There are 10 apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 10),
-            array('There are 10 apples', '{0} There are no apples|{1} There is one apple|]1,Inf]There are %count% apples', 10),
-            array('There are 10 apples', '{0} There are no apples|{1} There is one apple|]1,Inf]     There are %count% apples', 10),
+            ['There are 10 apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 10],
+            ['There are 10 apples', '{0} There are no apples|{1} There is one apple|]1,Inf]There are %count% apples', 10],
+            ['There are 10 apples', '{0} There are no apples|{1} There is one apple|]1,Inf]     There are %count% apples', 10],
 
-            array('There are 0 apples', 'There is one apple|There are %count% apples', 0),
-            array('There is one apple', 'There is one apple|There are %count% apples', 1),
-            array('There are 10 apples', 'There is one apple|There are %count% apples', 10),
+            ['There are 0 apples', 'There is one apple|There are %count% apples', 0],
+            ['There is one apple', 'There is one apple|There are %count% apples', 1],
+            ['There are 10 apples', 'There is one apple|There are %count% apples', 10],
 
-            array('There are 0 apples', 'one: There is one apple|more: There are %count% apples', 0),
-            array('There is one apple', 'one: There is one apple|more: There are %count% apples', 1),
-            array('There are 10 apples', 'one: There is one apple|more: There are %count% apples', 10),
+            ['There are 0 apples', 'one: There is one apple|more: There are %count% apples', 0],
+            ['There is one apple', 'one: There is one apple|more: There are %count% apples', 1],
+            ['There are 10 apples', 'one: There is one apple|more: There are %count% apples', 10],
 
-            array('There are no apples', '{0} There are no apples|one: There is one apple|more: There are %count% apples', 0),
-            array('There is one apple', '{0} There are no apples|one: There is one apple|more: There are %count% apples', 1),
-            array('There are 10 apples', '{0} There are no apples|one: There is one apple|more: There are %count% apples', 10),
+            ['There are no apples', '{0} There are no apples|one: There is one apple|more: There are %count% apples', 0],
+            ['There is one apple', '{0} There are no apples|one: There is one apple|more: There are %count% apples', 1],
+            ['There are 10 apples', '{0} There are no apples|one: There is one apple|more: There are %count% apples', 10],
 
-            array('', '{0}|{1} There is one apple|]1,Inf] There are %count% apples', 0),
-            array('', '{0} There are no apples|{1}|]1,Inf] There are %count% apples', 1),
+            ['', '{0}|{1} There is one apple|]1,Inf] There are %count% apples', 0],
+            ['', '{0} There are no apples|{1}|]1,Inf] There are %count% apples', 1],
 
             // Indexed only tests which are Gettext PoFile* compatible strings.
-            array('There are 0 apples', 'There is one apple|There are %count% apples', 0),
-            array('There is one apple', 'There is one apple|There are %count% apples', 1),
-            array('There are 2 apples', 'There is one apple|There are %count% apples', 2),
+            ['There are 0 apples', 'There is one apple|There are %count% apples', 0],
+            ['There is one apple', 'There is one apple|There are %count% apples', 1],
+            ['There are 2 apples', 'There is one apple|There are %count% apples', 2],
 
             // Tests for float numbers
-            array('There is almost one apple', '{0} There are no apples|]0,1[ There is almost one apple|{1} There is one apple|[1,Inf] There is more than one apple', 0.7),
-            array('There is one apple', '{0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 1),
-            array('There is more than one apple', '{0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 1.7),
-            array('There are no apples', '{0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 0),
-            array('There are no apples', '{0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 0.0),
-            array('There are no apples', '{0.0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 0),
+            ['There is almost one apple', '{0} There are no apples|]0,1[ There is almost one apple|{1} There is one apple|[1,Inf] There is more than one apple', 0.7],
+            ['There is one apple', '{0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 1],
+            ['There is more than one apple', '{0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 1.7],
+            ['There are no apples', '{0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 0],
+            ['There are no apples', '{0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 0.0],
+            ['There are no apples', '{0.0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 0],
 
             // Test texts with new-lines
             // with double-quotes and \n in id & double-quotes and actual newlines in text
-            array("This is a text with a\n            new-line in it. Selector = 0.", '{0}This is a text with a
+            ["This is a text with a\n            new-line in it. Selector = 0.", '{0}This is a text with a
             new-line in it. Selector = 0.|{1}This is a text with a
             new-line in it. Selector = 1.|[1,Inf]This is a text with a
-            new-line in it. Selector > 1.', 0),
+            new-line in it. Selector > 1.', 0],
             // with double-quotes and \n in id and single-quotes and actual newlines in text
-            array("This is a text with a\n            new-line in it. Selector = 1.", '{0}This is a text with a
+            ["This is a text with a\n            new-line in it. Selector = 1.", '{0}This is a text with a
             new-line in it. Selector = 0.|{1}This is a text with a
             new-line in it. Selector = 1.|[1,Inf]This is a text with a
-            new-line in it. Selector > 1.', 1),
-            array("This is a text with a\n            new-line in it. Selector > 1.", '{0}This is a text with a
+            new-line in it. Selector > 1.', 1],
+            ["This is a text with a\n            new-line in it. Selector > 1.", '{0}This is a text with a
             new-line in it. Selector = 0.|{1}This is a text with a
             new-line in it. Selector = 1.|[1,Inf]This is a text with a
-            new-line in it. Selector > 1.', 5),
+            new-line in it. Selector > 1.', 5],
             // with double-quotes and id split accros lines
-            array('This is a text with a
+            ['This is a text with a
             new-line in it. Selector = 1.', '{0}This is a text with a
             new-line in it. Selector = 0.|{1}This is a text with a
             new-line in it. Selector = 1.|[1,Inf]This is a text with a
-            new-line in it. Selector > 1.', 1),
+            new-line in it. Selector > 1.', 1],
             // with single-quotes and id split accros lines
-            array('This is a text with a
+            ['This is a text with a
             new-line in it. Selector > 1.', '{0}This is a text with a
             new-line in it. Selector = 0.|{1}This is a text with a
             new-line in it. Selector = 1.|[1,Inf]This is a text with a
-            new-line in it. Selector > 1.', 5),
+            new-line in it. Selector > 1.', 5],
             // with single-quotes and \n in text
-            array('This is a text with a\nnew-line in it. Selector = 0.', '{0}This is a text with a\nnew-line in it. Selector = 0.|{1}This is a text with a\nnew-line in it. Selector = 1.|[1,Inf]This is a text with a\nnew-line in it. Selector > 1.', 0),
+            ['This is a text with a\nnew-line in it. Selector = 0.', '{0}This is a text with a\nnew-line in it. Selector = 0.|{1}This is a text with a\nnew-line in it. Selector = 1.|[1,Inf]This is a text with a\nnew-line in it. Selector > 1.', 0],
             // with double-quotes and id split accros lines
-            array("This is a text with a\nnew-line in it. Selector = 1.", "{0}This is a text with a\nnew-line in it. Selector = 0.|{1}This is a text with a\nnew-line in it. Selector = 1.|[1,Inf]This is a text with a\nnew-line in it. Selector > 1.", 1),
+            ["This is a text with a\nnew-line in it. Selector = 1.", "{0}This is a text with a\nnew-line in it. Selector = 0.|{1}This is a text with a\nnew-line in it. Selector = 1.|[1,Inf]This is a text with a\nnew-line in it. Selector > 1.", 1],
             // esacape pipe
-            array('This is a text with | in it. Selector = 0.', '{0}This is a text with || in it. Selector = 0.|{1}This is a text with || in it. Selector = 1.', 0),
+            ['This is a text with | in it. Selector = 0.', '{0}This is a text with || in it. Selector = 0.|{1}This is a text with || in it. Selector = 1.', 0],
             // Empty plural set (2 plural forms) from a .PO file
-            array('', '|', 1),
+            ['', '|', 1],
             // Empty plural set (3 plural forms) from a .PO file
-            array('', '||', 1),
-        );
+            ['', '||', 1],
+        ];
     }
 
     /**
@@ -285,13 +285,13 @@ class TranslatorTest extends TestCase
      */
     public function successLangcodes()
     {
-        return array(
-            array('1', array('ay', 'bo', 'cgg', 'dz', 'id', 'ja', 'jbo', 'ka', 'kk', 'km', 'ko', 'ky')),
-            array('2', array('nl', 'fr', 'en', 'de', 'de_GE', 'hy', 'hy_AM')),
-            array('3', array('be', 'bs', 'cs', 'hr')),
-            array('4', array('cy', 'mt', 'sl')),
-            array('6', array('ar')),
-        );
+        return [
+            ['1', ['ay', 'bo', 'cgg', 'dz', 'id', 'ja', 'jbo', 'ka', 'kk', 'km', 'ko', 'ky']],
+            ['2', ['nl', 'fr', 'en', 'de', 'de_GE', 'hy', 'hy_AM']],
+            ['3', ['be', 'bs', 'cs', 'hr']],
+            ['4', ['cy', 'mt', 'sl']],
+            ['6', ['ar']],
+        ];
     }
 
     /**
@@ -304,13 +304,13 @@ class TranslatorTest extends TestCase
      */
     public function failingLangcodes()
     {
-        return array(
-            array('1', array('fa')),
-            array('2', array('jbo')),
-            array('3', array('cbs')),
-            array('4', array('gd', 'kw')),
-            array('5', array('ga')),
-        );
+        return [
+            ['1', ['fa']],
+            ['2', ['jbo']],
+            ['3', ['cbs']],
+            ['4', ['gd', 'kw']],
+            ['5', ['ga']],
+        ];
     }
 
     /**
@@ -340,7 +340,7 @@ class TranslatorTest extends TestCase
             }
         };
 
-        $matrix = array();
+        $matrix = [];
         foreach ($langCodes as $langCode) {
             for ($count = 0; $count < 200; ++$count) {
                 $plural = $translator->getPluralizationRule($count, $langCode);
diff --git a/src/Symfony/Contracts/Translation/TranslatorInterface.php b/src/Symfony/Contracts/Translation/TranslatorInterface.php
index 2bdc415cbd..d867637370 100644
--- a/src/Symfony/Contracts/Translation/TranslatorInterface.php
+++ b/src/Symfony/Contracts/Translation/TranslatorInterface.php
@@ -61,5 +61,5 @@ interface TranslatorInterface
      *
      * @throws \InvalidArgumentException If the locale contains invalid characters
      */
-    public function trans($id, array $parameters = array(), $domain = null, $locale = null);
+    public function trans($id, array $parameters = [], $domain = null, $locale = null);
 }
diff --git a/src/Symfony/Contracts/Translation/TranslatorTrait.php b/src/Symfony/Contracts/Translation/TranslatorTrait.php
index 4e53fbd42c..c1021923c8 100644
--- a/src/Symfony/Contracts/Translation/TranslatorTrait.php
+++ b/src/Symfony/Contracts/Translation/TranslatorTrait.php
@@ -41,7 +41,7 @@ trait TranslatorTrait
     /**
      * {@inheritdoc}
      */
-    public function trans($id, array $parameters = array(), $domain = null, $locale = null)
+    public function trans($id, array $parameters = [], $domain = null, $locale = null)
     {
         $id = (string) $id;
 
@@ -52,7 +52,7 @@ trait TranslatorTrait
         $number = (float) $parameters['%count%'];
         $locale = (string) $locale ?: $this->getLocale();
 
-        $parts = array();
+        $parts = [];
         if (preg_match('/^\|++$/', $id)) {
             $parts = explode('|', $id);
         } elseif (preg_match_all('/(?:\|\||[^\|])++/', $id, $matches)) {
@@ -77,7 +77,7 @@ trait TranslatorTrait
 )\s*(?P.*?)$/xs
 EOF;
 
-        $standardRules = array();
+        $standardRules = [];
         foreach ($parts as $part) {
             $part = trim(str_replace('||', '|', $part));