diff --git a/best_practices/business-logic.rst b/best_practices/business-logic.rst index a6313ae4cbf..143e1f696a4 100644 --- a/best_practices/business-logic.rst +++ b/best_practices/business-logic.rst @@ -312,11 +312,11 @@ Then, enable the bundle in ``AppKernel.php``, but only for the ``dev`` and { public function registerBundles() { - $bundles = array( + $bundles = [ // ... - ); + ]; - if (in_array($this->getEnvironment(), array('dev', 'test'))) { + if (in_array($this->getEnvironment(), ['dev', 'test'])) { // ... $bundles[] = new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle(); } diff --git a/best_practices/controllers.rst b/best_practices/controllers.rst index 13beba910bd..2be1bf6f01e 100644 --- a/best_practices/controllers.rst +++ b/best_practices/controllers.rst @@ -108,9 +108,9 @@ for the homepage of our app:: ->getRepository(Post::class) ->findLatest(); - return $this->render('default/index.html.twig', array( + return $this->render('default/index.html.twig', [ 'posts' => $posts, - )); + ]); } } @@ -155,10 +155,10 @@ For example:: { $deleteForm = $this->createDeleteForm($post); - return $this->render('admin/post/show.html.twig', array( + return $this->render('admin/post/show.html.twig', [ 'post' => $post, 'delete_form' => $deleteForm->createView(), - )); + ]); } Normally, you'd expect a ``$id`` argument to ``showAction()``. Instead, by @@ -182,7 +182,7 @@ manually. In our application, we have this situation in ``CommentController``:: { $post = $this->getDoctrine() ->getRepository(Post::class) - ->findOneBy(array('slug' => $postSlug)); + ->findOneBy(['slug' => $postSlug]); if (!$post) { throw $this->createNotFoundException(); diff --git a/best_practices/forms.rst b/best_practices/forms.rst index 8c1233196af..5041e604d0d 100644 --- a/best_practices/forms.rst +++ b/best_practices/forms.rst @@ -42,9 +42,9 @@ form in its own PHP class:: public function configureOptions(OptionsResolver $resolver) { - $resolver->setDefaults(array( + $resolver->setDefaults([ 'data_class' => Post::class, - )); + ]); } } @@ -96,7 +96,7 @@ scope of that form:: { $builder // ... - ->add('save', SubmitType::class, array('label' => 'Create Post')) + ->add('save', SubmitType::class, ['label' => 'Create Post']) ; } @@ -123,10 +123,10 @@ some developers configure form buttons in the controller:: { $post = new Post(); $form = $this->createForm(PostType::class, $post); - $form->add('submit', SubmitType::class, array( + $form->add('submit', SubmitType::class, [ 'label' => 'Create', - 'attr' => array('class' => 'btn btn-default pull-right'), - )); + 'attr' => ['class' => 'btn btn-default pull-right'], + ]); // ... } @@ -215,7 +215,7 @@ Handling a form submit usually follows a similar template:: return $this->redirect($this->generateUrl( 'admin_post_show', - array('id' => $post->getId()) + ['id' => $post->getId()] )); } diff --git a/best_practices/security.rst b/best_practices/security.rst index 3e18057d02d..6eef4c6cf43 100644 --- a/best_practices/security.rst +++ b/best_practices/security.rst @@ -285,7 +285,7 @@ the same ``getAuthorEmail()`` logic you used above:: protected function supports($attribute, $subject) { - if (!in_array($attribute, array(self::CREATE, self::EDIT))) { + if (!in_array($attribute, [self::CREATE, self::EDIT])) { return false; } @@ -309,7 +309,7 @@ the same ``getAuthorEmail()`` logic you used above:: switch ($attribute) { case self::CREATE: // if the user is an admin, allow them to create new posts - if ($this->decisionManager->decide($token, array('ROLE_ADMIN'))) { + if ($this->decisionManager->decide($token, ['ROLE_ADMIN'])) { return true; } diff --git a/best_practices/templates.rst b/best_practices/templates.rst index 38a88f7610b..6d128aa5a13 100644 --- a/best_practices/templates.rst +++ b/best_practices/templates.rst @@ -122,11 +122,11 @@ class in the constructor of the Twig extension:: public function getFilters() { - return array( + return [ new TwigFilter( 'md2html', - array($this, 'markdownToHtml'), - array('is_safe' => array('html'), 'pre_escape' => 'html') + [$this, 'markdownToHtml'], + ['is_safe' => ['html'], 'pre_escape' => 'html'] ), ); } diff --git a/best_practices/tests.rst b/best_practices/tests.rst index aef317a5b4f..4a26ee7139c 100644 --- a/best_practices/tests.rst +++ b/best_practices/tests.rst @@ -49,14 +49,14 @@ A functional test like this is simple to implement thanks to public function urlProvider() { - return array( - array('/'), - array('/posts'), - array('/post/fixture-post-1'), - array('/blog/category/fixture-category'), - array('/archives'), + return [ + ['/'], + ['/posts'], + ['/post/fixture-post-1'], + ['/blog/category/fixture-category'], + ['/archives'], // ... - ); + ]; } } diff --git a/bundles.rst b/bundles.rst index a4677f8a1fd..43ccbb10111 100644 --- a/bundles.rst +++ b/bundles.rst @@ -39,7 +39,7 @@ the ``registerBundles()`` method of the ``AppKernel`` class:: // app/AppKernel.php public function registerBundles() { - $bundles = array( + $bundles = [ new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\SecurityBundle\SecurityBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), @@ -48,9 +48,9 @@ the ``registerBundles()`` method of the ``AppKernel`` class:: new Symfony\Bundle\DoctrineBundle\DoctrineBundle(), new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(), new AppBundle\AppBundle(), - ); + ]; - if (in_array($this->getEnvironment(), array('dev', 'test'))) { + if (in_array($this->getEnvironment(), ['dev', 'test'])) { $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle(); $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle(); $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle(); @@ -107,12 +107,12 @@ Now that you've created the bundle, enable it via the ``AppKernel`` class:: // app/AppKernel.php public function registerBundles() { - $bundles = array( + $bundles = [ // ... // register your bundle new Acme\TestBundle\AcmeTestBundle(), - ); + ]; // ... return $bundles; diff --git a/bundles/best_practices.rst b/bundles/best_practices.rst index 04e00f0ccfb..79607178c0f 100644 --- a/bundles/best_practices.rst +++ b/bundles/best_practices.rst @@ -232,10 +232,10 @@ following standardized instructions in your ``README.md`` file. { public function registerBundles() { - $bundles = array( + $bundles = [ // ... new \\(), - ); + ]; // ... } @@ -278,11 +278,11 @@ following standardized instructions in your ``README.md`` file. { public function registerBundles() { - $bundles = array( + $bundles = [ // ... new \\(), - ); + ]; // ... } diff --git a/bundles/configuration.rst b/bundles/configuration.rst index 2d5e830da5d..b7535d55c96 100644 --- a/bundles/configuration.rst +++ b/bundles/configuration.rst @@ -39,9 +39,9 @@ as integration of other related components: .. code-block:: php - $container->loadFromExtension('framework', array( + $container->loadFromExtension('framework', [ 'form' => true, - )); + ]); .. sidebar:: Using Parameters to Configure your Bundle @@ -91,10 +91,10 @@ allow users to configure it with some configuration that looks like this: .. code-block:: php // app/config/config.php - $container->loadFromExtension('acme_social', array( + $container->loadFromExtension('acme_social', [ 'client_id' => 123, 'client_secret' => 'your_secret', - )); + ]); The basic idea is that instead of having the user override individual parameters, you let the user configure just a few, specifically created, @@ -139,14 +139,14 @@ automatically converts XML and YAML to an array). For the configuration example in the previous section, the array passed to your ``load()`` method will look like this:: - array( - array( - 'twitter' => array( + [ + [ + 'twitter' => [ 'client_id' => 123, 'client_secret' => 'your_secret', - ), - ), - ) + ], + ], + ] Notice that this is an *array of arrays*, not just a single flat array of the configuration values. This is intentional, as it allows Symfony to parse @@ -154,21 +154,21 @@ several configuration resources. For example, if ``acme_social`` appears in another configuration file - say ``config_dev.yml`` - with different values beneath it, the incoming array might look like this:: - array( + [ // values from config.yml - array( - 'twitter' => array( + [ + 'twitter' => [ 'client_id' => 123, 'client_secret' => 'your_secret', - ), - ), + ], + ], // values from config_dev.yml - array( - 'twitter' => array( + [ + 'twitter' => [ 'client_id' => 456, - ), - ), - ) + ], + ], + ] The order of the two arrays depends on which one is set first. @@ -315,7 +315,7 @@ In your extension, you can load this and dynamically set its arguments:: public function load(array $configs, ContainerBuilder $container) { - $config = array(); + $config = []; // let resources override the previous set value foreach ($configs as $subConfig) { $config = array_merge($config, $subConfig); diff --git a/bundles/extension.rst b/bundles/extension.rst index 51b3e57abed..2daefd2fed6 100644 --- a/bundles/extension.rst +++ b/bundles/extension.rst @@ -157,17 +157,17 @@ class names:: // ... // this method can't compile classes that contain PHP annotations - $this->addClassesToCompile(array( + $this->addClassesToCompile([ UserManager::class, Slugger::class, // ... - )); + ]); // add here only classes that contain PHP annotations - $this->addAnnotatedClassesToCompile(array( + $this->addAnnotatedClassesToCompile([ 'AppBundle\\Controller\\DefaultController', // ... - )); + ]); } .. note:: @@ -186,15 +186,15 @@ The classes to compile can also be added using file path patterns:: { // ... - $this->addClassesToCompile(array( + $this->addClassesToCompile([ '**Bundle\\Manager\\', // ... - )); + ]); - $this->addAnnotatedClassesToCompile(array( + $this->addAnnotatedClassesToCompile([ '**Bundle\\Controller\\', // ... - )); + ]); } Patterns are transformed into the actual class namespaces using the classmap diff --git a/bundles/installation.rst b/bundles/installation.rst index 52adbe39fa4..c8f3e4ec1d5 100644 --- a/bundles/installation.rst +++ b/bundles/installation.rst @@ -61,10 +61,10 @@ The only thing you need to do now is register the bundle in ``AppKernel``:: public function registerBundles() { - $bundles = array( + $bundles = [ // ... new FOS\UserBundle\FOSUserBundle(), - ); + ]; // ... } @@ -85,11 +85,11 @@ and ``test`` environments, register the bundle in this way:: public function registerBundles() { - $bundles = array( + $bundles = [ // ... - ); + ]; - if (in_array($this->getEnvironment(), array('dev', 'test'))) { + if (in_array($this->getEnvironment(), ['dev', 'test'])) { $bundles[] = new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle(); } diff --git a/bundles/prepend_extension.rst b/bundles/prepend_extension.rst index 28610a27154..fb9d3e5d470 100644 --- a/bundles/prepend_extension.rst +++ b/bundles/prepend_extension.rst @@ -64,7 +64,7 @@ in case a specific other bundle is not registered:: // determine if AcmeGoodbyeBundle is registered if (!isset($bundles['AcmeGoodbyeBundle'])) { // disable AcmeGoodbyeBundle in bundles - $config = array('use_acme_goodbye' => false); + $config = ['use_acme_goodbye' => false]; foreach ($container->getExtensions() as $name => $extension) { switch ($name) { case 'acme_something': @@ -90,7 +90,7 @@ in case a specific other bundle is not registered:: // check if entity_manager_name is set in the "acme_hello" configuration if (isset($config['entity_manager_name'])) { // prepend the acme_something settings with the entity_manager_name - $config = array('entity_manager_name' => $config['entity_manager_name']); + $config = ['entity_manager_name' => $config['entity_manager_name']]; $container->prependExtensionConfig('acme_something', $config); } } @@ -135,15 +135,15 @@ The above would be the equivalent of writing the following into the .. code-block:: php // app/config/config.php - $container->loadFromExtension('acme_something', array( + $container->loadFromExtension('acme_something', [ // ... 'use_acme_goodbye' => false, 'entity_manager_name' => 'non_default', - )); - $container->loadFromExtension('acme_other', array( + ]); + $container->loadFromExtension('acme_other', [ // ... 'use_acme_goodbye' => false, - )); + ]); More than one Bundle using PrependExtensionInterface ---------------------------------------------------- diff --git a/bundles/remove.rst b/bundles/remove.rst index 644e8742310..0c27eacb68b 100644 --- a/bundles/remove.rst +++ b/bundles/remove.rst @@ -19,11 +19,11 @@ bundle is only registered in the development environment:: { public function registerBundles() { - $bundles = array( + $bundles = [ new Acme\DemoBundle\AcmeDemoBundle(), - ); + ]; - if (in_array($this->getEnvironment(), array('dev', 'test'))) { + if (in_array($this->getEnvironment(), ['dev', 'test'])) { // comment or remove this line: // $bundles[] = new Acme\DemoBundle\AcmeDemoBundle(); // ... diff --git a/components/asset.rst b/components/asset.rst index 7d26723e363..b550f2ed036 100644 --- a/components/asset.rst +++ b/components/asset.rst @@ -292,10 +292,10 @@ constructor:: use Symfony\Component\Asset\UrlPackage; // ... - $urls = array( + $urls = [ '//static1.example.com/images/', '//static2.example.com/images/', - ); + ]; $urlPackage = new UrlPackage($urls, new StaticVersionStrategy('v1')); echo $urlPackage->getUrl('/logo.png'); @@ -320,7 +320,7 @@ protocol-relative URLs for HTTPs requests, any base URL for HTTP requests):: // ... $urlPackage = new UrlPackage( - array('http://example.com/', 'https://example.com/'), + ['http://example.com/', 'https://example.com/'], new StaticVersionStrategy('v1'), new RequestStackContext($requestStack) ); @@ -350,10 +350,10 @@ they all have different base paths:: $defaultPackage = new Package($versionStrategy); - $namedPackages = array( + $namedPackages = [ 'img' => new UrlPackage('http://img.example.com/', $versionStrategy), 'doc' => new PathPackage('/somewhere/deep/for/documents', $versionStrategy), - ); + ]; $packages = new Packages($defaultPackage, $namedPackages); diff --git a/components/browser_kit.rst b/components/browser_kit.rst index bab848c82c5..81bd04f01b6 100644 --- a/components/browser_kit.rst +++ b/components/browser_kit.rst @@ -207,7 +207,7 @@ into the client constructor:: $cookieJar->set($cookie); // create a client and set the cookies - $client = new Client(array(), null, $cookieJar); + $client = new Client([], null, $cookieJar); // ... History diff --git a/components/cache.rst b/components/cache.rst index af113fa4592..4557988c726 100644 --- a/components/cache.rst +++ b/components/cache.rst @@ -89,20 +89,20 @@ Now you can create, retrieve, update and delete items using this object:: You can also work with multiple items at once:: - $cache->setMultiple(array( + $cache->setMultiple([ 'stats.products_count' => 4711, 'stats.users_count' => 1356, - )); + ]); - $stats = $cache->getMultiple(array( + $stats = $cache->getMultiple([ 'stats.products_count', 'stats.users_count', - )); + ]); - $cache->deleteMultiple(array( + $cache->deleteMultiple([ 'stats.products_count', 'stats.users_count', - )); + ]); Available Simple Cache (PSR-16) Classes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/components/cache/adapters/chain_adapter.rst b/components/cache/adapters/chain_adapter.rst index faff4dc6859..c1ad7630565 100644 --- a/components/cache/adapters/chain_adapter.rst +++ b/components/cache/adapters/chain_adapter.rst @@ -17,14 +17,14 @@ lifetime as its constructor arguments:: use Symfony\Component\Cache\Adapter\ApcuAdapter; - $cache = new ChainAdapter(array( + $cache = new ChainAdapter([ // The ordered list of adapters used to fetch cached items array $adapters, // The max lifetime of items propagated from lower adapters to upper ones $maxLifetime = 0 - )); + ]); .. note:: @@ -40,10 +40,10 @@ slowest storage engines, :class:`Symfony\\Component\\Cache\\Adapter\\ApcuAdapter use Symfony\Component\Cache\Adapter\ChainAdapter; use Symfony\Component\Cache\Adapter\FilesystemAdapter; - $cache = new ChainAdapter(array( + $cache = new ChainAdapter([ new ApcuAdapter(), new FilesystemAdapter(), - )); + ]); When calling this adapter's :method:`Symfony\\Component\\Cache\\ChainAdapter::prune` method, the call is delegated to all its compatible cache adapters. It is safe to mix both adapters @@ -54,10 +54,10 @@ incompatible adapters are silently ignored:: use Symfony\Component\Cache\Adapter\ChainAdapter; use Symfony\Component\Cache\Adapter\FilesystemAdapter; - $cache = new ChainAdapter(array( + $cache = new ChainAdapter([ new ApcuAdapter(), // does NOT implement PruneableInterface new FilesystemAdapter(), // DOES implement PruneableInterface - )); + ]); // prune will proxy the call to FilesystemAdapter while silently skipping ApcuAdapter $cache->prune(); diff --git a/components/cache/adapters/memcached_adapter.rst b/components/cache/adapters/memcached_adapter.rst index f5eb8935774..10f2b43aee2 100644 --- a/components/cache/adapters/memcached_adapter.rst +++ b/components/cache/adapters/memcached_adapter.rst @@ -61,12 +61,12 @@ helper method allows creating and configuring a `Memcached`_ class instance usin ); // pass an array of DSN strings to register multiple servers with the client - $client = MemcachedAdapter::createConnection(array( + $client = MemcachedAdapter::createConnection([ 'memcached://10.0.0.100', 'memcached://10.0.0.101', 'memcached://10.0.0.102', // etc... - )); + ]); .. versionadded:: 3.4 @@ -90,7 +90,7 @@ Below are common examples of valid DSNs showing a combination of available value use Symfony\Component\Cache\Adapter\MemcachedAdapter; - $client = MemcachedAdapter::createConnection(array( + $client = MemcachedAdapter::createConnection([ // hostname + port 'memcached://my.server.com:11211' @@ -105,7 +105,7 @@ Below are common examples of valid DSNs showing a combination of available value // socket instead of hostname/IP + weight 'memcached:///var/run/memcached.sock?weight=20' - )); + ]); Configure the Options --------------------- @@ -119,14 +119,14 @@ option names and their respective values:: $client = MemcachedAdapter::createConnection( // a DSN string or an array of DSN strings - array(), + [], // associative array of configuration options - array( + [ 'compression' => true, 'libketama_compatible' => true, 'serializer' => 'igbinary', - ) + ] ); Available Options diff --git a/components/cache/adapters/pdo_doctrine_dbal_adapter.rst b/components/cache/adapters/pdo_doctrine_dbal_adapter.rst index 6ba9eb8f0b4..bbbf9507e82 100644 --- a/components/cache/adapters/pdo_doctrine_dbal_adapter.rst +++ b/components/cache/adapters/pdo_doctrine_dbal_adapter.rst @@ -32,7 +32,7 @@ third, and forth parameters:: $defaultLifetime = 0, // an array of options for configuring the database table and connection - $options = array() + $options = [] ); .. tip:: diff --git a/components/cache/adapters/php_array_cache_adapter.rst b/components/cache/adapters/php_array_cache_adapter.rst index 22dc93b6a4f..dfc29f62002 100644 --- a/components/cache/adapters/php_array_cache_adapter.rst +++ b/components/cache/adapters/php_array_cache_adapter.rst @@ -14,10 +14,10 @@ that is optimized and preloaded into OPcache memory storage:: // somehow, decide it's time to warm up the cache! if ($needsWarmup) { // some static values - $values = array( + $values = [ 'stats.products_count' => 4711, 'stats.users_count' => 1356, - ); + ]; $cache = new PhpArrayAdapter( // single file where values are cached diff --git a/components/cache/adapters/php_files_adapter.rst b/components/cache/adapters/php_files_adapter.rst index 1b223f118bc..078394aeaf0 100644 --- a/components/cache/adapters/php_files_adapter.rst +++ b/components/cache/adapters/php_files_adapter.rst @@ -10,22 +10,22 @@ Php Files Cache Adapter Similarly to :ref:`Filesystem Adapter `, this cache implementation writes cache entries out to disk, but unlike the Filesystem cache adapter, the PHP Files cache adapter writes and reads back these cache files *as native PHP code*. -For example, caching the value ``array('my', 'cached', 'array')`` will write out a cache +For example, caching the value ``['my', 'cached', 'array']`` will write out a cache file similar to the following:: - 9223372036854775807, // the cache item contents - 1 => array ( + 1 => [ 0 => 'my', 1 => 'cached', 2 => 'array', - ), + ], - ); + ]; .. note:: diff --git a/components/cache/adapters/redis_adapter.rst b/components/cache/adapters/redis_adapter.rst index 93b6b48426c..f85fe2081ea 100644 --- a/components/cache/adapters/redis_adapter.rst +++ b/components/cache/adapters/redis_adapter.rst @@ -95,14 +95,14 @@ array of ``key => value`` pairs representing option names and their respective v 'redis://localhost:6379', // associative array of configuration options - array( + [ 'lazy' => false, 'persistent' => 0, 'persistent_id' => null, 'timeout' => 30, 'read_timeout' => 0, 'retry_interval' => 0, - ) + ] ); diff --git a/components/cache/cache_invalidation.rst b/components/cache/cache_invalidation.rst index 5639663c4d6..ab78d8e5b49 100644 --- a/components/cache/cache_invalidation.rst +++ b/components/cache/cache_invalidation.rst @@ -36,7 +36,7 @@ cache items, as returned by cache adapters:: // ... // add one or more tags $item->tag('tag_1'); - $item->tag(array('tag_2', 'tag_3')); + $item->tag(['tag_2', 'tag_3']); $cache->save($item); If ``$cache`` implements :class:`Symfony\\Component\\Cache\\Adapter\\TagAwareAdapterInterface`, @@ -44,7 +44,7 @@ you can invalidate the cached items by calling :method:`Symfony\\Component\\Cache\\Adapter\\TagAwareAdapterInterface::invalidateTags`:: // invalidate all items related to `tag_1` or `tag_3` - $cache->invalidateTags(array('tag_1', 'tag_3')); + $cache->invalidateTags(['tag_1', 'tag_3']); // if you know the cache key, you can also delete the item directly $cache->deleteItem('cache_key'); diff --git a/components/cache/cache_items.rst b/components/cache/cache_items.rst index 1e9a6f7a76e..a9c0246ea75 100644 --- a/components/cache/cache_items.rst +++ b/components/cache/cache_items.rst @@ -41,10 +41,10 @@ the data stored in the cache item:: $cache->save($productsCount); // storing an array - $productsCount->set(array( + $productsCount->set([ 'category1' => 4711, 'category2' => 2387, - )); + ]); $cache->save($productsCount); The key and the value of any given cache item can be obtained with the diff --git a/components/cache/cache_pools.rst b/components/cache/cache_pools.rst index 6d59229a37a..45bc9e38f53 100644 --- a/components/cache/cache_pools.rst +++ b/components/cache/cache_pools.rst @@ -51,10 +51,10 @@ value but an empty object which implements the :class:`Symfony\\Component\\Cache class. If you need to fetch several cache items simultaneously, use instead the -``getItems(array($key1, $key2, ...))`` method:: +``getItems([$key1, $key2, ...])`` method:: // ... - $stocks = $cache->getItems(array('AAPL', 'FB', 'GOOGL', 'MSFT')); + $stocks = $cache->getItems(['AAPL', 'FB', 'GOOGL', 'MSFT']); Again, if any of the keys doesn't represent a valid cache item, you won't get a ``null`` value but an empty ``CacheItem`` object. @@ -115,7 +115,7 @@ delete several cache items simultaneously (it returns ``true`` only if all the items have been deleted, even when any or some of them don't exist):: // ... - $areDeleted = $cache->deleteItems(array('category1', 'category2')); + $areDeleted = $cache->deleteItems(['category1', 'category2']); Finally, to remove all the cache items stored in the pool, use the ``Psr\\Cache\\CacheItemPoolInterface::clear`` method (which returns ``true`` @@ -190,13 +190,13 @@ silently ignored):: use Symfony\Component\Cache\Adapter\PdoAdapter; use Symfony\Component\Cache\Adapter\PhpFilesAdapter; - $cache = new ChainAdapter(array( + $cache = new ChainAdapter([ new ApcuAdapter(), // does NOT implement PruneableInterface new FilesystemAdapter(), // DOES implement PruneableInterface new PdoAdapter(), // DOES implement PruneableInterface new PhpFilesAdapter(), // DOES implement PruneableInterface // ... - )); + ]); // prune will proxy the call to PdoAdapter, FilesystemAdapter and PhpFilesAdapter, // while silently skipping ApcuAdapter diff --git a/components/class_loader/class_loader.rst b/components/class_loader/class_loader.rst index c6d37661a84..0562722ba58 100644 --- a/components/class_loader/class_loader.rst +++ b/components/class_loader/class_loader.rst @@ -41,29 +41,29 @@ your classes:: $loader->addPrefix('Symfony', __DIR__.'/vendor/symfony/symfony/src'); // registers several namespaces at once - $loader->addPrefixes(array( + $loader->addPrefixes([ 'Symfony' => __DIR__.'/../vendor/symfony/symfony/src', 'Monolog' => __DIR__.'/../vendor/monolog/monolog/src', - )); + ]); // registers a prefix for a class following the PEAR naming conventions $loader->addPrefix('Twig_', __DIR__.'/vendor/twig/twig/lib'); - $loader->addPrefixes(array( + $loader->addPrefixes([ 'Swift_' => __DIR__.'/vendor/swiftmailer/swiftmailer/lib/classes', 'Twig_' => __DIR__.'/vendor/twig/twig/lib', - )); + ]); Classes from a sub-namespace or a sub-hierarchy of `PEAR`_ classes can be looked for in a location list to ease the vendoring of a sub-set of classes for large projects:: - $loader->addPrefixes(array( + $loader->addPrefixes([ 'Doctrine\Common' => __DIR__.'/vendor/doctrine/common/lib', 'Doctrine\DBAL\Migrations' => __DIR__.'/vendor/doctrine/migrations/lib', 'Doctrine\DBAL' => __DIR__.'/vendor/doctrine/dbal/lib', 'Doctrine' => __DIR__.'/vendor/doctrine/orm/lib', - )); + ]); In this example, if you try to use a class in the ``Doctrine\Common`` namespace or one of its children, the autoloader will first look for the class under diff --git a/components/class_loader/class_map_generator.rst b/components/class_loader/class_map_generator.rst index c060cc71a72..9069e1df960 100644 --- a/components/class_loader/class_map_generator.rst +++ b/components/class_loader/class_map_generator.rst @@ -119,7 +119,7 @@ is the same as in the example above):: use Symfony\Component\ClassLoader\ClassMapGenerator; ClassMapGenerator::dump( - array(__DIR__.'/library/bar', __DIR__.'/library/foo'), + [__DIR__.'/library/bar', __DIR__.'/library/foo'], __DIR__.'/class_map.php' ); diff --git a/components/class_loader/map_class_loader.rst b/components/class_loader/map_class_loader.rst index e6e464e771e..5f2e8cfab7a 100644 --- a/components/class_loader/map_class_loader.rst +++ b/components/class_loader/map_class_loader.rst @@ -29,10 +29,10 @@ an instance of the ``MapClassLoader`` class:: require_once '/path/to/src/Symfony/Component/ClassLoader/MapClassLoader.php'; - $mapping = array( + $mapping = [ 'Foo' => '/path/to/Foo', 'Bar' => '/path/to/Bar', - ); + ]; $loader = new MapClassLoader($mapping); diff --git a/components/config/caching.rst b/components/config/caching.rst index 99cd4f6a2b1..9ef987a3165 100644 --- a/components/config/caching.rst +++ b/components/config/caching.rst @@ -35,7 +35,7 @@ should be regenerated:: // fill this with an array of 'users.yml' file paths $yamlUserFiles = ...; - $resources = array(); + $resources = []; foreach ($yamlUserFiles as $yamlUserFile) { // see the article "Loading resources" to diff --git a/components/config/definition.rst b/components/config/definition.rst index 27c0f2cb4d5..87119092e21 100644 --- a/components/config/definition.rst +++ b/components/config/definition.rst @@ -143,7 +143,7 @@ values:: $rootNode ->children() ->enumNode('delivery') - ->values(array('standard', 'expedited', 'priority')) + ->values(['standard', 'expedited', 'priority']) ->end() ->end() ; @@ -509,9 +509,9 @@ methods:: // is equivalent to $arrayNode - ->treatFalseLike(array('enabled' => false)) - ->treatTrueLike(array('enabled' => true)) - ->treatNullLike(array('enabled' => true)) + ->treatFalseLike(['enabled' => false]) + ->treatTrueLike(['enabled' => true]) + ->treatNullLike(['enabled' => true]) ->children() ->booleanNode('enabled') ->defaultFalse() @@ -742,7 +742,7 @@ By changing a string value into an associative array with ``name`` as the key:: ->arrayNode('connection') ->beforeNormalization() ->ifString() - ->then(function ($v) { return array('name' => $v); }) + ->then(function ($v) { return ['name' => $v]; }) ->end() ->children() ->scalarNode('name')->isRequired() @@ -767,7 +767,7 @@ The builder is used for adding advanced validation rules to node definitions, li ->scalarNode('driver') ->isRequired() ->validate() - ->ifNotInArray(array('mysql', 'sqlite', 'mssql')) + ->ifNotInArray(['mysql', 'sqlite', 'mssql']) ->thenInvalid('Invalid database driver %s') ->end() ->end() @@ -820,7 +820,7 @@ Otherwise the result is a clean array of configuration values:: file_get_contents(__DIR__.'/src/Matthias/config/config_extra.yml') ); - $configs = array($config, $extraConfig); + $configs = [$config, $extraConfig]; $processor = new Processor(); $databaseConfiguration = new DatabaseConfiguration(); diff --git a/components/config/resources.rst b/components/config/resources.rst index 9b464a6a0cc..db38b6f5e71 100644 --- a/components/config/resources.rst +++ b/components/config/resources.rst @@ -19,7 +19,7 @@ files. This can be done with the :class:`Symfony\\Component\\Config\\FileLocator use Symfony\Component\Config\FileLocator; - $configDirectories = array(__DIR__.'/app/config'); + $configDirectories = [__DIR__.'/app/config']; $fileLocator = new FileLocator($configDirectories); $yamlUserFiles = $fileLocator->locate('users.yml', null, false); @@ -84,7 +84,7 @@ the resource:: use Symfony\Component\Config\Loader\LoaderResolver; use Symfony\Component\Config\Loader\DelegatingLoader; - $loaderResolver = new LoaderResolver(array(new YamlUserLoader($fileLocator))); + $loaderResolver = new LoaderResolver([new YamlUserLoader($fileLocator)]); $delegatingLoader = new DelegatingLoader($loaderResolver); // YamlUserLoader is used to load this resource because it supports diff --git a/components/console/console_arguments.rst b/components/console/console_arguments.rst index 0757cf051fb..d49b34701d7 100644 --- a/components/console/console_arguments.rst +++ b/components/console/console_arguments.rst @@ -29,11 +29,11 @@ Have a look at the following command that has three options:: ->setName('demo:args') ->setDescription('Describe args behaviors') ->setDefinition( - new InputDefinition(array( + new InputDefinition([ new InputOption('foo', 'f'), new InputOption('bar', 'b', InputOption::VALUE_REQUIRED), new InputOption('cat', 'c', InputOption::VALUE_OPTIONAL), - )) + ]) ); } @@ -69,10 +69,10 @@ argument:: // ... - new InputDefinition(array( + new InputDefinition([ // ... new InputArgument('arg', InputArgument::OPTIONAL), - )); + ]); You might have to use the special ``--`` separator to separate options from arguments. Have a look at the fifth example in the following table where it diff --git a/components/console/helpers/formatterhelper.rst b/components/console/helpers/formatterhelper.rst index 98f2ad87f93..6c1a91af8c4 100644 --- a/components/console/helpers/formatterhelper.rst +++ b/components/console/helpers/formatterhelper.rst @@ -50,7 +50,7 @@ notice that the background is only as long as each individual line. Use the :method:`Symfony\\Component\\Console\\Helper\\FormatterHelper::formatBlock` to generate a block output:: - $errorMessages = array('Error!', 'Something went wrong'); + $errorMessages = ['Error!', 'Something went wrong']; $formattedBlock = $formatter->formatBlock($errorMessages, 'error'); $output->writeln($formattedBlock); diff --git a/components/console/helpers/processhelper.rst b/components/console/helpers/processhelper.rst index 7fa01ab884c..5fba8efc819 100644 --- a/components/console/helpers/processhelper.rst +++ b/components/console/helpers/processhelper.rst @@ -14,7 +14,7 @@ a very verbose verbosity (e.g. -vv):: use Symfony\Component\Process\Process; $helper = $this->getHelper('process'); - $process = new Process(array('figlet', 'Symfony')); + $process = new Process(['figlet', 'Symfony']); $helper->run($output, $process); @@ -43,7 +43,7 @@ There are three ways to use the process helper: * An array of arguments:: // ... - $helper->run($output, array('figlet', 'Symfony')); + $helper->run($output, ['figlet', 'Symfony']); .. note:: @@ -55,7 +55,7 @@ There are three ways to use the process helper: use Symfony\Component\Process\Process; // ... - $process = new Process(array('figlet', 'Symfony')); + $process = new Process(['figlet', 'Symfony']); $helper->run($output, $process); diff --git a/components/console/helpers/progressbar.rst b/components/console/helpers/progressbar.rst index aa1aa53ea21..a309885dc96 100644 --- a/components/console/helpers/progressbar.rst +++ b/components/console/helpers/progressbar.rst @@ -324,7 +324,7 @@ The ``setMessage()`` method accepts a second optional argument to set the value of the custom placeholders:: // ... - // $files = array('client-001/invoices.xml', '...'); + // $files = ['client-001/invoices.xml', '...']; foreach ($files as $filename) { $progressBar->setMessage('Importing invoices...'); $progressBar->setMessage($filename, 'filename'); diff --git a/components/console/helpers/questionhelper.rst b/components/console/helpers/questionhelper.rst index 95061082f75..279bd53c601 100644 --- a/components/console/helpers/questionhelper.rst +++ b/components/console/helpers/questionhelper.rst @@ -105,7 +105,7 @@ from a predefined list:: $helper = $this->getHelper('question'); $question = new ChoiceQuestion( 'Please select your favorite color (defaults to red)', - array('red', 'blue', 'yellow'), + ['red', 'blue', 'yellow'], 0 ); $question->setErrorMessage('Color %s is invalid.'); @@ -143,7 +143,7 @@ this use :method:`Symfony\\Component\\Console\\Question\\ChoiceQuestion::setMult $helper = $this->getHelper('question'); $question = new ChoiceQuestion( 'Please select your favorite colors (defaults to red and blue)', - array('red', 'blue', 'yellow'), + ['red', 'blue', 'yellow'], '0,1' ); $question->setMultiselect(true); @@ -172,7 +172,7 @@ will be autocompleted as the user types:: // ... $helper = $this->getHelper('question'); - $bundles = array('AcmeDemoBundle', 'AcmeBlogBundle', 'AcmeStoreBundle'); + $bundles = ['AcmeDemoBundle', 'AcmeBlogBundle', 'AcmeStoreBundle']; $question = new Question('Please enter the name of a bundle', 'FooBundle'); $question->setAutocompleterValues($bundles); @@ -355,17 +355,17 @@ from the command line, you need to set the inputs that the command expects:: $commandTester = new CommandTester($command); // Equals to a user inputting "Test" and hitting ENTER - $commandTester->setInputs(array('Test')); + $commandTester->setInputs(['Test']); // Equals to a user inputting "This", "That" and hitting ENTER // This can be used for answering two separated questions for instance - $commandTester->setInputs(array('This', 'That')); + $commandTester->setInputs(['This', 'That']); // For simulating a positive answer to a confirmation question, adding an // additional input saying "yes" will work - $commandTester->setInputs(array('yes')); + $commandTester->setInputs(['yes']); - $commandTester->execute(array('command' => $command->getName())); + $commandTester->execute(['command' => $command->getName()]); // $this->assertRegExp('/.../', $commandTester->getDisplay()); } diff --git a/components/console/helpers/table.rst b/components/console/helpers/table.rst index ec532ab4560..fd242981f1f 100644 --- a/components/console/helpers/table.rst +++ b/components/console/helpers/table.rst @@ -32,13 +32,13 @@ set the headers, set the rows and then render the table:: { $table = new Table($output); $table - ->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'], + ]) ; $table->render(); } @@ -49,13 +49,13 @@ You can add a table separator anywhere in the output by passing an instance of use Symfony\Component\Console\Helper\TableSeparator; - $table->setRows(array( - array('99921-58-10-7', 'Divine Comedy', 'Dante Alighieri'), - array('9971-5-0210-0', 'A Tale of Two Cities', 'Charles Dickens'), + $table->setRows([ + ['99921-58-10-7', 'Divine Comedy', 'Dante Alighieri'], + ['9971-5-0210-0', 'A Tale of Two Cities', 'Charles Dickens'], new TableSeparator(), - 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'), - )); + ['960-425-059-0', 'The Lord of the Rings', 'J. R. R. Tolkien'], + ['80-902734-1-6', 'And Then There Were None', 'Agatha Christie'], + ]); .. code-block:: terminal @@ -74,7 +74,7 @@ contents. Use the :method:`Symfony\\Component\\Console\\Helper\\Table::setColumn method to set the column widths explicitly:: // ... - $table->setColumnWidths(array(10, 0, 30)); + $table->setColumnWidths([10, 0, 30]); $table->render(); In this example, the first column width will be ``10``, the last column width @@ -197,12 +197,12 @@ To make a table cell that spans multiple columns you can use a :class:`Symfony\\ $table = new Table($output); $table - ->setHeaders(array('ISBN', 'Title', 'Author')) - ->setRows(array( - array('99921-58-10-7', 'Divine Comedy', 'Dante Alighieri'), + ->setHeaders(['ISBN', 'Title', 'Author']) + ->setRows([ + ['99921-58-10-7', 'Divine Comedy', 'Dante Alighieri'], new TableSeparator(), - array(new TableCell('This value spans 3 columns.', array('colspan' => 3))), - )) + [new TableCell('This value spans 3 columns.', ['colspan' => 3])], + ]) ; $table->render(); @@ -223,9 +223,9 @@ This results in: You can create a multiple-line page title using a header cell that spans the entire table width:: - $table->setHeaders(array( - array(new TableCell('Main table title', array('colspan' => 3))), - array('ISBN', 'Title', 'Author'), + $table->setHeaders([ + [new TableCell('Main table title', ['colspan' => 3])], + ['ISBN', 'Title', 'Author'], )) // ... @@ -248,15 +248,15 @@ In a similar way you can span multiple rows:: $table = new Table($output); $table - ->setHeaders(array('ISBN', 'Title', 'Author')) - ->setRows(array( - array( + ->setHeaders(['ISBN', 'Title', 'Author']) + ->setRows([ + [ '978-0521567817', 'De Monarchia', - new TableCell("Dante Alighieri\nspans multiple rows", array('rowspan' => 2)), - ), - array('978-0804169127', 'Divine Comedy'), - )) + new TableCell("Dante Alighieri\nspans multiple rows", ['rowspan' => 2]), + ], + ['978-0804169127', 'Divine Comedy'], + ]) ; $table->render(); diff --git a/components/console/logger.rst b/components/console/logger.rst index e38438664f9..3d129f7aa3b 100644 --- a/components/console/logger.rst +++ b/components/console/logger.rst @@ -83,10 +83,11 @@ constructor:: use Psr\Log\LogLevel; // ... - $verbosityLevelMap = array( + $verbosityLevelMap = [ LogLevel::NOTICE => OutputInterface::VERBOSITY_NORMAL, LogLevel::INFO => OutputInterface::VERBOSITY_NORMAL, - ); + ]; + $logger = new ConsoleLogger($output, $verbosityLevelMap); Color @@ -97,11 +98,12 @@ level. This behavior is configurable through the third parameter of the constructor:: // ... - $formatLevelMap = array( + $formatLevelMap = [ LogLevel::CRITICAL => ConsoleLogger::ERROR, LogLevel::DEBUG => ConsoleLogger::INFO, - ); - $logger = new ConsoleLogger($output, array(), $formatLevelMap); + ]; + + $logger = new ConsoleLogger($output, [], $formatLevelMap); Errors ------ diff --git a/components/dependency_injection.rst b/components/dependency_injection.rst index 5c979c94b96..5023314048d 100644 --- a/components/dependency_injection.rst +++ b/components/dependency_injection.rst @@ -159,7 +159,7 @@ If you do want to though then the container can call the setter method:: $containerBuilder ->register('newsletter_manager', 'NewsletterManager') - ->addMethodCall('setMailer', array(new Reference('mailer'))); + ->addMethodCall('setMailer', [new Reference('mailer')]); You could then get your ``newsletter_manager`` service from the container like this:: @@ -300,7 +300,7 @@ config files: $container ->register('newsletter_manager', 'NewsletterManager') - ->addMethodCall('setMailer', array(new Reference('mailer'))); + ->addMethodCall('setMailer', [new Reference('mailer')]); Learn More ---------- diff --git a/components/dependency_injection/compilation.rst b/components/dependency_injection/compilation.rst index 8b689b7fcae..bd26ddf7521 100644 --- a/components/dependency_injection/compilation.rst +++ b/components/dependency_injection/compilation.rst @@ -146,12 +146,12 @@ that was loaded into the container. You are only loading a single config file in the above example but it will still be within an array. The array will look like this:: - array( - array( + [ + [ 'foo' => 'fooValue', 'bar' => 'barValue', - ), - ) + ], + ] Whilst you can manually manage merging the different files, it is much better to use :doc:`the Config component ` to @@ -490,7 +490,7 @@ dump it:: $dumper = new PhpDumper($containerBuilder); file_put_contents( $file, - $dumper->dump(array('class' => 'MyCachedContainer')) + $dumper->dump(['class' => 'MyCachedContainer']) ); } @@ -523,7 +523,7 @@ application:: $dumper = new PhpDumper($containerBuilder); file_put_contents( $file, - $dumper->dump(array('class' => 'MyCachedContainer')) + $dumper->dump(['class' => 'MyCachedContainer']) ); } } @@ -556,7 +556,7 @@ for these resources and use them as metadata for the cache:: $dumper = new PhpDumper($containerBuilder); $containerConfigCache->write( - $dumper->dump(array('class' => 'MyCachedContainer')), + $dumper->dump(['class' => 'MyCachedContainer']), $containerBuilder->getResources() ); } diff --git a/components/dom_crawler.rst b/components/dom_crawler.rst index 4288d31d97a..0fa5db13101 100644 --- a/components/dom_crawler.rst +++ b/components/dom_crawler.rst @@ -207,7 +207,7 @@ Extract attribute and/or node values from the list of nodes:: $attributes = $crawler ->filterXpath('//body/p') - ->extract(array('_text', 'class')) + ->extract(['_text', 'class']) ; .. note:: @@ -270,7 +270,7 @@ and :phpclass:`DOMNode` objects:: $crawler->addDocument($domDocument); $crawler->addNodeList($nodeList); - $crawler->addNodes(array($node)); + $crawler->addNodes([$node]); $crawler->addNode($node); $crawler->add($domDocument); @@ -428,9 +428,9 @@ form that the button lives in:: $crawler->filter('.form-vertical')->form(); // or "fill" the form fields with data - $form = $crawler->selectButton('my-super-button')->form(array( + $form = $crawler->selectButton('my-super-button')->form([ 'name' => 'Ryan', - )); + ]); The :class:`Symfony\\Component\\DomCrawler\\Form` object has lots of very useful methods for working with forms:: @@ -454,10 +454,10 @@ attribute followed by a query string of all of the form's values. You can virtually set and get values on the form:: // sets values on the form internally - $form->setValues(array( + $form->setValues([ 'registration[username]' => 'symfonyfan', 'registration[terms]' => 1, - )); + ]); // gets back an array of values - in the "flat" array like above $values = $form->getValues(); @@ -477,13 +477,13 @@ To work with multi-dimensional fields:: Pass an array of values:: // sets a single field - $form->setValues(array('multi' => array('value'))); + $form->setValues(['multi' => ['value']]); // sets multiple fields at once - $form->setValues(array('multi' => array( + $form->setValues(['multi' => [ 1 => 'value', 'dimensional' => 'an other value', - ))); + ]]); This is great, but it gets better! The ``Form`` object allows you to interact with your form like a browser, selecting radio values, ticking checkboxes, @@ -499,7 +499,7 @@ and uploading files:: $form['registration[birthday][year]']->select(1984); // selects many options from a "multiple" select - $form['registration[interests]']->select(array('symfony', 'cookies')); + $form['registration[interests]']->select(['symfony', 'cookies']); // fakes a file upload $form['registration[photo]']->upload('/path/to/lucas.jpg'); diff --git a/components/event_dispatcher.rst b/components/event_dispatcher.rst index ef5647bb4a1..077807710a7 100644 --- a/components/event_dispatcher.rst +++ b/components/event_dispatcher.rst @@ -141,7 +141,7 @@ A call to the dispatcher's ``addListener()`` method associates any valid PHP callable to an event:: $listener = new AcmeListener(); - $dispatcher->addListener('acme.foo.action', array($listener, 'onFooAction')); + $dispatcher->addListener('acme.foo.action', [$listener, 'onFooAction']); The ``addListener()`` method takes up to three arguments: @@ -214,10 +214,10 @@ determine which instance is passed. // registers an event listener $containerBuilder->register('listener_service_id', \AcmeListener::class) - ->addTag('kernel.event_listener', array( + ->addTag('kernel.event_listener', [ 'event' => 'acme.foo.action', 'method' => 'onFooAction', - )); + ]); // registers an event subscriber $containerBuilder->register('subscriber_service_id', \AcmeSubscriber::class) @@ -344,13 +344,13 @@ Take the following example of a subscriber that subscribes to the { public static function getSubscribedEvents() { - return array( - KernelEvents::RESPONSE => array( - array('onKernelResponsePre', 10), - array('onKernelResponsePost', -10), - ), + return [ + KernelEvents::RESPONSE => [ + ['onKernelResponsePre', 10], + ['onKernelResponsePost', -10], + ], OrderPlacedEvent::NAME => 'onStoreOrder', - ); + ]; } public function onKernelResponsePre(FilterResponseEvent $event) diff --git a/components/event_dispatcher/container_aware_dispatcher.rst b/components/event_dispatcher/container_aware_dispatcher.rst index 4954f9a30c0..d894e5a9e5a 100644 --- a/components/event_dispatcher/container_aware_dispatcher.rst +++ b/components/event_dispatcher/container_aware_dispatcher.rst @@ -53,9 +53,9 @@ Adding Services To connect existing service definitions, use the :method:`Symfony\\Component\\EventDispatcher\\ContainerAwareEventDispatcher::addListenerService` -method where the ``$callback`` is an array of ``array($serviceId, $methodName)``:: +method where the ``$callback`` is an array of ``[$serviceId, $methodName]``:: - $dispatcher->addListenerService($eventName, array('foo', 'logListener')); + $dispatcher->addListenerService($eventName, ['foo', 'logListener']); Adding Subscriber Services ~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -81,12 +81,12 @@ The ``EventSubscriberInterface`` is exactly as you would expect:: { public static function getSubscribedEvents() { - return array( - KernelEvents::RESPONSE => array( - array('onKernelResponsePre', 10), - array('onKernelResponsePost', 0), + return [ + KernelEvents::RESPONSE => [ + ['onKernelResponsePre', 10], + ['onKernelResponsePost', 0], ), - 'store.order' => array('onStoreOrder', 0), + 'store.order' => ['onStoreOrder', 0], ); } diff --git a/components/event_dispatcher/generic_event.rst b/components/event_dispatcher/generic_event.rst index 23d37f4de9c..42efd41b902 100644 --- a/components/event_dispatcher/generic_event.rst +++ b/components/event_dispatcher/generic_event.rst @@ -72,7 +72,7 @@ access the event arguments:: $event = new GenericEvent( $subject, - array('type' => 'foo', 'counter' => 0) + ['type' => 'foo', 'counter' => 0] ); $dispatcher->dispatch('foo', $event); @@ -92,7 +92,7 @@ Filtering data:: use Symfony\Component\EventDispatcher\GenericEvent; - $event = new GenericEvent($subject, array('data' => 'Foo')); + $event = new GenericEvent($subject, ['data' => 'Foo']); $dispatcher->dispatch('foo', $event); class FooListener diff --git a/components/expression_language.rst b/components/expression_language.rst index 66cdac8f63f..1e75bdeb78f 100644 --- a/components/expression_language.rst +++ b/components/expression_language.rst @@ -101,9 +101,9 @@ PHP type (including objects):: var_dump($expressionLanguage->evaluate( 'fruit.variety', - array( + [ 'fruit' => $apple, - ) + ] )); This will print "Honeycrisp". For more information, see the :doc:`/components/expression_language/syntax` diff --git a/components/expression_language/ast.rst b/components/expression_language/ast.rst index ac1e2b62057..0f15c20647a 100644 --- a/components/expression_language/ast.rst +++ b/components/expression_language/ast.rst @@ -21,7 +21,7 @@ method after parsing any expression to get its AST:: use Symfony\Component\ExpressionLanguage\ExpressionLanguage; $ast = (new ExpressionLanguage()) - ->parse('1 + 2', array()) + ->parse('1 + 2', []) ->getNodes() ; @@ -41,7 +41,7 @@ method to turn the AST into an array:: // ... $astAsArray = (new ExpressionLanguage()) - ->parse('1 + 2', array()) + ->parse('1 + 2', []) ->getNodes() ->toArray() ; diff --git a/components/expression_language/caching.rst b/components/expression_language/caching.rst index 5bfe6ac38d4..361446a0645 100644 --- a/components/expression_language/caching.rst +++ b/components/expression_language/caching.rst @@ -58,7 +58,7 @@ Both ``evaluate()`` and ``compile()`` can handle ``ParsedExpression`` and // ... // the parse() method returns a ParsedExpression - $expression = $expressionLanguage->parse('1 + 4', array()); + $expression = $expressionLanguage->parse('1 + 4', []); var_dump($expressionLanguage->evaluate($expression)); // prints 5 @@ -69,7 +69,7 @@ Both ``evaluate()`` and ``compile()`` can handle ``ParsedExpression`` and $expression = new SerializedParsedExpression( '1 + 4', - serialize($expressionLanguage->parse('1 + 4', array())->getNodes()) + serialize($expressionLanguage->parse('1 + 4', [])->getNodes()) ); var_dump($expressionLanguage->evaluate($expression)); // prints 5 diff --git a/components/expression_language/extending.rst b/components/expression_language/extending.rst index 61a7846a767..ec98dcdc089 100644 --- a/components/expression_language/extending.rst +++ b/components/expression_language/extending.rst @@ -74,7 +74,7 @@ register:: { public function getFunctions() { - return array( + return [ new ExpressionFunction('lowercase', function ($str) { return sprintf('(is_string(%1$s) ? strtolower(%1$s) : %1$s)', $str); }, function ($arguments, $str) { @@ -84,7 +84,7 @@ register:: return strtolower($str); }), - ); + ]; } } @@ -111,10 +111,10 @@ or by using the second argument of the constructor:: use Symfony\Component\ExpressionLanguage\ExpressionLanguage; // using the constructor - $expressionLanguage = new ExpressionLanguage(null, array( + $expressionLanguage = new ExpressionLanguage(null, [ new StringExpressionLanguageProvider(), // ... - )); + ]); // using registerProvider() $expressionLanguage->registerProvider(new StringExpressionLanguageProvider()); @@ -129,7 +129,7 @@ or by using the second argument of the constructor:: class ExpressionLanguage extends BaseExpressionLanguage { - public function __construct(ParserCacheInterface $parser = null, array $providers = array()) + public function __construct(ParserCacheInterface $parser = null, array $providers = []) { // prepends the default provider to let users override it easily array_unshift($providers, new StringExpressionLanguageProvider()); diff --git a/components/expression_language/syntax.rst b/components/expression_language/syntax.rst index dae2c8c517a..4ba134fbf38 100644 --- a/components/expression_language/syntax.rst +++ b/components/expression_language/syntax.rst @@ -56,9 +56,9 @@ to JavaScript:: var_dump($expressionLanguage->evaluate( 'fruit.variety', - array( + [ 'fruit' => $apple, - ) + ] )); This will print out ``Honeycrisp``. @@ -73,7 +73,7 @@ JavaScript:: { public function sayHi($times) { - $greetings = array(); + $greetings = []; for ($i = 0; $i < $times; $i++) { $greetings[] = 'Hi'; } @@ -86,9 +86,9 @@ JavaScript:: var_dump($expressionLanguage->evaluate( 'robot.sayHi(3)', - array( + [ 'robot' => $robot, - ) + ] )); This will print out ``Hi Hi Hi!``. @@ -124,13 +124,13 @@ Working with Arrays If you pass an array into an expression, use the ``[]`` syntax to access array keys, similar to JavaScript:: - $data = array('life' => 10, 'universe' => 10, 'everything' => 22); + $data = ['life' => 10, 'universe' => 10, 'everything' => 22]; var_dump($expressionLanguage->evaluate( 'data["life"] + data["universe"] + data["everything"]', - array( + [ 'data' => $data, - ) + ] )); This will print out ``42``. @@ -154,11 +154,11 @@ For example:: var_dump($expressionLanguage->evaluate( 'life + universe + everything', - array( + [ 'life' => 10, 'universe' => 10, 'everything' => 22, - ) + ] )); This will print out ``42``. @@ -197,20 +197,20 @@ Examples:: $ret1 = $expressionLanguage->evaluate( 'life == everything', - array( + [ 'life' => 10, 'universe' => 10, 'everything' => 22, - ) + ] ); $ret2 = $expressionLanguage->evaluate( 'life > everything', - array( + [ 'life' => 10, 'universe' => 10, 'everything' => 22, - ) + ] ); Both variables would be set to ``false``. @@ -226,11 +226,11 @@ For example:: $ret = $expressionLanguage->evaluate( 'life < universe or life < everything', - array( + [ 'life' => 10, 'universe' => 10, 'everything' => 22, - ) + ] ); This ``$ret`` variable will be set to ``true``. @@ -244,10 +244,10 @@ For example:: var_dump($expressionLanguage->evaluate( 'firstName~" "~lastName', - array( + [ 'firstName' => 'Arthur', 'lastName' => 'Dent', - ) + ] )); This would print out ``Arthur Dent``. @@ -270,9 +270,9 @@ For example:: $inGroup = $expressionLanguage->evaluate( 'user.group in ["human_resources", "marketing"]', - array( + [ 'user' => $user, - ) + ] ); The ``$inGroup`` would evaluate to ``true``. @@ -294,9 +294,9 @@ For example:: $expressionLanguage->evaluate( 'user.age in 18..45', - array( + [ 'user' => $user, - ) + ] ); This will evaluate to ``true``, because ``user.age`` is in the range from diff --git a/components/filesystem.rst b/components/filesystem.rst index f7eeee53a6f..7cd61bb80cd 100644 --- a/components/filesystem.rst +++ b/components/filesystem.rst @@ -83,7 +83,7 @@ them is missing:: // if rabbit.jpg exists and bottle.png does not exist, returns false // non-absolute paths are relative to the directory where the running PHP script is stored - $fileSystem->exists(array('rabbit.jpg', 'bottle.png')); + $fileSystem->exists(['rabbit.jpg', 'bottle.png']); .. note:: @@ -178,7 +178,7 @@ remove :method:`Symfony\\Component\\Filesystem\\Filesystem::remove` deletes files, directories and symlinks:: - $fileSystem->remove(array('symlink', '/path/to/directory', 'activity.log')); + $fileSystem->remove(['symlink', '/path/to/directory', 'activity.log']); .. note:: diff --git a/components/finder.rst b/components/finder.rst index ba88ff908a6..c010915c1b5 100644 --- a/components/finder.rst +++ b/components/finder.rst @@ -96,7 +96,7 @@ Search in several locations by chaining calls to :method:`Symfony\\Component\\Finder\\Finder::in`:: // search inside *both* directories - $finder->in(array(__DIR__, '/elsewhere')); + $finder->in([__DIR__, '/elsewhere']); // same as above $finder->in(__DIR__)->in('/elsewhere'); diff --git a/components/form.rst b/components/form.rst index 1c9bf3f0491..348371dda94 100644 --- a/components/form.rst +++ b/components/form.rst @@ -201,16 +201,16 @@ to bootstrap or access Twig and add the :class:`Symfony\\Bridge\\Twig\\Extension // the path to your other templates $viewsDirectory = realpath(__DIR__.'/../views'); - $twig = new Environment(new FilesystemLoader(array( + $twig = new Environment(new FilesystemLoader([ $viewsDirectory, $vendorTwigBridgeDirectory.'/Resources/views/Form', - ))); - $formEngine = new TwigRendererEngine(array($defaultFormTheme), $twig); - $twig->addRuntimeLoader(new FactoryRuntimeLoader(array( + ])); + $formEngine = new TwigRendererEngine([$defaultFormTheme], $twig); + $twig->addRuntimeLoader(new FactoryRuntimeLoader([ FormRenderer::class => function () use ($formEngine, $csrfManager) { return new FormRenderer($formEngine, $csrfManager); }, - ))); + ])); // ... (see the previous CSRF Protection section for more information) @@ -405,9 +405,9 @@ is created from the form factory. ->add('dueDate', DateType::class) ->getForm(); - var_dump($twig->render('new.html.twig', array( + var_dump($twig->render('new.html.twig', [ 'form' => $form->createView(), - ))); + ])); .. code-block:: php-symfony @@ -431,9 +431,9 @@ is created from the form factory. ->add('dueDate', DateType::class) ->getForm(); - return $this->render('@AcmeTask/Default/new.html.twig', array( + return $this->render('@AcmeTask/Default/new.html.twig', [ 'form' => $form->createView(), - )); + ]); } } @@ -462,9 +462,9 @@ builder: // ... - $defaults = array( + $defaults = [ 'dueDate' => new \DateTime('tomorrow'), - ); + ]; $form = $formFactory->createBuilder(FormType::class, $defaults) ->add('task', TextType::class) @@ -484,9 +484,9 @@ builder: { public function newAction(Request $request) { - $defaults = array( + $defaults = [ 'dueDate' => new \DateTime('tomorrow'), - ); + ]; $form = $this->createFormBuilder($defaults) ->add('task', TextType::class) @@ -546,10 +546,10 @@ by ``handleRequest()`` to determine whether a form has been submitted): // ... - $formBuilder = $formFactory->createBuilder(FormType::class, null, array( + $formBuilder = $formFactory->createBuilder(FormType::class, null, [ 'action' => '/search', 'method' => 'GET', - )); + ]); // ... @@ -565,10 +565,10 @@ by ``handleRequest()`` to determine whether a form has been submitted): { public function searchAction() { - $formBuilder = $this->createFormBuilder(null, array( + $formBuilder = $this->createFormBuilder(null, [ 'action' => '/search', 'method' => 'GET', - )); + ]); // ... } @@ -680,15 +680,15 @@ option when building each field: use Symfony\Component\Form\Extension\Core\Type\DateType; $form = $formFactory->createBuilder() - ->add('task', TextType::class, array( + ->add('task', TextType::class, [ 'constraints' => new NotBlank(), - )) - ->add('dueDate', DateType::class, array( - 'constraints' => array( + ]) + ->add('dueDate', DateType::class, [ + 'constraints' => [ new NotBlank(), new Type(\DateTime::class), - ) - )) + ] + ]) ->getForm(); .. code-block:: php-symfony @@ -707,15 +707,15 @@ option when building each field: public function newAction(Request $request) { $form = $this->createFormBuilder() - ->add('task', TextType::class, array( + ->add('task', TextType::class, [ 'constraints' => new NotBlank(), - )) - ->add('dueDate', DateType::class, array( - 'constraints' => array( + ]) + ->add('dueDate', DateType::class, [ + 'constraints' => [ new NotBlank(), new Type(\DateTime::class), - ) - )) + ] + ]) ->getForm(); // ... } diff --git a/components/http_foundation.rst b/components/http_foundation.rst index 40ae2867c62..c0a2b7eae6b 100644 --- a/components/http_foundation.rst +++ b/components/http_foundation.rst @@ -53,7 +53,7 @@ which is almost equivalent to the more verbose, but also more flexible, $request = new Request( $_GET, $_POST, - array(), + [], $_COOKIE, $_FILES, $_SERVER @@ -167,7 +167,7 @@ When PHP imports the request query, it handles request parameters like // the query string is '?foo[bar]=baz' $request->query->get('foo'); - // returns array('bar' => 'baz') + // returns ['bar' => 'baz'] $request->query->get('foo[bar]'); // returns null @@ -211,7 +211,7 @@ a request:: $request = Request::create( '/hello-world', 'GET', - array('name' => 'Fabien') + ['name' => 'Fabien'] ); The :method:`Symfony\\Component\\HttpFoundation\\Request::create` method @@ -297,12 +297,12 @@ PHP callable that is able to create an instance of your ``Request`` class:: use Symfony\Component\HttpFoundation\Request; Request::setFactory(function ( - array $query = array(), - array $request = array(), - array $attributes = array(), - array $cookies = array(), - array $files = array(), - array $server = array(), + array $query = [], + array $request = [], + array $attributes = [], + array $cookies = [], + array $files = [], + array $server = [], $content = null ) { return new SpecialRequest( @@ -333,7 +333,7 @@ code, and an array of HTTP headers:: $response = new Response( 'Content', Response::HTTP_OK, - array('content-type' => 'text/html') + ['content-type' => 'text/html'] ); This information can also be manipulated after the Response object creation:: @@ -416,14 +416,14 @@ The :method:`Symfony\\Component\\HttpFoundation\\Response::setCache` method can be used to set the most commonly used cache information in one method call:: - $response->setCache(array( + $response->setCache([ 'etag' => 'abcdef', 'last_modified' => new \DateTime(), 'max_age' => 600, 's_maxage' => 600, 'private' => false, 'public' => true, - )); + ]); To check if the Response validators (``ETag``, ``Last-Modified``) match a conditional value specified in the client Request, use the @@ -573,9 +573,9 @@ right content and headers. A JSON response might look like this:: use Symfony\Component\HttpFoundation\Response; $response = new Response(); - $response->setContent(json_encode(array( + $response->setContent(json_encode([ 'data' => 123, - ))); + ])); $response->headers->set('Content-Type', 'application/json'); There is also a helpful :class:`Symfony\\Component\\HttpFoundation\\JsonResponse` @@ -584,12 +584,12 @@ class, which can make this even easier:: use Symfony\Component\HttpFoundation\JsonResponse; // if you know the data to send when creating the response - $response = new JsonResponse(array('data' => 123)); + $response = new JsonResponse(['data' => 123]); // if you don't know the data to send when creating the response $response = new JsonResponse(); // ... - $response->setData(array('data' => 123)); + $response->setData(['data' => 123]); // if the data to send is already encoded in JSON $response = JsonResponse::fromJsonString('{ "data": 123 }'); diff --git a/components/http_foundation/session_configuration.rst b/components/http_foundation/session_configuration.rst index 5ad54f7f132..f78afca76ee 100644 --- a/components/http_foundation/session_configuration.rst +++ b/components/http_foundation/session_configuration.rst @@ -45,7 +45,7 @@ Example usage:: use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage; use Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeFileSessionHandler; - $sessionStorage = new NativeSessionStorage(array(), new NativeFileSessionHandler()); + $sessionStorage = new NativeSessionStorage([], new NativeFileSessionHandler()); $session = new Session($sessionStorage); .. note:: @@ -84,7 +84,7 @@ Example usage:: use Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler; $pdo = new \PDO(...); - $sessionStorage = new NativeSessionStorage(array(), new PdoSessionHandler($pdo)); + $sessionStorage = new NativeSessionStorage([], new PdoSessionHandler($pdo)); $session = new Session($sessionStorage); Configuring PHP Sessions @@ -175,7 +175,7 @@ calculated by adding the PHP runtime configuration value in using the ``migrate()`` or ``invalidate()`` methods of the ``Session`` class. The initial cookie lifetime can be set by configuring ``NativeSessionStorage`` - using the ``setOptions(array('cookie_lifetime' => 1234))`` method. + using the ``setOptions(['cookie_lifetime' => 1234])`` method. .. note:: diff --git a/components/http_foundation/sessions.rst b/components/http_foundation/sessions.rst index 609bee58191..32f85109826 100644 --- a/components/http_foundation/sessions.rst +++ b/components/http_foundation/sessions.rst @@ -33,7 +33,7 @@ Quick example:: $session->getFlashBag()->add('notice', 'Profile updated'); // retrieve messages - foreach ($session->getFlashBag()->get('notice', array()) as $message) { + foreach ($session->getFlashBag()->get('notice', []) as $message) { echo '
'.$message.'
'; } @@ -219,12 +219,12 @@ data is an array, for example a set of tokens. In this case, managing the array becomes a burden because you have to retrieve the array then process it and store it again:: - $tokens = array( - 'tokens' => array( + $tokens = [ + 'tokens' => [ 'a' => 'a6c1e0b6', 'b' => 'f4a7b1f3', - ), - ); + ], + ]; So any processing of this might quickly get ugly, even simply adding a token to the array:: @@ -278,7 +278,7 @@ has a simple API Gets flashes by type and clears those flashes from the bag. :method:`Symfony\\Component\\HttpFoundation\\Session\\Flash\\FlashBagInterface::setAll` - Sets all flashes, accepts a keyed array of arrays ``type => array(messages)``. + Sets all flashes, accepts a keyed array of arrays ``type => [messages]``. :method:`Symfony\\Component\\HttpFoundation\\Session\\Flash\\FlashBagInterface::all` Gets all flashes (as a keyed array of arrays) and clears the flashes from the bag. @@ -324,12 +324,12 @@ Displaying the flash messages might look as follows. Simple, display one type of message:: // display warnings - foreach ($session->getFlashBag()->get('warning', array()) as $message) { + foreach ($session->getFlashBag()->get('warning', []) as $message) { echo '
'.$message.'
'; } // display errors - foreach ($session->getFlashBag()->get('error', array()) as $message) { + foreach ($session->getFlashBag()->get('error', []) as $message) { echo '
'.$message.'
'; } diff --git a/components/http_kernel.rst b/components/http_kernel.rst index df027ffb5d9..6e001d12f81 100644 --- a/components/http_kernel.rst +++ b/components/http_kernel.rst @@ -661,12 +661,12 @@ else that can be used to create a working example:: use Symfony\Component\Routing\RouteCollection; $routes = new RouteCollection(); - $routes->add('hello', new Route('/hello/{name}', array( + $routes->add('hello', new Route('/hello/{name}', [ '_controller' => function (Request $request) { return new Response( sprintf("Hello %s", $request->get('name')) ); - }) + }] )); $request = Request::createFromGlobals(); diff --git a/components/intl.rst b/components/intl.rst index 72af4cc99ec..05055221692 100644 --- a/components/intl.rst +++ b/components/intl.rst @@ -96,13 +96,13 @@ class:: use Symfony\Component\Intl\ResourceBundle\Compiler\BundleCompiler; $writer = new TextBundleWriter(); - $writer->write('/path/to/bundle', 'en', array( - 'Data' => array( + $writer->write('/path/to/bundle', 'en', [ + 'Data' => [ 'entry1', 'entry2', // ... - ), - )); + ], + ]); $compiler = new BundleCompiler(); $compiler->compile('/path/to/bundle', '/path/to/binary/bundle'); @@ -123,13 +123,13 @@ writes an array or an array-like object to a .php resource bundle:: use Symfony\Component\Intl\ResourceBundle\Writer\PhpBundleWriter; $writer = new PhpBundleWriter(); - $writer->write('/path/to/bundle', 'en', array( - 'Data' => array( + $writer->write('/path/to/bundle', 'en', [ + 'Data' => [ 'entry1', 'entry2', // ... - ), - )); + ], + ]); BinaryBundleReader ~~~~~~~~~~~~~~~~~~ @@ -201,7 +201,7 @@ returned:: var_dump($data['Data']['entry1']); // returns null if the key "Data" does not exist - var_dump($reader->readEntry('/path/to/bundle', 'en', array('Data', 'entry1'))); + var_dump($reader->readEntry('/path/to/bundle', 'en', ['Data', 'entry1'])); Additionally, the :method:`Symfony\\Component\\Intl\\ResourceBundle\\Reader\\StructuredBundleReaderInterface::readEntry` @@ -215,7 +215,7 @@ locale will be merged. In order to suppress this behavior, the last parameter var_dump($reader->readEntry( '/path/to/bundle', 'en', - array('Data', 'entry1'), + ['Data', 'entry1'], false )); @@ -243,7 +243,7 @@ bundle:: \Locale::setDefault('en'); $languages = Intl::getLanguageBundle()->getLanguageNames(); - // => array('ab' => 'Abkhazian', ...) + // => ['ab' => 'Abkhazian', ...] $language = Intl::getLanguageBundle()->getLanguageName('de'); // => 'German' @@ -252,7 +252,7 @@ bundle:: // => 'Austrian German' $scripts = Intl::getLanguageBundle()->getScriptNames(); - // => array('Arab' => 'Arabic', ...) + // => ['Arab' => 'Arabic', ...] $script = Intl::getLanguageBundle()->getScriptName('Hans'); // => 'Simplified' @@ -261,7 +261,7 @@ All methods accept the translation locale as the last, optional parameter, which defaults to the current default locale:: $languages = Intl::getLanguageBundle()->getLanguageNames('de'); - // => array('ab' => 'Abchasisch', ...) + // => ['ab' => 'Abchasisch', ...] Country Names ~~~~~~~~~~~~~ @@ -273,7 +273,7 @@ The translations of country names can be found in the region bundle:: \Locale::setDefault('en'); $countries = Intl::getRegionBundle()->getCountryNames(); - // => array('AF' => 'Afghanistan', ...) + // => ['AF' => 'Afghanistan', ...] $country = Intl::getRegionBundle()->getCountryName('GB'); // => 'United Kingdom' @@ -282,7 +282,7 @@ All methods accept the translation locale as the last, optional parameter, which defaults to the current default locale:: $countries = Intl::getRegionBundle()->getCountryNames('de'); - // => array('AF' => 'Afghanistan', ...) + // => ['AF' => 'Afghanistan', ...] Locales ~~~~~~~ @@ -294,7 +294,7 @@ The translations of locale names can be found in the locale bundle:: \Locale::setDefault('en'); $locales = Intl::getLocaleBundle()->getLocaleNames(); - // => array('af' => 'Afrikaans', ...) + // => ['af' => 'Afrikaans', ...] $locale = Intl::getLocaleBundle()->getLocaleName('zh_Hans_MO'); // => 'Chinese (Simplified, Macau SAR China)' @@ -303,7 +303,7 @@ All methods accept the translation locale as the last, optional parameter, which defaults to the current default locale:: $locales = Intl::getLocaleBundle()->getLocaleNames('de'); - // => array('af' => 'Afrikaans', ...) + // => ['af' => 'Afrikaans', ...] Currencies ~~~~~~~~~~ @@ -316,7 +316,7 @@ be found in the currency bundle:: \Locale::setDefault('en'); $currencies = Intl::getCurrencyBundle()->getCurrencyNames(); - // => array('AFN' => 'Afghan Afghani', ...) + // => ['AFN' => 'Afghan Afghani', ...] $currency = Intl::getCurrencyBundle()->getCurrencyName('INR'); // => 'Indian Rupee' @@ -338,7 +338,7 @@ accept the translation locale as the last, optional parameter, which defaults to the current default locale:: $currencies = Intl::getCurrencyBundle()->getCurrencyNames('de'); - // => array('AFN' => 'Afghanische Afghani', ...) + // => ['AFN' => 'Afghanische Afghani', ...] That's all you need to know for now. Have fun coding! diff --git a/components/ldap.rst b/components/ldap.rst index c3af9ed322a..c764438671e 100644 --- a/components/ldap.rst +++ b/components/ldap.rst @@ -56,16 +56,16 @@ For example, to connect to a start-TLS secured LDAP server:: use Symfony\Component\Ldap\Ldap; - $ldap = Ldap::create('ext_ldap', array( + $ldap = Ldap::create('ext_ldap', [ 'host' => 'my-server', 'encryption' => 'ssl', - )); + ]); Or you could directly specify a connection string:: use Symfony\Component\Ldap\Ldap; - $ldap = Ldap::create('ext_ldap', array('connection_string' => 'ldaps://my-server:636')); + $ldap = Ldap::create('ext_ldap', ['connection_string' => 'ldaps://my-server:636']); The :method:`Symfony\\Component\\Ldap\\Ldap::bind` method authenticates a previously configured connection using both the @@ -113,10 +113,10 @@ delete existing ones:: use Symfony\Component\Ldap\Entry; // ... - $entry = new Entry('cn=Fabien Potencier,dc=symfony,dc=com', array( - 'sn' => array('fabpot'), - 'objectClass' => array('inetOrgPerson'), - )); + $entry = new Entry('cn=Fabien Potencier,dc=symfony,dc=com', [ + 'sn' => ['fabpot'], + 'objectClass' => ['inetOrgPerson'], + ]); $entryManager = $ldap->getEntryManager(); @@ -127,7 +127,7 @@ delete existing ones:: $query = $ldap->query('dc=symfony,dc=com', '(&(objectclass=person)(ou=Maintainers))'); $result = $query->execute(); $entry = $result[0]; - $entry->setAttribute('email', array('fabpot@symfony.com')); + $entry->setAttribute('email', ['fabpot@symfony.com']); $entryManager->update($entry); // Removing an existing entry diff --git a/components/lock.rst b/components/lock.rst index 6fc9fac2a0b..72e3d5a721f 100644 --- a/components/lock.rst +++ b/components/lock.rst @@ -248,7 +248,7 @@ then the lock is considered as acquired; otherwise as not acquired:: use Symfony\Component\Lock\Store\RedisStore; $stores = []; - foreach (array('server1', 'server2', 'server3') as $server) { + foreach (['server1', 'server2', 'server3'] as $server) { $redis = new \Redis(); $redis->connect($server); diff --git a/components/options_resolver.rst b/components/options_resolver.rst index 01bee94a151..5f302cec4d2 100644 --- a/components/options_resolver.rst +++ b/components/options_resolver.rst @@ -30,7 +30,7 @@ Imagine you have a ``Mailer`` class which has four options: ``host``, { protected $options; - public function __construct(array $options = array()) + public function __construct(array $options = []) { $this->options = $options; } @@ -74,14 +74,14 @@ options are buried in the business logic of your code. Use the { // ... - public function __construct(array $options = array()) + public function __construct(array $options = []) { - $this->options = array_replace(array( + $this->options = array_replace([ 'host' => 'smtp.example.org', 'username' => 'user', 'password' => 'pa$$word', 'port' => 25, - ), $options); + ], $options); } } @@ -90,9 +90,9 @@ the ``Mailer`` class makes a mistake? .. code-block:: php - $mailer = new Mailer(array( + $mailer = new Mailer([ 'usernme' => 'johndoe', // usernme misspelled (instead of username) - )); + ]); No error will be shown. In the best case, the bug will appear during testing, but the developer will spend time looking for the problem. In the worst case, @@ -107,15 +107,15 @@ class helps you to fix this problem:: { // ... - public function __construct(array $options = array()) + public function __construct(array $options = []) { $resolver = new OptionsResolver(); - $resolver->setDefaults(array( + $resolver->setDefaults([ 'host' => 'smtp.example.org', 'username' => 'user', 'password' => 'pa$$word', 'port' => 25, - )); + ]); $this->options = $resolver->resolve($options); } @@ -125,9 +125,9 @@ Like before, all options will be guaranteed to be set. Additionally, an :class:`Symfony\\Component\\OptionsResolver\\Exception\\UndefinedOptionsException` is thrown if an unknown option is passed:: - $mailer = new Mailer(array( + $mailer = new Mailer([ 'usernme' => 'johndoe', - )); + ]); // UndefinedOptionsException: The option "usernme" does not exist. // Known options are: "host", "password", "port", "username" @@ -158,7 +158,7 @@ It's a good practice to split the option configuration into a separate method:: { // ... - public function __construct(array $options = array()) + public function __construct(array $options = []) { $resolver = new OptionsResolver(); $this->configureOptions($resolver); @@ -168,13 +168,13 @@ It's a good practice to split the option configuration into a separate method:: public function configureOptions(OptionsResolver $resolver) { - $resolver->setDefaults(array( + $resolver->setDefaults([ 'host' => 'smtp.example.org', 'username' => 'user', 'password' => 'pa$$word', 'port' => 25, 'encryption' => null, - )); + ]); } } @@ -189,10 +189,10 @@ than processing options. Second, sub-classes may now override the { parent::configureOptions($resolver); - $resolver->setDefaults(array( + $resolver->setDefaults([ 'host' => 'smtp.google.com', 'encryption' => 'ssl', - )); + ]); } } @@ -235,7 +235,7 @@ one required option:: public function configureOptions(OptionsResolver $resolver) { // ... - $resolver->setRequired(array('host', 'username', 'password')); + $resolver->setRequired(['host', 'username', 'password']); } } @@ -323,7 +323,7 @@ correctly. To validate the types of the options, call $resolver->setAllowedTypes('host', 'string'); // specify multiple allowed types - $resolver->setAllowedTypes('port', array('null', 'int')); + $resolver->setAllowedTypes('port', ['null', 'int']); // check all items in an array recursively for a type $resolver->setAllowedTypes('dates', 'DateTime[]'); @@ -345,9 +345,9 @@ If you pass an invalid option now, an :class:`Symfony\\Component\\OptionsResolver\\Exception\\InvalidOptionsException` is thrown:: - $mailer = new Mailer(array( + $mailer = new Mailer([ 'host' => 25, - )); + ]); // InvalidOptionsException: The option "host" with value "25" is // expected to be of type "string" @@ -373,7 +373,7 @@ to verify that the passed option contains one of these values:: { // ... $resolver->setDefault('transport', 'sendmail'); - $resolver->setAllowedValues('transport', array('sendmail', 'mail', 'smtp')); + $resolver->setAllowedValues('transport', ['sendmail', 'mail', 'smtp']); } } @@ -381,9 +381,9 @@ If you pass an invalid transport, an :class:`Symfony\\Component\\OptionsResolver\\Exception\\InvalidOptionsException` is thrown:: - $mailer = new Mailer(array( + $mailer = new Mailer([ 'transport' => 'send-mail', - )); + ]); // InvalidOptionsException: The option "transport" has the value // "send-mail", but is expected to be one of "sendmail", "mail", "smtp" @@ -506,10 +506,10 @@ the closure:: public function configureOptions(OptionsResolver $resolver) { // ... - $resolver->setDefaults(array( + $resolver->setDefaults([ 'encryption' => null, 'host' => 'example.org', - )); + ]); } } @@ -594,9 +594,9 @@ be included in the resolved options if it was actually passed to $mailer->sendMail($from, $to); // => Not Set! - $mailer = new Mailer(array( + $mailer = new Mailer([ 'port' => 25, - )); + ]); $mailer->sendMail($from, $to); // => Set! @@ -610,7 +610,7 @@ options in one go:: public function configureOptions(OptionsResolver $resolver) { // ... - $resolver->setDefined(array('port', 'encryption')); + $resolver->setDefined(['port', 'encryption']); } } @@ -651,11 +651,11 @@ can change your code to do the configuration only once per class:: // ... class Mailer { - private static $resolversByClass = array(); + private static $resolversByClass = []; protected $options; - public function __construct(array $options = array()) + public function __construct(array $options = []) { // What type of Mailer is this, a Mailer, a GoogleMailer, ... ? $class = get_class($this); @@ -684,11 +684,11 @@ method ``clearOptionsConfig()`` and call it periodically:: // ... class Mailer { - private static $resolversByClass = array(); + private static $resolversByClass = []; public static function clearOptionsConfig() { - self::$resolversByClass = array(); + self::$resolversByClass = []; } // ... diff --git a/components/phpunit_bridge.rst b/components/phpunit_bridge.rst index 1b15d6da181..710679e2253 100644 --- a/components/phpunit_bridge.rst +++ b/components/phpunit_bridge.rst @@ -433,7 +433,7 @@ constraint to test the validity of the email domain:: public function testEmail() { $validator = ... - $constraint = new Email(array('checkMX' => true)); + $constraint = new Email(['checkMX' => true]); $result = $validator->validate('foo@example.com', $constraint); @@ -454,10 +454,10 @@ the data you expect to get for the given hosts:: { public function testEmails() { - DnsMock::withMockedHosts(array('example.com' => array(array('type' => 'MX')))); + DnsMock::withMockedHosts(['example.com' => [['type' => 'MX']]]); $validator = ... - $constraint = new Email(array('checkMX' => true)); + $constraint = new Email(['checkMX' => true]); $result = $validator->validate('foo@example.com', $constraint); @@ -469,18 +469,18 @@ are the mocked hosts and the values are arrays of DNS records in the same format returned by :phpfunction:`dns_get_record`, so you can simulate diverse network conditions:: - DnsMock::withMockedHosts(array( - 'example.com' => array( - array( + DnsMock::withMockedHosts([ + 'example.com' => [ + [ 'type' => 'A', 'ip' => '1.2.3.4', - ), - array( + ], + [ 'type' => 'AAAA', 'ipv6' => '::12', - ), - ), - )); + ], + ], + ]); Troubleshooting --------------- diff --git a/components/process.rst b/components/process.rst index dbc1e472354..679fe67cc31 100644 --- a/components/process.rst +++ b/components/process.rst @@ -27,7 +27,7 @@ a command in a sub-process:: use Symfony\Component\Process\Process; use Symfony\Component\Process\Exception\ProcessFailedException; - $process = new Process(array('ls', '-lsa')); + $process = new Process(['ls', '-lsa']); $process->run(); // executes after the command finishes @@ -55,7 +55,7 @@ You can also use the :class:`Symfony\\Component\\Process\\Process` class with th foreach construct to get the output while it is generated. By default, the loop waits for new output before going to the next iteration:: - $process = new Process(array('ls', '-lsa')); + $process = new Process(['ls', '-lsa']); $process->start(); foreach ($process as $type => $data) { @@ -72,7 +72,7 @@ for new output before going to the next iteration:: it is generated. That iterator is exposed via the ``getIterator()`` method to allow customizing its behavior:: - $process = new Process(array('ls', '-lsa')); + $process = new Process(['ls', '-lsa']); $process->start(); $iterator = $process->getIterator($process::ITER_SKIP_ERR | $process::ITER_KEEP_OUTPUT); foreach ($iterator as $data) { @@ -91,7 +91,7 @@ with a non-zero code):: use Symfony\Component\Process\Exception\ProcessFailedException; use Symfony\Component\Process\Process; - $process = new Process(array('ls', '-lsa')); + $process = new Process(['ls', '-lsa']); try { $process->mustRun(); @@ -112,7 +112,7 @@ with a non-zero code):: saves you from any escaping and allows sending signals seamlessly (e.g. to stop processes before completion.):: - $process = new Process(array('/path/command', '--flag', 'arg 1', 'etc.')); + $process = new Process(['/path/command', '--flag', 'arg 1', 'etc.']); If you need to use stream redirections, conditional execution, or any other feature provided by the shell of your operating system, you can also define @@ -132,7 +132,7 @@ with a non-zero code):: $process = new Process('echo "!MESSAGE!"'); // On both Unix-like and Windows - $process->run(null, array('MESSAGE' => 'Something to output')); + $process->run(null, ['MESSAGE' => 'Something to output']); Getting real-time Process Output -------------------------------- @@ -144,7 +144,7 @@ anonymous function to the use Symfony\Component\Process\Process; - $process = new Process(array('ls', '-lsa')); + $process = new Process(['ls', '-lsa']); $process->run(function ($type, $buffer) { if (Process::ERR === $type) { echo 'ERR > '.$buffer; @@ -163,7 +163,7 @@ process, the :method:`Symfony\\Component\\Process\\Process::isRunning` method to check if the process is done and the :method:`Symfony\\Component\\Process\\Process::getOutput` method to get the output:: - $process = new Process(array('ls', '-lsa')); + $process = new Process(['ls', '-lsa']); $process->start(); while ($process->isRunning()) { @@ -175,7 +175,7 @@ to check if the process is done and the You can also wait for a process to end if you started it asynchronously and are done doing other stuff:: - $process = new Process(array('ls', '-lsa')); + $process = new Process(['ls', '-lsa']); $process->start(); // ... do other things @@ -214,7 +214,7 @@ are done doing other stuff:: a callback that is called repeatedly whilst the process is still running, passing in the output and its type:: - $process = new Process(array('ls', '-lsa')); + $process = new Process(['ls', '-lsa']); $process->start(); $process->wait(function ($type, $buffer) { @@ -246,7 +246,7 @@ provides the :class:`Symfony\\Component\\Process\\InputStream` class:: $input = new InputStream(); $input->write('foo'); - $process = new Process(array('cat')); + $process = new Process(['cat']); $process->setInput($input); $process->start(); @@ -272,7 +272,7 @@ The input of a process can also be defined using `PHP streams`_:: $stream = fopen('php://temporary', 'w+'); - $process = new Process(array('cat')); + $process = new Process(['cat']); $process->setInput($stream); $process->start(); @@ -298,7 +298,7 @@ is sent to the running process. The default signal sent to a process is ``SIGKIL Please read the :ref:`signal documentation below` to find out more about signal handling in the Process component:: - $process = new Process(array('ls', '-lsa')); + $process = new Process(['ls', '-lsa']); $process->start(); // ... do other things @@ -327,7 +327,7 @@ a different timeout (in seconds) to the ``setTimeout()`` method:: use Symfony\Component\Process\Process; - $process = new Process(array('ls', '-lsa')); + $process = new Process(['ls', '-lsa']); $process->setTimeout(3600); $process->run(); @@ -359,7 +359,7 @@ considers the time since the last output was produced by the process:: use Symfony\Component\Process\Process; - $process = new Process(array('something-with-variable-runtime')); + $process = new Process(['something-with-variable-runtime']); $process->setTimeout(3600); $process->setIdleTimeout(60); $process->run(); @@ -375,7 +375,7 @@ When running a program asynchronously, you can send it POSIX signals with the use Symfony\Component\Process\Process; - $process = new Process(array('find', '/', '-name', 'rabbit')); + $process = new Process(['find', '/', '-name', 'rabbit']); $process->start(); // will send a SIGKILL to the process @@ -389,7 +389,7 @@ You can access the `pid`_ of a running process with the use Symfony\Component\Process\Process; - $process = new Process(array('/usr/bin/php', 'worker.php')); + $process = new Process(['/usr/bin/php', 'worker.php']); $process->start(); $pid = $process->getPid(); @@ -404,7 +404,7 @@ Use :method:`Symfony\\Component\\Process\\Process::disableOutput` and use Symfony\Component\Process\Process; - $process = new Process(array('/usr/bin/php', 'worker.php')); + $process = new Process(['/usr/bin/php', 'worker.php']); $process->disableOutput(); $process->run(); diff --git a/components/property_access.rst b/components/property_access.rst index 8bf14e346e0..1181f8ff3a7 100644 --- a/components/property_access.rst +++ b/components/property_access.rst @@ -40,9 +40,9 @@ You can read an array with the method. This is done using the index notation that is used in PHP:: // ... - $person = array( + $person = [ 'first_name' => 'Wouter', - ); + ]; var_dump($propertyAccessor->getValue($person, '[first_name]')); // 'Wouter' var_dump($propertyAccessor->getValue($person, '[age]')); // null @@ -57,9 +57,9 @@ method:: ->enableExceptionOnInvalidIndex() ->getPropertyAccessor(); - $person = array( + $person = [ 'first_name' => 'Wouter', - ); + ]; // instead of returning null, the code now throws an exception of type // Symfony\Component\PropertyAccess\Exception\NoSuchIndexException @@ -68,14 +68,14 @@ method:: You can also use multi dimensional arrays:: // ... - $persons = array( - array( + $persons = [ + [ 'first_name' => 'Wouter', - ), - array( + ], + [ 'first_name' => 'Ryan', - ) - ); + ] + ]; var_dump($propertyAccessor->getValue($persons, '[0][first_name]')); // 'Wouter' var_dump($propertyAccessor->getValue($persons, '[1][first_name]')); // 'Ryan' @@ -99,7 +99,7 @@ To read from properties, use the "dot" notation:: $child = new Person(); $child->firstName = 'Bar'; - $person->children = array($child); + $person->children = [$child]; var_dump($propertyAccessor->getValue($person, 'children[0].firstName')); // 'Bar' @@ -144,7 +144,7 @@ getters, this means that you can do something like this:: class Person { private $author = true; - private $children = array(); + private $children = []; public function isAuthor() { @@ -176,9 +176,9 @@ The ``getValue()`` method can also use the magic ``__get()`` method:: // ... class Person { - private $children = array( - 'Wouter' => array(...), - ); + private $children = [ + 'Wouter' => [...], + ]; public function __get($id) { @@ -188,7 +188,7 @@ The ``getValue()`` method can also use the magic ``__get()`` method:: $person = new Person(); - var_dump($propertyAccessor->getValue($person, 'Wouter')); // array(...) + var_dump($propertyAccessor->getValue($person, 'Wouter')); // [...] .. _components-property-access-magic-call: @@ -201,9 +201,9 @@ enable this feature by using :class:`Symfony\\Component\\PropertyAccess\\Propert // ... class Person { - private $children = array( - 'wouter' => array(...), - ); + private $children = [ + 'wouter' => [...], + ]; public function __call($name, $args) { @@ -226,7 +226,7 @@ enable this feature by using :class:`Symfony\\Component\\PropertyAccess\\Propert ->enableMagicCall() ->getPropertyAccessor(); - var_dump($propertyAccessor->getValue($person, 'wouter')); // array(...) + var_dump($propertyAccessor->getValue($person, 'wouter')); // [...] .. caution:: @@ -243,7 +243,7 @@ also write to an array. This can be achieved using the method:: // ... - $person = array(); + $person = []; $propertyAccessor->setValue($person, '[first_name]', 'Wouter'); @@ -262,7 +262,7 @@ can use setters, the magic ``__set()`` method or properties to set values:: { public $firstName; private $lastName; - private $children = array(); + private $children = []; public function setLastName($name) { @@ -289,11 +289,11 @@ can use setters, the magic ``__set()`` method or properties to set values:: $propertyAccessor->setValue($person, 'firstName', 'Wouter'); $propertyAccessor->setValue($person, 'lastName', 'de Jong'); // setLastName is called - $propertyAccessor->setValue($person, 'children', array(new Person())); // __set is called + $propertyAccessor->setValue($person, 'children', [new Person()]); // __set is called var_dump($person->firstName); // 'Wouter' var_dump($person->getLastName()); // 'de Jong' - var_dump($person->getChildren()); // array(Person()); + var_dump($person->getChildren()); // [Person()]; You can also use ``__call()`` to set values but you need to enable the feature, see `Enable other Features`_. @@ -303,7 +303,7 @@ see `Enable other Features`_. // ... class Person { - private $children = array(); + private $children = []; public function __call($name, $args) { @@ -327,9 +327,9 @@ see `Enable other Features`_. ->enableMagicCall() ->getPropertyAccessor(); - $propertyAccessor->setValue($person, 'wouter', array(...)); + $propertyAccessor->setValue($person, 'wouter', [...]); - var_dump($person->getWouter()); // array(...) + var_dump($person->getWouter()); // [...] Writing to Array Properties ~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -345,7 +345,7 @@ properties through *adder* and *remover* methods. /** * @var string[] */ - private $children = array(); + private $children = []; public function getChildren(): array { @@ -364,9 +364,9 @@ properties through *adder* and *remover* methods. } $person = new Person(); - $propertyAccessor->setValue($person, 'children', array('kevin', 'wouter')); + $propertyAccessor->setValue($person, 'children', ['kevin', 'wouter']); - var_dump($person->getChildren()); // array('kevin', 'wouter') + var_dump($person->getChildren()); // ['kevin', 'wouter'] The PropertyAccess component checks for methods called ``add()`` and ``remove()``. Both methods must be defined. @@ -411,7 +411,7 @@ You can also mix objects and arrays:: class Person { public $firstName; - private $children = array(); + private $children = []; public function setChildren($children) { diff --git a/components/property_info.rst b/components/property_info.rst index 1cfd4b94431..b75033d06c1 100644 --- a/components/property_info.rst +++ b/components/property_info.rst @@ -51,16 +51,16 @@ provide it with a set of information extractors. $reflectionExtractor = new ReflectionExtractor(); // array of PropertyListExtractorInterface - $listExtractors = array($reflectionExtractor); + $listExtractors = [$reflectionExtractor]; // array of PropertyTypeExtractorInterface - $typeExtractors = array($phpDocExtractor, $reflectionExtractor); + $typeExtractors = [$phpDocExtractor, $reflectionExtractor]; // array of PropertyDescriptionExtractorInterface - $descriptionExtractors = array($phpDocExtractor); + $descriptionExtractors = [$phpDocExtractor]; // array of PropertyAccessExtractorInterface - $accessExtractors = array($reflectionExtractor); + $accessExtractors = [$reflectionExtractor]; $propertyInfo = new PropertyInfoExtractor( $listExtractors, @@ -103,15 +103,15 @@ both provide list and type information it is probably better that: $propertyInfo = new PropertyInfoExtractor( // List extractors - array( + [ $reflectionExtractor, $doctrineExtractor - ), + ], // Type extractors - array( + [ $doctrineExtractor, $reflectionExtractor - ) + ] ); .. _`components-property-information-extractable-information`: diff --git a/components/psr7.rst b/components/psr7.rst index 26f9fd0dbbb..61b2d1b35e3 100644 --- a/components/psr7.rst +++ b/components/psr7.rst @@ -42,7 +42,7 @@ to a ``Zend\Diactoros\ServerRequest`` class implementing the use Symfony\Bridge\PsrHttpMessage\Factory\DiactorosFactory; use Symfony\Component\HttpFoundation\Request; - $symfonyRequest = new Request(array(), array(), array(), array(), array(), array('HTTP_HOST' => 'dunglas.fr'), 'Content'); + $symfonyRequest = new Request([], [], [], [], [], ['HTTP_HOST' => 'dunglas.fr'], 'Content'); // The HTTP_HOST server key must be set to avoid an unexpected error $psr7Factory = new DiactorosFactory(); diff --git a/components/routing.rst b/components/routing.rst index 8b161e69e71..ea390022d40 100644 --- a/components/routing.rst +++ b/components/routing.rst @@ -42,7 +42,7 @@ your autoloader to load the Routing component:: use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; - $route = new Route('/foo', array('_controller' => 'MyController')); + $route = new Route('/foo', ['_controller' => 'MyController']); $routes = new RouteCollection(); $routes->add('route_name', $route); @@ -51,7 +51,7 @@ your autoloader to load the Routing component:: $matcher = new UrlMatcher($routes, $context); $parameters = $matcher->match('/foo'); - // array('_controller' => 'MyController', '_route' => 'route_name') + // ['_controller' => 'MyController', '_route' => 'route_name'] .. note:: @@ -109,23 +109,23 @@ Take the following route, which combines several of these ideas:: $route = new Route( '/archive/{month}', // path - array('_controller' => 'showArchive'), // default values - array('month' => '[0-9]{4}-[0-9]{2}', 'subdomain' => 'www|m'), // requirements - array(), // options + ['_controller' => 'showArchive'], // default values + ['month' => '[0-9]{4}-[0-9]{2}', 'subdomain' => 'www|m'], // requirements + [], // options '{subdomain}.example.com', // host - array(), // schemes - array() // methods + [], // schemes + [] // methods ); // ... $parameters = $matcher->match('/archive/2012-01'); - // array( + // [ // '_controller' => 'showArchive', // 'month' => '2012-01', // 'subdomain' => 'www', // '_route' => ... - // ) + // ] $parameters = $matcher->match('/archive/foo'); // throws ResourceNotFoundException @@ -145,8 +145,8 @@ as value. $route = new Route( '/start/{suffix}', - array('suffix' => ''), - array('suffix' => '.*') + ['suffix' => ''], + ['suffix' => '.*'] ); Using Prefixes @@ -165,12 +165,12 @@ host to all routes of a subtree using methods provided by the $subCollection->add(...); $subCollection->add(...); $subCollection->addPrefix('/prefix'); - $subCollection->addDefaults(array(...)); - $subCollection->addRequirements(array(...)); - $subCollection->addOptions(array(...)); + $subCollection->addDefaults([...]); + $subCollection->addRequirements([]); + $subCollection->addOptions([]); $subCollection->setHost('admin.example.com'); - $subCollection->setMethods(array('POST')); - $subCollection->setSchemes(array('https')); + $subCollection->setMethods(['POST']); + $subCollection->setSchemes(['https']); $rootCollection->addCollection($subCollection); @@ -224,9 +224,9 @@ a certain route:: $generator = new UrlGenerator($routes, $context); - $url = $generator->generate('show_post', array( + $url = $generator->generate('show_post', [ 'slug' => 'my-blog-post', - )); + ]); // /show/my-blog-post .. note:: @@ -291,7 +291,7 @@ To load this file, you can use the following code. This assumes that your use Symfony\Component\Routing\Loader\YamlFileLoader; // looks inside *this* directory - $fileLocator = new FileLocator(array(__DIR__)); + $fileLocator = new FileLocator([__DIR__]); $loader = new YamlFileLoader($fileLocator); $routes = $loader->load('routes.yml'); @@ -311,7 +311,7 @@ have to provide the name of a PHP file which returns a :class:`Symfony\\Componen $routes = new RouteCollection(); $routes->add( 'route_name', - new Route('/foo', array('_controller' => 'ExampleController')) + new Route('/foo', ['_controller' => 'ExampleController']) ); // ... @@ -353,7 +353,7 @@ a path to the main route definition and some other settings:: public function __construct( LoaderInterface $loader, $resource, - array $options = array(), + array $options = [], RequestContext $context = null, LoggerInterface $logger = null ); @@ -363,13 +363,13 @@ path) or disable caching (if it's set to ``null``). The caching is done automatically in the background if you want to use it. A basic example of the :class:`Symfony\\Component\\Routing\\Router` class would look like:: - $fileLocator = new FileLocator(array(__DIR__)); + $fileLocator = new FileLocator([__DIR__]); $requestContext = new RequestContext('/'); $router = new Router( new YamlFileLoader($fileLocator), 'routes.yml', - array('cache_dir' => __DIR__.'/cache'), + ['cache_dir' => __DIR__.'/cache'], $requestContext ); $router->match('/foo/bar'); @@ -444,13 +444,13 @@ routes with UTF-8 characters: $routes = new RouteCollection(); $routes->add('route1', new Route('/category/{name}', - array( + [ '_controller' => 'AppBundle:Default:category', - ), - array(), - array( + ], + [], + [ 'utf8' => true, - ) + ] )); // ... @@ -525,15 +525,15 @@ You can also include UTF-8 strings as routing requirements: $routes = new RouteCollection(); $routes->add('route2', new Route('/default/{default}', - array( + [ '_controller' => 'AppBundle:Default:default', - ), - array( + ], + [ 'default' => '한국어', - ), - array( + ], + [ 'utf8' => true, - ) + ] )); // ... diff --git a/components/security/authentication.rst b/components/security/authentication.rst index d7d291276db..9430808c825 100644 --- a/components/security/authentication.rst +++ b/components/security/authentication.rst @@ -74,7 +74,7 @@ The default authentication manager is an instance of use Symfony\Component\Security\Core\Exception\AuthenticationException; // instances of Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface - $providers = array(...); + $providers = [...]; $authenticationManager = new AuthenticationProviderManager($providers); @@ -132,13 +132,13 @@ password was valid:: use Symfony\Component\Security\Core\Encoder\EncoderFactory; $userProvider = new InMemoryUserProvider( - array( - 'admin' => array( + [ + 'admin' => [ // password is "foo" 'password' => '5FZ2Z8QIkA7UTZ4BYkoC+GsReLf569mSKDsfods6LYQ8t+a8EW9oaircfMpmaLbPBh4FOBiiFyLfuZmTSUwzZg==', - 'roles' => array('ROLE_ADMIN'), - ), - ) + 'roles' => ['ROLE_ADMIN'], + ], + ] ); // for some extra checks: is account enabled, locked, expired, etc. @@ -181,11 +181,11 @@ receives an array of encoders:: $defaultEncoder = new MessageDigestPasswordEncoder('sha512', true, 5000); $weakEncoder = new MessageDigestPasswordEncoder('md5', true, 1); - $encoders = array( + $encoders = [ User::class => $defaultEncoder, LegacyUser::class => $weakEncoder, // ... - ); + ]; $encoderFactory = new EncoderFactory($encoders); Each encoder should implement :class:`Symfony\\Component\\Security\\Core\\Encoder\\PasswordEncoderInterface` diff --git a/components/security/authorization.rst b/components/security/authorization.rst index 685df577126..cf88ed8642e 100644 --- a/components/security/authorization.rst +++ b/components/security/authorization.rst @@ -54,7 +54,7 @@ recognizes several strategies: use Symfony\Component\Security\Core\Authorization\AccessDecisionManager; // instances of Symfony\Component\Security\Core\Authorization\Voter\VoterInterface - $voters = array(...); + $voters = [...]; // one of "affirmative", "consensus", "unanimous" $strategy = ...; @@ -119,7 +119,7 @@ on a "remember-me" cookie, or even authenticated anonymously? // any object $object = ...; - $vote = $authenticatedVoter->vote($token, $object, array('IS_AUTHENTICATED_FULLY')); + $vote = $authenticatedVoter->vote($token, $object, ['IS_AUTHENTICATED_FULLY']); RoleVoter ~~~~~~~~~ @@ -134,7 +134,7 @@ method:: $roleVoter = new RoleVoter('ROLE_'); - $roleVoter->vote($token, $object, array('ROLE_ADMIN')); + $roleVoter->vote($token, $object, ['ROLE_ADMIN']); RoleHierarchyVoter ~~~~~~~~~~~~~~~~~~ @@ -151,9 +151,9 @@ role:: use Symfony\Component\Security\Core\Authorization\Voter\RoleHierarchyVoter; use Symfony\Component\Security\Core\Role\RoleHierarchy; - $hierarchy = array( - 'ROLE_SUPER_ADMIN' => array('ROLE_ADMIN', 'ROLE_USER'), - ); + $hierarchy = [ + 'ROLE_SUPER_ADMIN' => ['ROLE_ADMIN', 'ROLE_USER'], + ]; $roleHierarchy = new RoleHierarchy($hierarchy); @@ -209,7 +209,7 @@ are required for the current user to get access to the application:: $accessMap = new AccessMap(); $requestMatcher = new RequestMatcher('^/admin'); - $accessMap->add($requestMatcher, array('ROLE_ADMIN')); + $accessMap->add($requestMatcher, ['ROLE_ADMIN']); $accessListener = new AccessListener( $securityContext, diff --git a/components/security/firewall.rst b/components/security/firewall.rst index 51b62c037dd..72000b4cb18 100644 --- a/components/security/firewall.rst +++ b/components/security/firewall.rst @@ -61,7 +61,7 @@ the user:: $requestMatcher = new RequestMatcher('^/secured-area/'); // instances of Symfony\Component\Security\Http\Firewall\ListenerInterface - $listeners = array(...); + $listeners = [...]; $exceptionListener = new ExceptionListener(...); @@ -80,7 +80,7 @@ with the event dispatcher that is used by the :class:`Symfony\\Component\\HttpKe $dispatcher->addListener( KernelEvents::REQUEST, - array($firewall, 'onKernelRequest') + [$firewall, 'onKernelRequest'] ); The firewall is registered to listen to the ``kernel.request`` event that diff --git a/components/serializer.rst b/components/serializer.rst index 9a568b23e87..bba2740a715 100644 --- a/components/serializer.rst +++ b/components/serializer.rst @@ -53,8 +53,8 @@ which encoders and normalizer are going to be available:: use Symfony\Component\Serializer\Encoder\JsonEncoder; use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; - $encoders = array(new XmlEncoder(), new JsonEncoder()); - $normalizers = array(new ObjectNormalizer()); + $encoders = [new XmlEncoder(), new JsonEncoder()]; + $normalizers = [new ObjectNormalizer()]; $serializer = new Serializer($normalizers, $encoders); @@ -188,10 +188,10 @@ when constructing the normalizer:: // because "city" is not an attribute of the Person class $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader())); $normalizer = new ObjectNormalizer($classMetadataFactory); - $serializer = new Serializer(array($normalizer)); - $person = $serializer->deserialize($data, 'Acme\Person', 'xml', array( + $serializer = new Serializer([$normalizer]); + $person = $serializer->deserialize($data, 'Acme\Person', 'xml', [ 'allow_extra_attributes' => false, - )); + ]); Deserializing in an Existing Object ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -211,7 +211,7 @@ The serializer can also be used to update an existing object:: EOF; - $serializer->deserialize($data, Person::class, 'xml', array('object_to_populate' => $person)); + $serializer->deserialize($data, Person::class, 'xml', ['object_to_populate' => $person]); // $person = App\Model\Person(name: 'foo', age: '69', sportsperson: true) This is a common need when working with an ORM. @@ -336,16 +336,16 @@ You are now able to serialize only attributes in the groups you want:: $obj->setBar('bar'); $normalizer = new ObjectNormalizer($classMetadataFactory); - $serializer = new Serializer(array($normalizer)); + $serializer = new Serializer([$normalizer]); - $data = $serializer->normalize($obj, null, array('groups' => array('group1'))); - // $data = array('foo' => 'foo'); + $data = $serializer->normalize($obj, null, ['groups' => ['group1']]); + // $data = ['foo' => 'foo']; $obj2 = $serializer->denormalize( - array('foo' => 'foo', 'bar' => 'bar'), + ['foo' => 'foo', 'bar' => 'bar'], 'MyObj', null, - array('groups' => array('group1', 'group3')) + ['groups' => ['group1', 'group3']] ); // $obj2 = MyObj(foo: 'foo', bar: 'bar') @@ -383,10 +383,10 @@ It is also possible to serialize only a set of specific attributes:: $user->givenName = 'Kévin'; $user->company = $company; - $serializer = new Serializer(array(new ObjectNormalizer())); + $serializer = new Serializer([new ObjectNormalizer()]); - $data = $serializer->normalize($user, null, array('attributes' => array('familyName', 'company' => ['name']))); - // $data = array('familyName' => 'Dunglas', 'company' => array('name' => 'Les-Tilleuls.coop')); + $data = $serializer->normalize($user, null, ['attributes' => ['familyName', 'company' => ['name']]]); + // $data = ['familyName' => 'Dunglas', 'company' => ['name' => 'Les-Tilleuls.coop']]; Only attributes that are not ignored (see below) are available. If some serialization groups are set, only attributes allowed by those groups can be used. @@ -411,10 +411,10 @@ method on the normalizer definition:: use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; $normalizer = new ObjectNormalizer(); - $normalizer->setIgnoredAttributes(array('age')); + $normalizer->setIgnoredAttributes(['age']); $encoder = new JsonEncoder(); - $serializer = new Serializer(array($normalizer), array($encoder)); + $serializer = new Serializer([$normalizer], [$encoder]); $serializer->serialize($person, 'json'); // Output: {"name":"foo","sportsperson":false} .. _component-serializer-converting-property-names-when-serializing-and-deserializing: @@ -471,7 +471,7 @@ and :class:`Symfony\\Component\\Serializer\\Normalizer\\PropertyNormalizer`:: $nameConverter = new OrgPrefixNameConverter(); $normalizer = new ObjectNormalizer(null, $nameConverter); - $serializer = new Serializer(array($normalizer), array(new JsonEncoder())); + $serializer = new Serializer([$normalizer], [new JsonEncoder()]); $company = new Company(); $company->name = 'Acme Inc.'; @@ -520,7 +520,7 @@ processes:: $normalizer->normalize($kevin); // ['first_name' => 'Kévin']; - $anne = $normalizer->denormalize(array('first_name' => 'Anne'), 'Person'); + $anne = $normalizer->denormalize(['first_name' => 'Anne'], 'Person'); // Person object with firstName: 'Anne' Serializing Boolean Attributes @@ -552,9 +552,9 @@ When serializing, you can set a callback to format a specific object property:: : ''; }; - $normalizer->setCallbacks(array('createdAt' => $callback)); + $normalizer->setCallbacks(['createdAt' => $callback]); - $serializer = new Serializer(array($normalizer), array($encoder)); + $serializer = new Serializer([$normalizer], [$encoder]); $person = new Person(); $person->setName('cordoval'); @@ -737,7 +737,7 @@ when such a case is encountered:: $organization = new Organization(); $organization->setName('Les-Tilleuls.coop'); - $organization->setMembers(array($member)); + $organization->setMembers([$member]); $member->setOrganization($organization); @@ -758,7 +758,7 @@ having unique identifiers:: return $object->getName(); }); - $serializer = new Serializer(array($normalizer), array($encoder)); + $serializer = new Serializer([$normalizer], [$encoder]); var_dump($serializer->serialize($org, 'json')); // {"name":"Les-Tilleuls.coop","members":[{"name":"K\u00e9vin", organization: "Les-Tilleuls.coop"}]} @@ -843,17 +843,17 @@ The check is only done if the ``enable_max_depth`` key of the serializer context is set to ``true``. In the following example, the third level is not serialized because it is deeper than the configured maximum depth of 2:: - $result = $serializer->normalize($level1, null, array('enable_max_depth' => true)); + $result = $serializer->normalize($level1, null, ['enable_max_depth' => true]); /* - $result = array( + $result = [ 'foo' => 'level1', - 'child' => array( + 'child' => [ 'foo' => 'level2', - 'child' => array( + 'child' => [ 'child' => null, - ), - ), - ); + ], + ], + ]; */ Handling Arrays @@ -874,7 +874,7 @@ Serializing arrays works just like serializing a single object:: $person2->setAge(33); $person2->setSportsman(true); - $persons = array($person1, $person2); + $persons = [$person1, $person2]; $data = $serializer->serialize($persons, 'json'); // $data contains [{"name":"foo","age":99,"sportsman":false},{"name":"bar","age":33,"sportsman":true}] @@ -893,8 +893,8 @@ you indicate that you're expecting an array instead of a single object. use Symfony\Component\Serializer\Serializer; $serializer = new Serializer( - array(new GetSetMethodNormalizer(), new ArrayDenormalizer()), - array(new JsonEncoder()) + [new GetSetMethodNormalizer(), new ArrayDenormalizer()], + [new JsonEncoder()] ); $data = ...; // The serialized data from the previous example @@ -906,7 +906,7 @@ The ``XmlEncoder`` This encoder transforms arrays into XML and vice versa. For example, take an object normalized as following:: - array('foo' => array(1, 2), 'bar' => true); + ['foo' => [1, 2], 'bar' => true]; The ``XmlEncoder`` encodes this object as follows: @@ -921,7 +921,7 @@ The ``XmlEncoder`` encodes this object as follows: The array keys beginning with ``@`` are considered XML attributes:: - array('foo' => array('@bar' => 'value')); + ['foo' => ['@bar' => 'value']]; // is encoded as follows: // @@ -931,7 +931,7 @@ The array keys beginning with ``@`` are considered XML attributes:: Use the special ``#`` key to define the data of a node:: - array('foo' => array('@bar' => 'value', '#' => 'baz')); + ['foo' => ['@bar' => 'value', '#' => 'baz']]; // is encoded as follows: // @@ -1021,10 +1021,10 @@ parameter of the ``ObjectNormalizer``:: } $normalizer = new ObjectNormalizer(null, null, null, new ReflectionExtractor()); - $serializer = new Serializer(array(new DateTimeNormalizer(), $normalizer)); + $serializer = new Serializer([new DateTimeNormalizer(), $normalizer]); $obj = $serializer->denormalize( - array('inner' => array('foo' => 'foo', 'bar' => 'bar'), 'date' => '1988/01/21'), + ['inner' => ['foo' => 'foo', 'bar' => 'bar'], 'date' => '1988/01/21'], 'Acme\ObjectOuter' ); diff --git a/components/templating.rst b/components/templating.rst index 6d8fc3dac94..bd23640d9ad 100644 --- a/components/templating.rst +++ b/components/templating.rst @@ -49,7 +49,7 @@ which uses the template reference to actually find and load the template:: $templating = new PhpEngine(new TemplateNameParser(), $filesystemLoader); - echo $templating->render('hello.php', array('firstname' => 'Fabien')); + echo $templating->render('hello.php', ['firstname' => 'Fabien']); .. code-block:: html+php @@ -83,9 +83,9 @@ can then be included by other templates. As the ``$view`` variable is an instance of ``PhpEngine``, you can use the ``render()`` method (which was used to render the template originally) inside the template to render another template:: - + - render('hello.php', array('firstname' => $name)) ?> + render('hello.php', ['firstname' => $name]) ?> Global Variables @@ -178,7 +178,7 @@ using the Templating component. To do that, create a new class which implements the :class:`Symfony\\Component\\Templating\\EngineInterface`. This requires 3 method: -* :method:`render($name, array $parameters = array()) ` +* :method:`render($name, array $parameters = []) ` - Renders a template * :method:`exists($name) ` - Checks if the template exists @@ -200,10 +200,10 @@ method is used:: use Symfony\Component\Templating\PhpEngine; use Symfony\Component\Templating\DelegatingEngine; - $templating = new DelegatingEngine(array( + $templating = new DelegatingEngine([ new PhpEngine(...), new CustomEngine(...), - )); + ]); Learn More ---------- diff --git a/components/translation.rst b/components/translation.rst index 4ee67440aef..9bff7c1a614 100644 --- a/components/translation.rst +++ b/components/translation.rst @@ -120,9 +120,9 @@ argument is the loader name (this was the first argument of the ``addLoader()`` method), the second is the resource and the third argument is the locale:: // ... - $translator->addResource('array', array( + $translator->addResource('array', [ 'Hello World!' => 'Bonjour', - ), 'fr_FR'); + ], 'fr_FR'); Loading Messages with the File Loaders ...................................... @@ -176,7 +176,7 @@ For (3), the fallback locales can be set by calling :method:`Symfony\\Component\\Translation\\Translator::setFallbackLocales`:: // ... - $translator->setFallbackLocales(array('en')); + $translator->setFallbackLocales(['en']); .. _using-message-domains: @@ -207,7 +207,7 @@ loaded like this:: When translating strings that are not in the default domain (``messages``), you must specify the domain as the third argument of ``trans()``:: - $translator->trans('Symfony is great', array(), 'admin'); + $translator->trans('Symfony is great', [], 'admin'); Symfony will now look for the message in the ``admin`` domain of the specified locale. diff --git a/components/translation/custom_formats.rst b/components/translation/custom_formats.rst index c466a526749..8856b41c006 100644 --- a/components/translation/custom_formats.rst +++ b/components/translation/custom_formats.rst @@ -37,7 +37,7 @@ create the catalog that will be returned:: { public function load($resource, $locale, $domain = 'messages') { - $messages = array(); + $messages = []; $lines = file($resource); foreach ($lines as $line) { @@ -85,7 +85,7 @@ will save a few lines:: class MyFormatDumper extends FileDumper { - public function formatCatalogue(MessageCatalogue $messages, $domain, array $options = array()) + public function formatCatalogue(MessageCatalogue $messages, $domain, array $options = []) { $output = ''; @@ -122,4 +122,4 @@ YAML file are dumped into a text file with the custom format:: $translations = $loader->load(__DIR__ . '/translations/messages.fr_FR.yml' , 'fr_FR'); $dumper = new MyFormatDumper(); - $dumper->dump($translations, array('path' => __DIR__.'/dumps')); + $dumper->dump($translations, ['path' => __DIR__.'/dumps']); diff --git a/components/translation/usage.rst b/components/translation/usage.rst index 9481109f1a9..b7883ea8182 100644 --- a/components/translation/usage.rst +++ b/components/translation/usage.rst @@ -11,9 +11,9 @@ Imagine you want to translate the string *"Symfony is great"* into French:: $translator = new Translator('fr_FR'); $translator->addLoader('array', new ArrayLoader()); - $translator->addResource('array', array( + $translator->addResource('array', [ 'Symfony is great!' => 'Symfony est super !', - ), 'fr_FR'); + ], 'fr_FR'); var_dump($translator->trans('Symfony is great!')); @@ -42,7 +42,7 @@ variable with a "placeholder":: // ... $translated = $translator->trans( 'Hello %name%', - array('%name%' => $name) + ['%name%' => $name] ); var_dump($translated); @@ -69,9 +69,9 @@ is done just as before: .. code-block:: php - return array( + return [ 'Hello %name%' => 'Bonjour %name%', - ); + ]; .. code-block:: yaml @@ -134,10 +134,10 @@ recommended format. These files are parsed by one of the loader classes. .. code-block:: php - return array( + return [ 'Symfony is great' => 'J\'aime Symfony', 'symfony.great' => 'J\'aime Symfony', - ); + ]; .. _translation-real-vs-keyword-messages: @@ -185,20 +185,20 @@ recommended format. These files are parsed by one of the loader classes. .. code-block:: php - array( - 'symfony' => array( - 'is' => array( + [ + 'symfony' => [ + 'is' => [ 'great' => 'Symfony is great', 'amazing' => 'Symfony is amazing', - ), - 'has' => array( + ], + 'has' => [ 'bundles' => 'Symfony has bundles', - ), + ], ), - 'user' => array( + 'user' => [ 'login' => 'Login', - ), - ); + ], + ]; The multiple levels are flattened into single id/translation pairs by adding a dot (``.``) between every level, therefore the above examples are @@ -215,12 +215,12 @@ recommended format. These files are parsed by one of the loader classes. .. code-block:: php - return array( + return [ 'symfony.is.great' => 'Symfony is great', 'symfony.is.amazing' => 'Symfony is amazing', 'symfony.has.bundles' => 'Symfony has bundles', 'user.login' => 'Login', - ); + ]; .. _component-translation-pluralization: @@ -264,7 +264,7 @@ To translate pluralized messages, use the 'Hurry up %name%! There is one apple left.|There are %count% apples left.', 10, // no need to include %count% here; Symfony does that for you - array('%name%' => $user->getName()) + ['%name%' => $user->getName()] ); The second argument (``10`` in this example) is the *number* of objects being @@ -280,7 +280,7 @@ the ``%count%`` placeholder. $translator->transChoice( 'There is one apple|There are %count% apples', 10, - array('%count%' => 10) + ['%count%' => 10] ); Starting from Symfony 3.2, when the only placeholder is ``%count%``, you @@ -381,7 +381,7 @@ use for translation:: $translator->trans( 'Symfony is great', - array(), + [], 'messages', 'fr_FR' ); @@ -389,7 +389,7 @@ use for translation:: $translator->transChoice( '{0} There are no apples|{1} There is one apple|]1,Inf[ There are %count% apples', 10, - array(), + [], 'messages', 'fr_FR' ); @@ -403,7 +403,7 @@ use for translation:: $translator->transChoice( '{0} There are no apples|{1} There is one apple|]1,Inf[ There are %count% apples', 10, - array('%count%' => 10), + ['%count%' => 10], 'messages', 'fr_FR' ); @@ -423,15 +423,15 @@ messages. Just specify the required locale:: The ``$messages`` variable will have the following structure:: - array( - 'messages' => array( + [ + 'messages' => [ 'Hello world' => 'Bonjour tout le monde', - ), - 'validators' => array( + ], + 'validators' => [ 'Value should not be empty' => 'Valeur ne doit pas être vide', 'Value is too long' => 'Valeur est trop long', - ), - ); + ], + ]; Adding Notes to Translation Contents ------------------------------------ diff --git a/components/validator.rst b/components/validator.rst index 78c3f56c15a..f0c4edde217 100644 --- a/components/validator.rst +++ b/components/validator.rst @@ -41,10 +41,10 @@ characters long:: use Symfony\Component\Validator\Constraints\NotBlank; $validator = Validation::createValidator(); - $violations = $validator->validate('Bernhard', array( - new Length(array('min' => 10)), + $violations = $validator->validate('Bernhard', [ + new Length(['min' => 10]), new NotBlank(), - )); + ]); if (0 !== count($violations)) { // there are errors, now you can show them diff --git a/components/validator/metadata.rst b/components/validator/metadata.rst index 2b68d535b40..77c4037cc48 100755 --- a/components/validator/metadata.rst +++ b/components/validator/metadata.rst @@ -27,7 +27,7 @@ the ``Author`` class has at least 3 characters:: $metadata->addPropertyConstraint('firstName', new Assert\NotBlank()); $metadata->addPropertyConstraint( 'firstName', - new Assert\Length(array("min" => 3)) + new Assert\Length(["min" => 3]) ); } } @@ -58,9 +58,9 @@ Then, add the Validator component configuration to the class:: { public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addGetterConstraint('passwordSafe', new Assert\IsTrue(array( + $metadata->addGetterConstraint('passwordSafe', new Assert\IsTrue([ 'message' => 'The password cannot match your first name', - ))); + ])); } } diff --git a/components/validator/resources.rst b/components/validator/resources.rst index a567011dc77..83b4f47efa9 100644 --- a/components/validator/resources.rst +++ b/components/validator/resources.rst @@ -45,10 +45,10 @@ In this example, the validation metadata is retrieved executing the public static function loadValidatorMetadata(ClassMetadata $metadata) { $metadata->addPropertyConstraint('name', new Assert\NotBlank()); - $metadata->addPropertyConstraint('name', new Assert\Length(array( + $metadata->addPropertyConstraint('name', new Assert\Length([ 'min' => 5, 'max' => 20, - ))); + ])); } } diff --git a/components/var_dumper.rst b/components/var_dumper.rst index 3177e830c69..97306f01ffd 100644 --- a/components/var_dumper.rst +++ b/components/var_dumper.rst @@ -151,7 +151,7 @@ Example:: public function testWithDumpEquals() { - $testedVar = array(123, 'foo'); + $testedVar = [123, 'foo']; $expectedDump = << "in an array of 5 elements", 'a float' => 1.0, 'an integer' => 1, 'a boolean' => true, - 'an empty array' => array(), - ); + 'an empty array' => [], + ]; dump($var); .. image:: /_images/components/var_dumper/01-simple.png @@ -258,11 +258,11 @@ then its dump representation:: .. code-block:: php - $var = array(); + $var = []; $var[0] = 1; $var[1] =& $var[0]; $var[1] += 1; - $var[2] = array("Hard references (circular or sibling)"); + $var[2] = ["Hard references (circular or sibling)"]; $var[3] =& $var[2]; $var[3][] = "are dumped using `&number` prefixes."; dump($var); diff --git a/components/var_dumper/advanced.rst b/components/var_dumper/advanced.rst index 9ee054ad30f..3846845abbf 100644 --- a/components/var_dumper/advanced.rst +++ b/components/var_dumper/advanced.rst @@ -202,11 +202,11 @@ method:: $output = fopen('php://memory', 'r+b'); $dumper = new HtmlDumper(); - $dumper->dump($var, $output, array( + $dumper->dump($var, $output, [ // 1 and 160 are the default values for these options 'maxDepth' => 1, 'maxStringLength' => 160 - )); + ]); .. versionadded:: 3.2 @@ -242,7 +242,7 @@ next to its content: use Symfony\Component\VarDumper\Dumper\AbstractDumper; use Symfony\Component\VarDumper\Dumper\CliDumper; - $var = array('test'); + $var = ['test']; $dumper = new CliDumper(); echo $dumper->dump($var, true); @@ -266,7 +266,7 @@ similar to PHP's short array notation: use Symfony\Component\VarDumper\Dumper\AbstractDumper; use Symfony\Component\VarDumper\Dumper\CliDumper; - $var = array('test'); + $var = ['test']; $dumper = new CliDumper(); echo $dumper->dump($var, true); @@ -290,7 +290,7 @@ using a the logical OR operator ``|``: use Symfony\Component\VarDumper\Dumper\AbstractDumper; use Symfony\Component\VarDumper\Dumper\CliDumper; - $var = array('test'); + $var = ['test']; $dumper = new CliDumper(null, null, AbstractDumper::DUMP_STRING_LENGTH | AbstractDumper::DUMP_LIGHT_ARRAY); echo $dumper->dump($var, true); @@ -313,7 +313,7 @@ or its ``addCasters()`` method:: use Symfony\Component\VarDumper\Cloner\VarCloner; - $myCasters = array(...); + $myCasters = [...]; $cloner = new VarCloner($myCasters); // or @@ -323,10 +323,10 @@ or its ``addCasters()`` method:: The provided ``$myCasters`` argument is an array that maps a class, an interface or a resource type to a callable:: - $myCasters = array( + $myCasters = [ 'FooClass' => $myFooClassCallableCaster, ':bar resource' => $myBarResourceCallableCaster, - ); + ]; As you can notice, resource types are prefixed by a ``:`` to prevent colliding with a class name. diff --git a/components/yaml.rst b/components/yaml.rst index ab44a3526a4..adce112c41f 100644 --- a/components/yaml.rst +++ b/components/yaml.rst @@ -102,7 +102,7 @@ string and converts it to a PHP array:: use Symfony\Component\Yaml\Yaml; $value = Yaml::parse("foo: bar"); - // $value = array('foo' => 'bar') + // $value = ['foo' => 'bar'] If an error occurs during parsing, the parser throws a :class:`Symfony\\Component\\Yaml\\Exception\\ParseException` exception @@ -143,10 +143,10 @@ array to its YAML representation:: use Symfony\Component\Yaml\Yaml; - $array = array( + $array = [ 'foo' => 'bar', - 'bar' => array('foo' => 'bar', 'bar' => 'baz'), - ); + 'bar' => ['foo' => 'bar', 'bar' => 'baz'], + ]; $yaml = Yaml::dump($array); @@ -274,7 +274,7 @@ You can dump objects as Yaml maps by using the ``DUMP_OBJECT_AS_MAP`` flag:: $object = new \stdClass(); $object->foo = 'bar'; - $dumped = Yaml::dump(array('data' => $object), 2, 4, Yaml::DUMP_OBJECT_AS_MAP); + $dumped = Yaml::dump(['data' => $object], 2, 4, Yaml::DUMP_OBJECT_AS_MAP); // $dumped = "data:\n foo: bar" And parse them by using the ``PARSE_OBJECT_FOR_MAP`` flag:: @@ -327,14 +327,14 @@ Dumping Multi-line Literal Blocks In YAML multiple lines can be represented as literal blocks, by default the dumper will encode multiple lines as an inline string:: - $string = array("string" => "Multiple\nLine\nString"); + $string = ["string" => "Multiple\nLine\nString"]; $yaml = Yaml::dump($string); echo $yaml; // string: "Multiple\nLine\nString" You can make it use a literal block with the ``DUMP_MULTI_LINE_LITERAL_BLOCK`` flag:: - $string = array("string" => "Multiple\nLine\nString"); + $string = ["string" => "Multiple\nLine\nString"]; $yaml = Yaml::dump($string, 2, 4, Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK); echo $yaml; // string: | @@ -351,7 +351,7 @@ syntax to parse them as proper PHP constants:: $yaml = '{ foo: PHP_INT_SIZE, bar: !php/const PHP_INT_SIZE }'; $parameters = Yaml::parse($yaml, Yaml::PARSE_CONSTANT); - // $parameters = array('foo' => 'PHP_INT_SIZE', 'bar' => 8); + // $parameters = ['foo' => 'PHP_INT_SIZE', 'bar' => 8]; Parsing and Dumping of Binary Data ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -364,7 +364,7 @@ You can dump binary data by using the ``DUMP_BASE64_BINARY_DATA`` flag:: $imageContents = file_get_contents(__DIR__.'/images/logo.png'); - $dumped = Yaml::dump(array('logo' => $imageContents), 2, 4, Yaml::DUMP_BASE64_BINARY_DATA); + $dumped = Yaml::dump(['logo' => $imageContents], 2, 4, Yaml::DUMP_BASE64_BINARY_DATA); // logo: !!binary iVBORw0KGgoAAAANSUhEUgAAA6oAAADqCAY... Binary data is automatically parsed if they include the ``!!binary`` YAML tag @@ -387,16 +387,16 @@ In addition to the built-in support of tags like ``!php/const`` and $data = "!my_tag { foo: bar }"; $parsed = Yaml::parse($data, Yaml::PARSE_CUSTOM_TAGS); - // $parsed = Symfony\Component\Yaml\Tag\TaggedValue('my_tag', array('foo' => 'bar')); + // $parsed = Symfony\Component\Yaml\Tag\TaggedValue('my_tag', ['foo' => 'bar']); $tagName = $parsed->getTag(); // $tagName = 'my_tag' - $tagValue = $parsed->getValue(); // $tagValue = array('foo' => 'bar') + $tagValue = $parsed->getValue(); // $tagValue = ['foo' => 'bar'] If the contents to dump contain :class:`Symfony\\Component\\Yaml\\Tag\\TaggedValue` objects, they are automatically transformed into YAML tags:: use Symfony\Component\Yaml\Tag\TaggedValue; - $data = new TaggedValue('my_tag', array('foo' => 'bar')); + $data = new TaggedValue('my_tag', ['foo' => 'bar']); $dumped = Yaml::dump($data); // $dumped = '!my_tag { foo: bar }' diff --git a/components/yaml/yaml_format.rst b/components/yaml/yaml_format.rst index cbd2d1956ed..592d44d11cd 100644 --- a/components/yaml/yaml_format.rst +++ b/components/yaml/yaml_format.rst @@ -179,7 +179,7 @@ Sequences use a dash followed by a space: The previous YAML file is equivalent to the following PHP code:: - array('PHP', 'Perl', 'Python'); + ['PHP', 'Perl', 'Python']; Mappings use a colon followed by a space (``:`` ) to mark each key/value pair: @@ -191,7 +191,7 @@ Mappings use a colon followed by a space (``:`` ) to mark each key/value pair: which is equivalent to this PHP code:: - array('PHP' => 5.2, 'MySQL' => 5.1, 'Apache' => '2.2.20'); + ['PHP' => 5.2, 'MySQL' => 5.1, 'Apache' => '2.2.20']; .. note:: @@ -218,16 +218,16 @@ YAML uses indentation with one or more spaces to describe nested collections: The above YAML is equivalent to the following PHP code:: - array( - 'symfony 1.0' => array( + [ + 'symfony 1.0' => [ 'PHP' => 5.0, 'Propel' => 1.2, - ), - 'symfony 1.2' => array( + ], + 'symfony 1.2' => [ 'PHP' => 5.2, 'Propel' => 1.3, - ), - ); + ], + ]; There is one important thing you need to remember when using indentation in a YAML file: *Indentation must be done with one or more spaces, but never with diff --git a/configuration.rst b/configuration.rst index e6a4358210a..e972de44e31 100644 --- a/configuration.rst +++ b/configuration.rst @@ -74,19 +74,19 @@ The main configuration file is called ``config.yml``: $this->import('security.yml'); $this->import('services.yml'); - $container->loadFromExtension('framework', array( + $container->loadFromExtension('framework', [ 'secret' => '%secret%', - 'router' => array( + 'router' => [ 'resource' => '%kernel.project_dir%/app/config/routing.php', - ), + ], // ... - )); + ]); // Twig Configuration - $container->loadFromExtension('twig', array( + $container->loadFromExtension('twig', [ 'debug' => '%kernel.debug%', 'strict_variables' => '%kernel.debug%', - )); + ]); // ... @@ -276,10 +276,10 @@ key: $container->setParameter('locale', 'en'); - $container->loadFromExtension('framework', array( + $container->loadFromExtension('framework', [ 'default_locale' => '%locale%', // ... - )); + ]); // ... @@ -349,15 +349,15 @@ configure DoctrineBundle and other parts of Symfony: .. code-block:: php // app/config/config.php - $container->loadFromExtension('doctrine', array( - 'dbal' => array( + $container->loadFromExtension('doctrine', [ + 'dbal' => [ 'driver' => 'pdo_mysql', // ... 'user' => '%database_user%', 'password' => '%database_password%', - ), - )); + ], + ]); But the ``parameters.yml`` file *is* special: it defines the values that usually change on each server. For example, the database credentials on your local diff --git a/configuration/environments.rst b/configuration/environments.rst index abc5ab13e33..eadb3f8beb6 100644 --- a/configuration/environments.rst +++ b/configuration/environments.rst @@ -135,10 +135,10 @@ configuration file: // app/config/config_dev.php $loader->import('config.php'); - $container->loadFromExtension('web_profiler', array( + $container->loadFromExtension('web_profiler', [ 'toolbar' => true, // ... - )); + ]); .. index:: single: Environments; Executing different environments @@ -235,13 +235,13 @@ this code and changing the environment string. .. code-block:: php - $container->loadFromExtension('doctrine', array( - 'dbal' => array( + $container->loadFromExtension('doctrine', [ + 'dbal' => [ 'logging' => '%kernel.debug%', // ... - ), + ], // ... - )); + ]); Selecting the Environment for Console Commands ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -333,9 +333,9 @@ The best way to accomplish this is via a new environment called, for example, // app/config/config_benchmark.php $loader->import('config_prod.php'); - $container->loadFromExtension('framework', array( - 'profiler' => array('only_exceptions' => false), - )); + $container->loadFromExtension('framework', [ + 'profiler' => ['only_exceptions' => false], + ]); .. include:: /components/dependency_injection/_imports-parameters-note.rst.inc @@ -371,7 +371,7 @@ The new environment is now accessible via:: aren't accessible, the front controller is usually protected from external IP addresses via the following code at the top of the controller:: - if (!in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', '::1'))) { + if (!in_array(@$_SERVER['REMOTE_ADDR'], ['127.0.0.1', '::1'])) { die('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.'); } diff --git a/configuration/external_parameters.rst b/configuration/external_parameters.rst index 9e346f22cd4..7c08b001a2d 100644 --- a/configuration/external_parameters.rst +++ b/configuration/external_parameters.rst @@ -58,11 +58,11 @@ variable in your service container configuration, you can reference it using .. code-block:: php // app/config/config.php - $container->loadFromExtension('doctrine', array( - 'dbal' => array( + $container->loadFromExtension('doctrine', [ + 'dbal' => [ 'host' => '%env(DATABASE_HOST)%', - ), - )); + ], + ]); You can also give the ``env()`` parameters a default value: the default value will be used whenever the corresponding environment variable is *not* found: @@ -183,11 +183,11 @@ turn the value of the ``HTTP_PORT`` env var into an integer: .. code-block:: php // config/packages/framework.php - $container->loadFromExtension('framework', array( - 'router' => array( + $container->loadFromExtension('framework', [ + 'router' => [ 'http_port' => '%env(int:HTTP_PORT)%', - ), - )); + ], + ]); Symfony provides the following env var processors: @@ -227,9 +227,9 @@ Symfony provides the following env var processors: // config/packages/framework.php $container->setParameter('env(SECRET)', 'some_secret'); - $container->loadFromExtension('framework', array( + $container->loadFromExtension('framework', [ 'secret' => '%env(string:SECRET)%', - )); + ]); ``env(bool:FOO)`` Casts ``FOO`` to a bool: @@ -267,9 +267,9 @@ Symfony provides the following env var processors: // config/packages/framework.php $container->setParameter('env(HTTP_METHOD_OVERRIDE)', 'true'); - $container->loadFromExtension('framework', array( + $container->loadFromExtension('framework', [ 'http_method_override' => '%env(bool:HTTP_METHOD_OVERRIDE)%', - )); + ]); ``env(int:FOO)`` Casts ``FOO`` to an int. @@ -314,14 +314,14 @@ Symfony provides the following env var processors: // config/packages/security.php $container->setParameter('env(HEALTH_CHECK_METHOD)', 'Symfony\Component\HttpFoundation\Request::METHOD_HEAD'); - $container->loadFromExtension('security', array( - 'access_control' => array( - array( + $container->loadFromExtension('security', [ + 'access_control' => [ + [ 'path' => '^/health-check$', 'methods' => '%env(const:HEALTH_CHECK_METHOD)%', - ), - ), - )); + ], + ], + ]); ``env(base64:FOO)`` Decodes the content of ``FOO``, which is a base64 encoded string. @@ -363,9 +363,9 @@ Symfony provides the following env var processors: // config/packages/framework.php $container->setParameter('env(TRUSTED_HOSTS)', '["10.0.0.1", "10.0.0.2"]'); - $container->loadFromExtension('framework', array( + $container->loadFromExtension('framework', [ 'trusted_hosts' => '%env(json:TRUSTED_HOSTS)%', - )); + ]); ``env(resolve:FOO)`` Replaces the string ``FOO`` by the value of a config parameter with the @@ -404,9 +404,9 @@ Symfony provides the following env var processors: // config/packages/sentry.php $container->setParameter('env(HOST)', '10.0.0.1'); $container->setParameter('env(SENTRY_DSN)', 'http://%env(HOST)%/project'); - $container->loadFromExtension('sentry', array( + $container->loadFromExtension('sentry', [ 'dsn' => '%env(resolve:SENTRY_DSN)%', - )); + ]); ``env(file:FOO)`` Returns the contents of a file whose path is the value of the ``FOO`` env var: @@ -444,9 +444,9 @@ Symfony provides the following env var processors: // config/packages/framework.php $container->setParameter('env(AUTH_FILE)', '../config/auth.json'); - $container->loadFromExtension('google', array( + $container->loadFromExtension('google', [ 'auth' => '%env(file:AUTH_FILE)%', - )); + ]); It is also possible to combine any number of processors: diff --git a/configuration/micro_kernel_trait.rst b/configuration/micro_kernel_trait.rst index 3e07e117a8b..f43a0f1c054 100644 --- a/configuration/micro_kernel_trait.rst +++ b/configuration/micro_kernel_trait.rst @@ -40,17 +40,17 @@ Next, create an ``index.php`` file that creates a kernel class and executes it:: public function registerBundles() { - return array( + return [ new Symfony\Bundle\FrameworkBundle\FrameworkBundle() - ); + ]; } protected function configureContainer(ContainerBuilder $c, LoaderInterface $loader) { // PHP equivalent of config.yml - $c->loadFromExtension('framework', array( + $c->loadFromExtension('framework', [ 'secret' => 'S0ME_SECRET' - )); + ]); } protected function configureRoutes(RouteCollectionBuilder $routes) @@ -62,9 +62,9 @@ Next, create an ``index.php`` file that creates a kernel class and executes it:: public function randomAction($limit) { - return new JsonResponse(array( + return new JsonResponse([ 'number' => rand(0, $limit) - )); + ]); } } @@ -144,7 +144,7 @@ hold the kernel. Now it looks like this:: // require Composer's autoloader $loader = require __DIR__.'/../vendor/autoload.php'; // auto-load annotations - AnnotationRegistry::registerLoader(array($loader, 'loadClass')); + AnnotationRegistry::registerLoader([$loader, 'loadClass']); class AppKernel extends Kernel { @@ -152,10 +152,10 @@ hold the kernel. Now it looks like this:: public function registerBundles() { - $bundles = array( + $bundles = [ new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), - ); + ]; if ($this->getEnvironment() == 'dev') { $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle(); @@ -170,10 +170,10 @@ hold the kernel. Now it looks like this:: // configure WebProfilerBundle only if the bundle is enabled if (isset($this->bundles['WebProfilerBundle'])) { - $c->loadFromExtension('web_profiler', array( + $c->loadFromExtension('web_profiler', [ 'toolbar' => true, 'intercept_redirects' => false, - )); + ]); } } @@ -243,15 +243,15 @@ because the configuration started to get bigger: .. code-block:: php // app/config/config.php - $container->loadFromExtension('framework', array( + $container->loadFromExtension('framework', [ 'secret' => 'S0ME_SECRET', - 'templating' => array( - 'engines' => array('twig'), - ), - 'profiler' => array( + 'templating' => [ + 'engines' => ['twig'], + ], + 'profiler' => [ 'only_exceptions' => false, - ), - )); + ], + ]); This also loads annotation routes from an ``src/App/Controller/`` directory, which has one file in it:: @@ -271,9 +271,9 @@ has one file in it:: { $number = rand(0, $limit); - return $this->render('micro/random.html.twig', array( + return $this->render('micro/random.html.twig', [ 'number' => $number - )); + ]); } } diff --git a/configuration/override_dir_structure.rst b/configuration/override_dir_structure.rst index 7eb24df6e84..e757cb87b2e 100644 --- a/configuration/override_dir_structure.rst +++ b/configuration/override_dir_structure.rst @@ -127,11 +127,11 @@ define your own templates directory (or directories): .. code-block:: php // app/config/config.php - $container->loadFromExtension('twig', array( - 'paths' => array( + $container->loadFromExtension('twig', [ + 'paths' => [ '%kernel.project_dir%/templates', - ), - )); + ], + ]); .. _override-web-dir: @@ -206,10 +206,10 @@ You also need to change the ``extra.symfony-web-dir`` option in the // app/config/config.php // ... - $container->loadFromExtension('assetic', array( + $container->loadFromExtension('assetic', [ // ... 'read_from' => '%kernel.project_dir%/../public_html', - )); + ]); Now you just need to clear the cache and dump the assets again and your application should work: diff --git a/configuration/using_parameters_in_dic.rst b/configuration/using_parameters_in_dic.rst index 4d45d7738c2..4162c0c145c 100644 --- a/configuration/using_parameters_in_dic.rst +++ b/configuration/using_parameters_in_dic.rst @@ -70,19 +70,19 @@ Now, examine the results to see this closely: .. code-block:: php - $container->loadFromExtension('my_bundle', array( + $container->loadFromExtension('my_bundle', [ 'logging' => true, // true, as expected ) - ); + ]; - $container->loadFromExtension('my_bundle', array( + $container->loadFromExtension('my_bundle', [ 'logging' => "%kernel.debug%", // true/false (depends on 2nd parameter of AppKernel), // as expected, because %kernel.debug% inside configuration // gets evaluated before being passed to the extension ) - ); + ]; $container->loadFromExtension('my_bundle'); // passes the string "%kernel.debug%". diff --git a/console.rst b/console.rst index 477d301593b..857c6c81431 100644 --- a/console.rst +++ b/console.rst @@ -285,7 +285,7 @@ console:: $command = $application->find('app:create-user'); $commandTester = new CommandTester($command); - $commandTester->execute(array( + $commandTester->execute([ 'command' => $command->getName(), // pass arguments to the helper @@ -293,7 +293,7 @@ console:: // prefix the key with two dashes when passing options, // e.g: '--some-option' => 'option_value', - )); + ]); // the output of the command in the console $output = $commandTester->getDisplay(); diff --git a/console/calling_commands.rst b/console/calling_commands.rst index e8add467783..5d4c3d55e42 100644 --- a/console/calling_commands.rst +++ b/console/calling_commands.rst @@ -19,11 +19,11 @@ Calling a command from another one is straightforward:: { $command = $this->getApplication()->find('demo:greet'); - $arguments = array( + $arguments = [ 'command' => 'demo:greet', 'name' => 'Fabien', '--yell' => true, - ); + ]; $greetInput = new ArrayInput($arguments); $returnCode = $command->run($greetInput, $output); diff --git a/console/coloring.rst b/console/coloring.rst index 2793a709fd5..a5b3adf8dfa 100644 --- a/console/coloring.rst +++ b/console/coloring.rst @@ -40,7 +40,7 @@ It is possible to define your own styles using the use Symfony\Component\Console\Formatter\OutputFormatterStyle; // ... - $outputStyle = new OutputFormatterStyle('red', 'yellow', array('bold', 'blink')); + $outputStyle = new OutputFormatterStyle('red', 'yellow', ['bold', 'blink']); $output->getFormatter()->setStyle('fire', $outputStyle); $output->writeln('foo'); diff --git a/console/command_in_controller.rst b/console/command_in_controller.rst index e01706fdfba..bef73d3b0aa 100644 --- a/console/command_in_controller.rst +++ b/console/command_in_controller.rst @@ -41,13 +41,13 @@ Run this command from inside your controller via:: $application = new Application($kernel); $application->setAutoExit(false); - $input = new ArrayInput(array( + $input = new ArrayInput([ 'command' => 'swiftmailer:spool:send', // (optional) define the value of command arguments 'fooArgument' => 'barValue', // (optional) pass options to the command '--message-limit' => $messages, - )); + ]); // You can use NullOutput() if you don't need the output $output = new BufferedOutput(); diff --git a/console/commands_as_services.rst b/console/commands_as_services.rst index 1f35663c454..6957cbd4b5d 100644 --- a/console/commands_as_services.rst +++ b/console/commands_as_services.rst @@ -126,7 +126,7 @@ Or set the ``command`` attribute on the ``console.command`` tag in your service $container ->register(SunshineCommand::class) - ->addTag('console.command', array('command' => 'app:sunshine')) + ->addTag('console.command', ['command' => 'app:sunshine']) ; .. note:: diff --git a/console/input.rst b/console/input.rst index fdc9e4e9239..2f570e73d4d 100644 --- a/console/input.rst +++ b/console/input.rst @@ -220,7 +220,7 @@ You can combine ``VALUE_IS_ARRAY`` with ``VALUE_REQUIRED`` or null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Which colors do you like?', - array('blue', 'red') + ['blue', 'red'] ); Options with optional arguments diff --git a/console/lazy_commands.rst b/console/lazy_commands.rst index 5d1d124a593..9c4e9585e07 100644 --- a/console/lazy_commands.rst +++ b/console/lazy_commands.rst @@ -21,9 +21,9 @@ which will be responsible for returning ``Command`` instances:: use Symfony\Component\Console\Application; use Symfony\Component\Console\CommandLoader\FactoryCommandLoader; - $commandLoader = new FactoryCommandLoader(array( + $commandLoader = new FactoryCommandLoader([ 'app:heavy' => function () { return new HeavyCommand(); }, - )); + ]); $application = new Application(); $application->setCommandLoader($commandLoader); @@ -51,10 +51,10 @@ array of ``Command`` factories as its only constructor argument:: use Symfony\Component\Console\CommandLoader\FactoryCommandLoader; - $commandLoader = new FactoryCommandLoader(array( + $commandLoader = new FactoryCommandLoader([ 'app:foo' => function () { return new FooCommand(); }, - 'app:bar' => array(BarCommand::class, 'create'), - )); + 'app:bar' => [BarCommand::class, 'create'], + ]); Factories can be any PHP callable and will be executed each time :method:`Symfony\\Component\\Console\\CommandLoader\\FactoryCommandLoader::get` @@ -76,9 +76,9 @@ with command names as keys and service identifiers as values:: $containerBuilder->register(FooCommand::class, FooCommand::class); $containerBuilder->compile(); - $commandLoader = new ContainerCommandLoader($containerBuilder, array( + $commandLoader = new ContainerCommandLoader($containerBuilder, [ 'app:foo' => FooCommand::class, - )); + ]); Like this, executing the ``app:foo`` command will load the ``FooCommand`` service by calling ``$containerBuilder->get(FooCommand::class)``. diff --git a/console/request_context.rst b/console/request_context.rst index 2cdac8cb9a7..06b8a338b99 100644 --- a/console/request_context.rst +++ b/console/request_context.rst @@ -88,7 +88,7 @@ from the ``router`` service and override its settings:: $context->setScheme('https'); $context->setBaseUrl('my/path'); - $url = $router->generate('route-name', array('param-name' => 'param-value')); + $url = $router->generate('route-name', ['param-name' => 'param-value']); // ... } } diff --git a/console/style.rst b/console/style.rst index caa61737132..9f84081278c 100644 --- a/console/style.rst +++ b/console/style.rst @@ -23,11 +23,11 @@ Consider for example the code used to display the title of the following command protected function execute(InputInterface $input, OutputInterface $output) { - $output->writeln(array( + $output->writeln([ 'Lorem Ipsum Dolor Sit Amet', '==========================', '', - )); + ]); // ... } @@ -113,31 +113,31 @@ Content Methods // ... // consider using arrays when displaying long messages - $io->text(array( + $io->text([ 'Lorem ipsum dolor sit amet', 'Consectetur adipiscing elit', 'Aenean sit amet arcu vitae sem faucibus porta', - )); + ]); :method:`Symfony\\Component\\Console\\Style\\SymfonyStyle::listing` It displays an unordered list of elements passed as an array:: - $io->listing(array( + $io->listing([ 'Element #1 Lorem ipsum dolor sit amet', 'Element #2 Lorem ipsum dolor sit amet', 'Element #3 Lorem ipsum dolor sit amet', - )); + ]); :method:`Symfony\\Component\\Console\\Style\\SymfonyStyle::table` It displays the given array of headers and rows as a compact table:: $io->table( - array('Header 1', 'Header 2'), - array( - array('Cell 1-1', 'Cell 1-2'), - array('Cell 2-1', 'Cell 2-2'), - array('Cell 3-1', 'Cell 3-2'), - ) + ['Header 1', 'Header 2'], + [ + ['Cell 1-1', 'Cell 1-2'], + ['Cell 2-1', 'Cell 2-2'], + ['Cell 3-1', 'Cell 3-2'], + ] ); :method:`Symfony\\Component\\Console\\Style\\SymfonyStyle::newLine` @@ -165,11 +165,11 @@ Admonition Methods // ... // consider using arrays when displaying long notes - $io->note(array( + $io->note([ 'Lorem ipsum dolor sit amet', 'Consectetur adipiscing elit', 'Aenean sit amet arcu vitae sem faucibus porta', - )); + ]); :method:`Symfony\\Component\\Console\\Style\\SymfonyStyle::caution` Similar to the ``note()`` helper, but the contents are more prominently @@ -182,11 +182,11 @@ Admonition Methods // ... // consider using arrays when displaying long caution messages - $io->caution(array( + $io->caution([ 'Lorem ipsum dolor sit amet', 'Consectetur adipiscing elit', 'Aenean sit amet arcu vitae sem faucibus porta', - )); + ]); Progress Bar Methods ~~~~~~~~~~~~~~~~~~~~ @@ -271,12 +271,12 @@ User Input Methods It asks a question whose answer is constrained to the given list of valid answers:: - $io->choice('Select the queue to analyze', array('queue1', 'queue2', 'queue3')); + $io->choice('Select the queue to analyze', ['queue1', 'queue2', 'queue3']); You can pass the default value as the third argument so the user can simply hit the key to select that value:: - $io->choice('Select the queue to analyze', array('queue1', 'queue2', 'queue3'), 'queue1'); + $io->choice('Select the queue to analyze', ['queue1', 'queue2', 'queue3'], 'queue1'); Result Methods ~~~~~~~~~~~~~~ @@ -293,10 +293,10 @@ Result Methods // ... // consider using arrays when displaying long success messages - $io->success(array( + $io->success([ 'Lorem ipsum dolor sit amet', 'Consectetur adipiscing elit', - )); + ]); :method:`Symfony\\Component\\Console\\Style\\SymfonyStyle::warning` It displays the given string or array of strings highlighted as a warning @@ -310,10 +310,10 @@ Result Methods // ... // consider using arrays when displaying long warning messages - $io->warning(array( + $io->warning([ 'Lorem ipsum dolor sit amet', 'Consectetur adipiscing elit', - )); + ]); :method:`Symfony\\Component\\Console\\Style\\SymfonyStyle::error` It displays the given string or array of strings highlighted as an error @@ -327,10 +327,10 @@ Result Methods // ... // consider using arrays when displaying long error messages - $io->error(array( + $io->error([ 'Lorem ipsum dolor sit amet', 'Consectetur adipiscing elit', - )); + ]); Defining your Own Styles ------------------------ diff --git a/console/verbosity.rst b/console/verbosity.rst index be42fac5e81..c16737c2b61 100644 --- a/console/verbosity.rst +++ b/console/verbosity.rst @@ -53,10 +53,10 @@ level. For example:: { $user = new User(...); - $output->writeln(array( + $output->writeln([ 'Username: '.$input->getArgument('username'), 'Password: '.$input->getArgument('password'), - )); + ]); // available methods: ->isQuiet(), ->isVerbose(), ->isVeryVerbose(), ->isDebug() if ($output->isVerbose()) { diff --git a/contributing/code/standards.rst b/contributing/code/standards.rst index f734ec7946a..8b28f2d64a7 100644 --- a/contributing/code/standards.rst +++ b/contributing/code/standards.rst @@ -86,12 +86,12 @@ short example containing most features described below: * * @throws \RuntimeException When an invalid option is provided */ - private function transformText($dummy, array $options = array()) + private function transformText($dummy, array $options = []) { - $defaultOptions = array( + $defaultOptions = [ 'some_default' => 'values', 'another_default' => 'more values', - ); + ]; foreach ($options as $option) { if (!in_array($option, $defaultOptions)) { diff --git a/contributing/community/review-comments.rst b/contributing/community/review-comments.rst index a317c12fa27..d64ceb880d0 100644 --- a/contributing/community/review-comments.rst +++ b/contributing/community/review-comments.rst @@ -113,7 +113,7 @@ If a piece of code is in fact wrong, explain why: * I profiled this change and it hurts performance significantly (if you don't profile, it's an opinion, so we can ignore) - * Code doesn't match Symfony's CS rules (e.g. ``use array()`` instead of ``[]``) + * Code doesn't match Symfony's CS rules (e.g. use ``[]`` instead of ``array()``) * We only provide integration with very popular projects (e.g. we integrate Bootstrap but not your own CSS framework) diff --git a/controller.rst b/controller.rst index bf2c879e882..48668f8ae85 100644 --- a/controller.rst +++ b/controller.rst @@ -167,7 +167,7 @@ Generating URLs The :method:`Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller::generateUrl` method is just a helper method that generates the URL for a given route:: - $url = $this->generateUrl('blog_show', array('slug' => 'slug-value')); + $url = $this->generateUrl('blog_show', ['slug' => 'slug-value']); Redirecting ~~~~~~~~~~~ @@ -181,10 +181,10 @@ and ``redirect()`` methods:: return $this->redirectToRoute('homepage'); // does a permanent - 301 redirect - return $this->redirectToRoute('homepage', array(), 301); + return $this->redirectToRoute('homepage', [], 301); // redirects to a route with parameters - return $this->redirectToRoute('blog_show', array('slug' => 'my-page')); + return $this->redirectToRoute('blog_show', ['slug' => 'my-page']); // redirects to a route and mantains the original query string parameters return $this->redirectToRoute('blog_show', $request->query->all()); @@ -227,15 +227,15 @@ method renders a template **and** puts that content into a ``Response`` object for you:: // renders app/Resources/views/lucky/number.html.twig - return $this->render('lucky/number.html.twig', array('number' => $number)); + return $this->render('lucky/number.html.twig', ['number' => $number]); Templates can also live in deeper sub-directories. Just try to avoid creating unnecessarily deep structures:: // renders app/Resources/views/lottery/lucky/number.html.twig - return $this->render('lottery/lucky/number.html.twig', array( + return $this->render('lottery/lucky/number.html.twig', [ 'number' => $number, - )); + ]); The Symfony templating system and Twig are explained more in the :doc:`Creating and Using Templates article `. @@ -329,9 +329,9 @@ the argument by its name: $container->register(LuckyController::class) ->setPublic(true) - ->setBindings(array( + ->setBindings([ '$logger' => new Reference('monolog.logger.doctrine'), - )) + ]) ; You can of course also use normal :ref:`constructor injection ` @@ -484,7 +484,7 @@ type-hint to your argument and Symfony will provide you with a session:: $foobar = $session->get('foobar'); // uses a default value if the attribute doesn't exist - $filters = $session->get('filters', array()); + $filters = $session->get('filters', []); } Stored attributes remain in the session for the remainder of that user's session. @@ -590,7 +590,7 @@ the ``Request`` class:: { $request->isXmlHttpRequest(); // is it an Ajax request? - $request->getPreferredLanguage(array('en', 'fr')); + $request->getPreferredLanguage(['en', 'fr']); // retrieves GET and POST variables respectively $request->query->get('page'); @@ -658,10 +658,10 @@ This returns a special ``JsonResponse`` object that encodes the data automatical public function indexAction() { // returns '{"username":"jane.doe"}' and sets the proper Content-Type header - return $this->json(array('username' => 'jane.doe')); + return $this->json(['username' => 'jane.doe']); // the shortcut defines three optional arguments - // return $this->json($data, $status = 200, $headers = array(), $context = array()); + // return $this->json($data, $status = 200, $headers = [], $context = []); } If the :doc:`serializer service ` is enabled in your diff --git a/controller/argument_value_resolver.rst b/controller/argument_value_resolver.rst index b7c9aad74c4..5aae993f2e9 100644 --- a/controller/argument_value_resolver.rst +++ b/controller/argument_value_resolver.rst @@ -104,12 +104,12 @@ type-hinted method arguments: .. code-block:: php // app/config/config.php - $container->loadFromExtension('sensio_framework_extra', array( - 'request' => array( + $container->loadFromExtension('sensio_framework_extra', [ + 'request' => [ 'converters' => true, 'auto_convert' => false, - ), - )); + ], + ]); Adding a new value resolver requires creating a class that implements :class:`Symfony\\Component\\HttpKernel\\Controller\\ArgumentValueResolverInterface` @@ -219,7 +219,7 @@ and adding a priority. use AppBundle\ArgumentResolver\UserValueResolver; $container->autowire(UserValueResolver::class) - ->addTag('controller.argument_value_resolver', array('priority' => 50)); + ->addTag('controller.argument_value_resolver', ['priority' => 50]); While adding a priority is optional, it's recommended to add one to make sure the expected value is injected. The ``RequestAttributeValueResolver`` has a diff --git a/controller/error_pages.rst b/controller/error_pages.rst index b2e45950e10..2ff82a3c382 100644 --- a/controller/error_pages.rst +++ b/controller/error_pages.rst @@ -230,10 +230,10 @@ configuration option to point to it: .. code-block:: php // app/config/config.php - $container->loadFromExtension('twig', array( + $container->loadFromExtension('twig', [ 'exception_controller' => 'AppBundle:Exception:showException', // ... - )); + ]); The :class:`Symfony\\Component\\HttpKernel\\EventListener\\ExceptionListener` class used by the TwigBundle as a listener of the ``kernel.exception`` event creates diff --git a/controller/forwarding.rst b/controller/forwarding.rst index df8a4c685b1..cf727128436 100644 --- a/controller/forwarding.rst +++ b/controller/forwarding.rst @@ -13,10 +13,10 @@ from *that* controller:: public function indexAction($name) { - $response = $this->forward('AppBundle:Something:fancy', array( + $response = $this->forward('AppBundle:Something:fancy', [ 'name' => $name, 'color' => 'green', - )); + ]); // ... further modify the response or return it directly diff --git a/controller/service.rst b/controller/service.rst index de890956973..c7a044bec33 100644 --- a/controller/service.rst +++ b/controller/service.rst @@ -64,9 +64,9 @@ syntax: .. code-block:: php // app/config/routing.php - $collection->add('hello', new Route('/hello', array( + $collection->add('hello', new Route('/hello', [ '_controller' => 'app.hello_controller:indexAction', - ))); + ])); .. note:: @@ -116,7 +116,7 @@ service and use it directly:: { $content = $this->twig->render( 'hello/index.html.twig', - array('name' => $name) + ['name' => $name] ); return new Response($content); diff --git a/controller/soap_web_service.rst b/controller/soap_web_service.rst index ec54c5a9f0d..d531613f14c 100644 --- a/controller/soap_web_service.rst +++ b/controller/soap_web_service.rst @@ -101,7 +101,7 @@ route ``/soap``:: $soapClient = new \SoapClient('http://example.com/app.php/soap?wsdl'); - $result = $soapClient->call('hello', array('name' => 'Scott')); + $result = $soapClient->call('hello', ['name' => 'Scott']); An example WSDL is below. diff --git a/controller/upload_file.rst b/controller/upload_file.rst index 8eded88cb70..4c853d8c8f3 100644 --- a/controller/upload_file.rst +++ b/controller/upload_file.rst @@ -66,16 +66,16 @@ Then, add a new ``brochure`` field to the form that manages the ``Product`` enti { $builder // ... - ->add('brochure', FileType::class, array('label' => 'Brochure (PDF file)')) + ->add('brochure', FileType::class, ['label' => 'Brochure (PDF file)']) // ... ; } public function configureOptions(OptionsResolver $resolver) { - $resolver->setDefaults(array( + $resolver->setDefaults([ 'data_class' => Product::class, - )); + ]); } } @@ -143,9 +143,9 @@ Finally, you need to update the code of the controller that handles the form:: return $this->redirect($this->generateUrl('app_product_list')); } - return $this->render('product/new.html.twig', array( + return $this->render('product/new.html.twig', [ 'form' => $form->createView(), - )); + ]); } /** @@ -414,12 +414,12 @@ Now, register this class as a Doctrine listener: use AppBundle\EventListener\BrochureUploaderListener; $container->autowire(BrochureUploaderListener::class) - ->addTag('doctrine.event_listener', array( + ->addTag('doctrine.event_listener', [ 'event' => 'prePersist', - )) - ->addTag('doctrine.event_listener', array( + ]) + ->addTag('doctrine.event_listener', [ 'event' => 'preUpdate', - )) + ]) ; This listener is now automatically executed when persisting a new Product diff --git a/create_framework/dependency_injection.rst b/create_framework/dependency_injection.rst index a1609ec3838..ed8b804718d 100644 --- a/create_framework/dependency_injection.rst +++ b/create_framework/dependency_injection.rst @@ -108,33 +108,33 @@ Create a new file to host the dependency injection container configuration:: $containerBuilder = new DependencyInjection\ContainerBuilder(); $containerBuilder->register('context', Routing\RequestContext::class); $containerBuilder->register('matcher', Routing\Matcher\UrlMatcher::class) - ->setArguments(array($routes, new Reference('context'))) + ->setArguments([$routes, new Reference('context')]) ; $containerBuilder->register('request_stack', HttpFoundation\RequestStack::class); $containerBuilder->register('controller_resolver', HttpKernel\Controller\ControllerResolver::class); $containerBuilder->register('argument_resolver', HttpKernel\Controller\ArgumentResolver::class); $containerBuilder->register('listener.router', HttpKernel\EventListener\RouterListener::class) - ->setArguments(array(new Reference('matcher'), new Reference('request_stack'))) + ->setArguments([new Reference('matcher'), new Reference('request_stack')]) ; $containerBuilder->register('listener.response', HttpKernel\EventListener\ResponseListener::class) - ->setArguments(array('UTF-8')) + ->setArguments(['UTF-8']) ; $containerBuilder->register('listener.exception', HttpKernel\EventListener\ExceptionListener::class) - ->setArguments(array('Calendar\Controller\ErrorController::exceptionAction')) + ->setArguments(['Calendar\Controller\ErrorController::exceptionAction']) ; $containerBuilder->register('dispatcher', EventDispatcher\EventDispatcher::class) - ->addMethodCall('addSubscriber', array(new Reference('listener.router'))) - ->addMethodCall('addSubscriber', array(new Reference('listener.response'))) - ->addMethodCall('addSubscriber', array(new Reference('listener.exception'))) + ->addMethodCall('addSubscriber', [new Reference('listener.router')]) + ->addMethodCall('addSubscriber', [new Reference('listener.response')]) + ->addMethodCall('addSubscriber', [new Reference('listener.exception')]) ; $containerBuilder->register('framework', Framework::class) - ->setArguments(array( + ->setArguments([ new Reference('dispatcher'), new Reference('controller_resolver'), new Reference('request_stack'), new Reference('argument_resolver'), - )) + ]) ; return $containerBuilder; @@ -198,7 +198,7 @@ Now, here is how you can register a custom listener in the front controller:: $container->register('listener.string_response', StringResponseListener::class); $container->getDefinition('dispatcher') - ->addMethodCall('addSubscriber', array(new Reference('listener.string_response'))) + ->addMethodCall('addSubscriber', [new Reference('listener.string_response')]) ; Beside describing your objects, the dependency injection container can also be @@ -214,7 +214,7 @@ charset configurable:: // ... $container->register('listener.response', HttpKernel\EventListener\ResponseListener::class) - ->setArguments(array('%charset%')) + ->setArguments(['%charset%']) ; After this change, you must set the charset before using the response listener @@ -227,7 +227,7 @@ Instead of relying on the convention that the routes are defined by the // ... $container->register('matcher', Routing\Matcher\UrlMatcher::class) - ->setArguments(array('%routes%', new Reference('context'))) + ->setArguments(['%routes%', new Reference('context')]) ; And the related change in the front controller:: diff --git a/create_framework/event_dispatcher.rst b/create_framework/event_dispatcher.rst index 8939659bd4f..7c515da2b15 100644 --- a/create_framework/event_dispatcher.rst +++ b/create_framework/event_dispatcher.rst @@ -240,8 +240,8 @@ And do the same with the other listener:: Our front controller should now look like the following:: $dispatcher = new EventDispatcher(); - $dispatcher->addListener('response', array(new Simplex\ContentLengthListener(), 'onResponse'), -255); - $dispatcher->addListener('response', array(new Simplex\GoogleListener(), 'onResponse')); + $dispatcher->addListener('response', [new Simplex\ContentLengthListener(), 'onResponse'], -255); + $dispatcher->addListener('response', [new Simplex\GoogleListener(), 'onResponse']); Even if the code is now nicely wrapped in classes, there is still a slight issue: the knowledge of the priorities is "hardcoded" in the front controller, @@ -270,7 +270,7 @@ look at the new version of the ``GoogleListener``:: public static function getSubscribedEvents() { - return array('response' => 'onResponse'); + return ['response' => 'onResponse']; } } @@ -287,7 +287,7 @@ And here is the new version of ``ContentLengthListener``:: public static function getSubscribedEvents() { - return array('response' => array('onResponse', -255)); + return ['response' => ['onResponse', -255]]; } } diff --git a/create_framework/front_controller.rst b/create_framework/front_controller.rst index b2acfc06ade..2f271e5b704 100644 --- a/create_framework/front_controller.rst +++ b/create_framework/front_controller.rst @@ -80,10 +80,10 @@ Such a script might look like the following:: $request = Request::createFromGlobals(); $response = new Response(); - $map = array( + $map = [ '/hello' => __DIR__.'/hello.php', '/bye' => __DIR__.'/bye.php', - ); + ]; $path = $request->getPathInfo(); if (isset($map[$path])) { @@ -203,10 +203,10 @@ We have the first version of our framework:: $request = Request::createFromGlobals(); $response = new Response(); - $map = array( + $map = [ '/hello' => __DIR__.'/../src/pages/hello.php', '/bye' => __DIR__.'/../src/pages/bye.php', - ); + ]; $path = $request->getPathInfo(); if (isset($map[$path])) { diff --git a/create_framework/http_foundation.rst b/create_framework/http_foundation.rst index d54990def79..52d6950c0c3 100644 --- a/create_framework/http_foundation.rst +++ b/create_framework/http_foundation.rst @@ -256,7 +256,7 @@ code in production without a proxy, it becomes trivially easy to abuse your system. That's not the case with the ``getClientIp()`` method as you must explicitly trust your reverse proxies by calling ``setTrustedProxies()``:: - Request::setTrustedProxies(array('10.0.0.1')); + Request::setTrustedProxies(['10.0.0.1']); if ($myIp === $request->getClientIp()) { // the client is a known one, so give it some more privilege diff --git a/create_framework/http_kernel_controller_resolver.rst b/create_framework/http_kernel_controller_resolver.rst index b1b8bdaee17..48a331ed36d 100644 --- a/create_framework/http_kernel_controller_resolver.rst +++ b/create_framework/http_kernel_controller_resolver.rst @@ -22,10 +22,10 @@ class:: Update the route definition accordingly:: - $routes->add('leap_year', new Routing\Route('/is_leap_year/{year}', array( + $routes->add('leap_year', new Routing\Route('/is_leap_year/{year}', [ 'year' => null, - '_controller' => array(new LeapYearController(), 'indexAction'), - ))); + '_controller' => [new LeapYearController(), 'indexAction'], + ])); The move is pretty straightforward and makes a lot of sense as soon as you create more pages but you might have noticed a non-desirable side-effect... @@ -72,10 +72,10 @@ controller associated with the Request. Besides the built-in PHP callbacks, ``getController()`` also supports strings composed of a class name followed by two colons and a method name as a valid callback, like 'class::method':: - $routes->add('leap_year', new Routing\Route('/is_leap_year/{year}', array( + $routes->add('leap_year', new Routing\Route('/is_leap_year/{year}', [ 'year' => null, '_controller' => 'LeapYearController::indexAction', - ))); + ])); To make this code work, modify the framework code to use the controller resolver from HttpKernel:: diff --git a/create_framework/http_kernel_httpkernel_class.rst b/create_framework/http_kernel_httpkernel_class.rst index 94191eeb102..07e7820c3df 100644 --- a/create_framework/http_kernel_httpkernel_class.rst +++ b/create_framework/http_kernel_httpkernel_class.rst @@ -170,7 +170,7 @@ only if needed:: public static function getSubscribedEvents() { - return array('kernel.view' => 'onView'); + return ['kernel.view' => 'onView']; } } diff --git a/create_framework/http_kernel_httpkernelinterface.rst b/create_framework/http_kernel_httpkernelinterface.rst index 13f98119eb2..2d7c2ed053f 100644 --- a/create_framework/http_kernel_httpkernelinterface.rst +++ b/create_framework/http_kernel_httpkernelinterface.rst @@ -119,13 +119,13 @@ abstracts the most frequently used caching strategies into one simple array:: $date = date_create_from_format('Y-m-d H:i:s', '2005-10-15 10:00:00'); - $response->setCache(array( + $response->setCache([ 'public' => true, 'etag' => 'abcde', 'last_modified' => $date, 'max_age' => 10, 's_maxage' => 10, - )); + ]); // it is equivalent to the following code $response->setPublic(); @@ -186,7 +186,7 @@ ease debugging, you can enable the debug mode:: $framework, new HttpKernel\HttpCache\Store(__DIR__.'/../cache'), new HttpKernel\HttpCache\Esi(), - array('debug' => true) + ['debug' => true] ); The debug mode adds a ``X-Symfony-Cache`` header to each response that diff --git a/create_framework/routing.rst b/create_framework/routing.rst index cafe4beb7ce..ef3307ccd99 100644 --- a/create_framework/routing.rst +++ b/create_framework/routing.rst @@ -12,10 +12,10 @@ framework just a little to make templates even more readable:: $request = Request::createFromGlobals(); - $map = array( + $map = [ '/hello' => 'hello', '/bye' => 'bye', - ); + ]; $path = $request->getPathInfo(); if (isset($map[$path])) { @@ -61,12 +61,12 @@ one for the simple ``/bye`` one:: use Symfony\Component\Routing\Route; - $routes->add('hello', new Route('/hello/{name}', array('name' => 'World'))); + $routes->add('hello', new Route('/hello/{name}', ['name' => 'World'])); $routes->add('bye', new Route('/bye')); Each entry in the collection is defined by a name (``hello``) and a ``Route`` instance, which is defined by a route pattern (``/hello/{name}``) and an array -of default values for route attributes (``array('name' => 'World')``). +of default values for route attributes (``['name' => 'World']``). .. note:: @@ -174,7 +174,7 @@ There are a few new things in the code: use Symfony\Component\Routing; $routes = new Routing\RouteCollection(); - $routes->add('hello', new Routing\Route('/hello/{name}', array('name' => 'World'))); + $routes->add('hello', new Routing\Route('/hello/{name}', ['name' => 'World'])); $routes->add('bye', new Routing\Route('/bye')); return $routes; @@ -195,7 +195,7 @@ impact. Want to know how to use the generator? Insanely easy:: $generator = new Routing\Generator\UrlGenerator($routes, $context); - echo $generator->generate('hello', array('name' => 'Fabien')); + echo $generator->generate('hello', ['name' => 'Fabien']); // outputs /hello/Fabien The code should be self-explanatory; and thanks to the context, you can even @@ -205,7 +205,7 @@ generate absolute URLs:: echo $generator->generate( 'hello', - array('name' => 'Fabien'), + ['name' => 'Fabien'], UrlGeneratorInterface::ABSOLUTE_URL ); // outputs something like http://example.com/somewhere/hello/Fabien diff --git a/create_framework/separation_of_concerns.rst b/create_framework/separation_of_concerns.rst index 84db81611e0..9ed5a65f258 100644 --- a/create_framework/separation_of_concerns.rst +++ b/create_framework/separation_of_concerns.rst @@ -136,10 +136,10 @@ And move the ``is_leap_year()`` function to its own class too:: Don't forget to update the ``example.com/src/app.php`` file accordingly:: - $routes->add('leap_year', new Routing\Route('/is_leap_year/{year}', array( + $routes->add('leap_year', new Routing\Route('/is_leap_year/{year}', [ 'year' => null, '_controller' => 'Calendar\Controller\LeapYearController::indexAction', - ))); + ])); To sum up, here is the new file layout: diff --git a/create_framework/templating.rst b/create_framework/templating.rst index a00f5b352fb..8b2801c8e5a 100644 --- a/create_framework/templating.rst +++ b/create_framework/templating.rst @@ -55,10 +55,10 @@ controller... your choice. As a convention, for each route, the associated controller is configured via the ``_controller`` route attribute:: - $routes->add('hello', new Routing\Route('/hello/{name}', array( + $routes->add('hello', new Routing\Route('/hello/{name}', [ 'name' => 'World', '_controller' => 'render_template', - ))); + ])); try { $request->attributes->add($matcher->match($request->getPathInfo())); @@ -72,17 +72,17 @@ the ``_controller`` route attribute:: A route can now be associated with any controller and of course, within a controller, you can still use the ``render_template()`` to render a template:: - $routes->add('hello', new Routing\Route('/hello/{name}', array( + $routes->add('hello', new Routing\Route('/hello/{name}', [ 'name' => 'World', '_controller' => function ($request) { return render_template($request); } - ))); + ])); This is rather flexible as you can change the Response object afterwards and you can even pass additional arguments to the template:: - $routes->add('hello', new Routing\Route('/hello/{name}', array( + $routes->add('hello', new Routing\Route('/hello/{name}', [ 'name' => 'World', '_controller' => function ($request) { // $foo will be available in the template @@ -95,7 +95,7 @@ you can even pass additional arguments to the template:: return $response; } - ))); + ])); Here is the updated and improved version of our framework:: @@ -154,7 +154,7 @@ framework does not need to be modified in any way, just create a new } $routes = new Routing\RouteCollection(); - $routes->add('leap_year', new Routing\Route('/is_leap_year/{year}', array( + $routes->add('leap_year', new Routing\Route('/is_leap_year/{year}', [ 'year' => null, '_controller' => function ($request) { if (is_leap_year($request->attributes->get('year'))) { @@ -163,7 +163,7 @@ framework does not need to be modified in any way, just create a new return new Response('Nope, this is not a leap year.'); } - ))); + ])); return $routes; diff --git a/create_framework/unit_testing.rst b/create_framework/unit_testing.rst index d3bb5f623a4..17cf79393be 100644 --- a/create_framework/unit_testing.rst +++ b/create_framework/unit_testing.rst @@ -164,13 +164,13 @@ Response:: $matcher ->expects($this->once()) ->method('match') - ->will($this->returnValue(array( + ->will($this->returnValue([ '_route' => 'foo', 'name' => 'Fabien', '_controller' => function ($name) { return new Response('Hello '.$name); } - ))) + ])) ; $matcher ->expects($this->once()) diff --git a/deployment/fortrabbit.rst b/deployment/fortrabbit.rst index ffe968e813d..2c4b4edfc97 100644 --- a/deployment/fortrabbit.rst +++ b/deployment/fortrabbit.rst @@ -61,14 +61,14 @@ to redirect it to :phpfunction:`error_log`: .. code-block:: php // app/config/config_prod.php - $container->loadFromExtension('monolog', array( + $container->loadFromExtension('monolog', [ // ... - 'handlers' => array( - 'nested' => array( + 'handlers' => [ + 'nested' => [ 'type' => 'error_log', - ), - ), - )); + ], + ], + ]); Configuring Database Access & Session Handler ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -98,7 +98,7 @@ contents:: // check if the Memcache component is present if (isset($secrets['MEMCACHE'])) { $memcache = $secrets['MEMCACHE']; - $handlers = array(); + $handlers = []; foreach (range(1, $memcache['COUNT']) as $num) { $handlers[] = $memcache['HOST'.$num].':'.$memcache['PORT'.$num]; @@ -161,11 +161,11 @@ Make sure this file is imported into the main config file: $loader->import('config.php'); $loader->import('config_prod_secrets.php'); - $container->loadFromExtension('framework', array( - 'session' => array( + $container->loadFromExtension('framework', [ + 'session' => [ 'handler_id' => null, - ), - )); + ], + ]); // ... diff --git a/deployment/proxies.rst b/deployment/proxies.rst index 25a8026108c..9c4f7c4c9de 100644 --- a/deployment/proxies.rst +++ b/deployment/proxies.rst @@ -70,7 +70,7 @@ In this case, you'll need to - *very carefully* - trust *all* proxies. // ... Request::setTrustedProxies( // trust *all* requests - array('127.0.0.1', $request->server->get('REMOTE_ADDR')), + ['127.0.0.1', $request->server->get('REMOTE_ADDR')], // if you're using ELB, otherwise use a constant from above Request::HEADER_X_FORWARDED_AWS_ELB diff --git a/doctrine.rst b/doctrine.rst index d5081462cac..aa029025461 100644 --- a/doctrine.rst +++ b/doctrine.rst @@ -100,15 +100,15 @@ information. By convention, this information is usually configured in an .. code-block:: php // app/config/config.php - $container->loadFromExtension('doctrine', array( - 'dbal' => array( + $container->loadFromExtension('doctrine', [ + 'dbal' => [ 'driver' => 'pdo_mysql', 'host' => '%database_host%', 'dbname' => '%database_name%', 'user' => '%database_user%', 'password' => '%database_password%', - ), - )); + ], + ]); By separating the database information into a separate file, you can easily keep different versions of the file on each server. You can also @@ -185,15 +185,15 @@ can automatically generate an empty ``test_project`` database for you: .. code-block:: php // app/config/config.php - $configuration->loadFromExtension('doctrine', array( - 'dbal' => array( + $configuration->loadFromExtension('doctrine', [ + 'dbal' => [ 'charset' => 'utf8mb4', - 'default_table_options' => array( + 'default_table_options' => [ 'charset' => 'utf8mb4', 'collate' => 'utf8mb4_unicode_ci', - ) - ), - )); + ] + ], + ]); We recommend against MySQL's ``utf8`` character set, since it does not support 4-byte unicode characters, and strings containing them will be @@ -248,13 +248,13 @@ can automatically generate an empty ``test_project`` database for you: .. code-block:: php // app/config/config.php - $container->loadFromExtension('doctrine', array( - 'dbal' => array( + $container->loadFromExtension('doctrine', [ + 'dbal' => [ 'driver' => 'pdo_sqlite', 'path' => '%kernel.project_dir%/app/sqlite.db', 'charset' => 'UTF-8', - ), - )); + ], + ]); Creating an Entity Class ~~~~~~~~~~~~~~~~~~~~~~~~ @@ -664,14 +664,15 @@ to easily fetch objects based on multiple conditions:: $repository = $this->getDoctrine()->getRepository(Product::class); // looks for a single product matching the given name and price - $product = $repository->findOneBy( - array('name' => 'Keyboard', 'price' => 19.99) - ); + $product = $repository->findOneBy([ + 'name' => 'Keyboard', + 'price' => 19.99 + ]); // looks for multiple products matching the given name, ordered by price $products = $repository->findBy( - array('name' => 'Keyboard'), - array('price' => 'ASC') + ['name' => 'Keyboard'], + ['price' => 'ASC'] ); .. tip:: diff --git a/doctrine/custom_dql_functions.rst b/doctrine/custom_dql_functions.rst index bc9687c065a..cfdee97f160 100644 --- a/doctrine/custom_dql_functions.rst +++ b/doctrine/custom_dql_functions.rst @@ -58,23 +58,23 @@ In Symfony, you can register your custom DQL functions as follows: use AppBundle\DQL\NumericFunction; use AppBundle\DQL\DatetimeFunction; - $container->loadFromExtension('doctrine', array( - 'orm' => array( + $container->loadFromExtension('doctrine', [ + 'orm' => [ // ... - 'dql' => array( - 'string_functions' => array( + 'dql' => [ + 'string_functions' => [ 'test_string' => StringFunction::class, 'second_string' => SecondStringFunction::class, - ), - 'numeric_functions' => array( + ], + 'numeric_functions' => [ 'test_numeric' => NumericFunction::class, - ), - 'datetime_functions' => array( + ], + 'datetime_functions' => [ 'test_datetime' => DatetimeFunction::class, - ), - ), - ), - )); + ], + ], + ], + ]); .. note:: @@ -130,22 +130,22 @@ In Symfony, you can register your custom DQL functions as follows: // app/config/config.php use AppBundle\DQL\DatetimeFunction; - $container->loadFromExtension('doctrine', array( - 'doctrine' => array( - 'orm' => array( + $container->loadFromExtension('doctrine', [ + 'doctrine' => [ + 'orm' => [ // ... - 'entity_managers' => array( - 'example_manager' => array( + 'entity_managers' => [ + 'example_manager' => [ // place your functions here - 'dql' => array( - 'datetime_functions' => array( + 'dql' => [ + 'datetime_functions' => [ 'test_datetime' => DatetimeFunction::class, - ), - ), - ), - ), - ), - ), - )); + ], + ], + ], + ], + ], + ], + ]); .. _`DQL User Defined Functions`: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/cookbook/dql-user-defined-functions.html diff --git a/doctrine/dbal.rst b/doctrine/dbal.rst index cb27a1b8a70..abd13cd22f2 100644 --- a/doctrine/dbal.rst +++ b/doctrine/dbal.rst @@ -66,16 +66,16 @@ To get started, configure the database connection parameters: .. code-block:: php // app/config/config.php - $container->loadFromExtension('doctrine', array( - 'dbal' => array( + $container->loadFromExtension('doctrine', [ + 'dbal' => [ 'driver' => 'pdo_mysql', 'dbname' => 'Symfony', 'user' => 'root', 'password' => null, 'charset' => 'UTF8', 'server_version' => '5.6', - ), - )); + ], + ]); For full DBAL configuration options, or to learn how to configure multiple connections, see :ref:`reference-dbal-configuration`. @@ -138,14 +138,14 @@ mapping types, read Doctrine's `Custom Mapping Types`_ section of their document use AppBundle\Type\CustomFirst; use AppBundle\Type\CustomSecond; - $container->loadFromExtension('doctrine', array( - 'dbal' => array( - 'types' => array( + $container->loadFromExtension('doctrine', [ + 'dbal' => [ + 'types' => [ 'custom_first' => CustomFirst::class, 'custom_second' => CustomSecond::class, - ), - ), - )); + ], + ], + ]); Registering custom Mapping Types in the SchemaTool -------------------------------------------------- @@ -188,13 +188,13 @@ mapping type: .. code-block:: php // app/config/config.php - $container->loadFromExtension('doctrine', array( - 'dbal' => array( - 'mapping_types' => array( + $container->loadFromExtension('doctrine', [ + 'dbal' => [ + 'mapping_types' => [ 'enum' => 'string', - ), - ), - )); + ], + ], + ]); .. _`PDO`: https://php.net/pdo .. _`Doctrine`: http://www.doctrine-project.org diff --git a/doctrine/event_listeners_subscribers.rst b/doctrine/event_listeners_subscribers.rst index 1faa304180c..605af48a87b 100644 --- a/doctrine/event_listeners_subscribers.rst +++ b/doctrine/event_listeners_subscribers.rst @@ -73,16 +73,16 @@ managers that use this connection. use AppBundle\EventListener\SearchIndexerSubscriber; $container->autowire(SearchIndexer::class) - ->addTag('doctrine.event_listener', array('event' => 'postPersist')) + ->addTag('doctrine.event_listener', ['event' => 'postPersist']) ; $container->autowire(SearchIndexer2::class) - ->addTag('doctrine.event_listener', array( + ->addTag('doctrine.event_listener', [ 'event' => 'postPersist', 'connection' => 'default', - )) + ]) ; $container->autowire(SearchIndexerSubscriber::class) - ->addTag('doctrine.event_subscriber', array('connection' => 'default')) + ->addTag('doctrine.event_subscriber', ['connection' => 'default']) ; Creating the Listener Class @@ -150,10 +150,10 @@ interface and have an event method for each event it subscribes to:: { public function getSubscribedEvents() { - return array( + return [ Events::postPersist, Events::postUpdate, - ); + ]; } public function postUpdate(LifecycleEventArgs $args) @@ -233,7 +233,7 @@ to the tag like so: $container ->register('my.listener', SearchIndexer::class) - ->addTag('doctrine.event_listener', array('event' => 'postPersist', 'lazy' => 'true')) + ->addTag('doctrine.event_listener', ['event' => 'postPersist', 'lazy' => 'true']) ; .. note:: @@ -290,10 +290,10 @@ numbers mean that listeners are invoked earlier. $container ->register('my.listener.with_high_priority', MyHighPriorityListener::class) - ->addTag('doctrine.event_listener', array('event' => 'postPersist', 'priority' => 10)) + ->addTag('doctrine.event_listener', ['event' => 'postPersist', 'priority' => 10]) ; $container ->register('my.listener.with_low_priority', MyLowPriorityListener::class) - ->addTag('doctrine.event_listener', array('event' => 'postPersist', 'priority' => 1)) + ->addTag('doctrine.event_listener', ['event' => 'postPersist', 'priority' => 1]) ; diff --git a/doctrine/mapping_model_classes.rst b/doctrine/mapping_model_classes.rst index 340a3005cd0..d3f2f6f46dd 100644 --- a/doctrine/mapping_model_classes.rst +++ b/doctrine/mapping_model_classes.rst @@ -34,17 +34,17 @@ be adapted for your case:: // ... $modelDirectory = realpath(__DIR__.'/Resources/config/doctrine/model'); - $mappings = array( + $mappings = [ $modelDirectory => Model::class, - ); + ]; if (class_exists(DoctrineOrmMappingsPass::class)) { $container->addCompilerPass( DoctrineOrmMappingsPass::createXmlMappingDriver( $mappings, - array('cmf_routing.model_manager_name'), + ['cmf_routing.model_manager_name'], 'cmf_routing.backend_type_orm', - array('CmfRoutingBundle' => Model::class) + ['CmfRoutingBundle' => Model::class] )); } @@ -52,9 +52,9 @@ be adapted for your case:: $container->addCompilerPass( DoctrineMongoDBMappingsPass::createXmlMappingDriver( $mappings, - array('cmf_routing.model_manager_name'), + ['cmf_routing.model_manager_name'], 'cmf_routing.backend_type_mongodb', - array('CmfRoutingBundle' => Model::class) + ['CmfRoutingBundle' => Model::class] )); } @@ -62,9 +62,9 @@ be adapted for your case:: $container->addCompilerPass( DoctrineCouchDBMappingsPass::createXmlMappingDriver( $mappings, - array('cmf_routing.model_manager_name'), + ['cmf_routing.model_manager_name'], 'cmf_routing.backend_type_couchdb', - array('CmfRoutingBundle' => Model::class) + ['CmfRoutingBundle' => Model::class] )); } @@ -72,9 +72,9 @@ be adapted for your case:: $container->addCompilerPass( DoctrinePhpcrMappingsPass::createXmlMappingDriver( $mappings, - array('cmf_routing.model_manager_name'), + ['cmf_routing.model_manager_name'], 'cmf_routing.backend_type_phpcr', - array('CmfRoutingBundle' => Model::class) + ['CmfRoutingBundle' => Model::class] )); } } @@ -122,16 +122,16 @@ Annotations, XML, Yaml, PHP and StaticPHP. The arguments are: // ... private function buildMappingCompilerPass() { - $fileLocator = new Definition(DefaultFileLocator::class, array( - array(realpath(__DIR__ . '/Resources/config/doctrine-base')), + $fileLocator = new Definition(DefaultFileLocator::class, [ + [realpath(__DIR__ . '/Resources/config/doctrine-base')], '.orm.xml' - )); - $driver = new Definition(XmlDriver::class, array($fileLocator)); + ]); + $driver = new Definition(XmlDriver::class, [$fileLocator]); return new DoctrineOrmMappingsPass( $driver, - array(Model::class), - array('your_bundle.manager_name'), + [Model::class], + ['your_bundle.manager_name'], 'your_bundle.orm_enabled' ); } diff --git a/doctrine/mongodb_session_storage.rst b/doctrine/mongodb_session_storage.rst index fcfecfe3dd2..28a2fd6bb4c 100644 --- a/doctrine/mongodb_session_storage.rst +++ b/doctrine/mongodb_session_storage.rst @@ -79,28 +79,28 @@ need to change/add some parameters in the main configuration file: use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\HttpFoundation\Session\Storage\Handler\MongoDbSessionHandler; - $container->loadFromExtension('framework', array( - 'session' => array( + $container->loadFromExtension('framework', [ + 'session' => [ // ... 'handler_id' => 'session.handler.mongo', 'cookie_lifetime' => 2592000, // optional, it is set to 30 days here 'gc_maxlifetime' => 2592000, // optional, it is set to 30 days here - ), - )); + ], + ]); $container->register('mongo_client', \MongoClient::class) - ->setArguments(array( + ->setArguments([ // if using a username and password - array('mongodb://%mongodb_username%:%mongodb_password%@%mongodb_host%:27017'), + ['mongodb://%mongodb_username%:%mongodb_password%@%mongodb_host%:27017'], // if not using a username and password - array('mongodb://%mongodb_host%:27017'), - )); + ['mongodb://%mongodb_host%:27017'], + ]); $container->register('session.handler.mongo', MongoDbSessionHandler::class) - ->setArguments(array( + ->setArguments([ new Reference('mongo_client'), '%mongo.session.options%', - )); + ]); The parameters used above should be defined somewhere in your application, often in your main parameters configuration: @@ -148,10 +148,10 @@ parameters configuration: use Symfony\Component\DependencyInjection\Reference; - $container->setParameter('mongo.session.options', array( + $container->setParameter('mongo.session.options', [ 'database' => 'session_db', // your MongoDB database name 'collection' => 'session', // your MongoDB collection name - )); + ]); $container->setParameter('mongodb_host', '1.2.3.4'); // your MongoDB server's IP $container->setParameter('mongodb_username', 'my_username'); $container->setParameter('mongodb_password', 'my_password'); diff --git a/doctrine/multiple_entity_managers.rst b/doctrine/multiple_entity_managers.rst index 8f43b493660..948ca8b9092 100644 --- a/doctrine/multiple_entity_managers.rst +++ b/doctrine/multiple_entity_managers.rst @@ -111,11 +111,11 @@ The following configuration code shows how you can configure two entity managers .. code-block:: php - $container->loadFromExtension('doctrine', array( - 'dbal' => array( + $container->loadFromExtension('doctrine', [ + 'dbal' => [ 'default_connection' => 'default', - 'connections' => array( - 'default' => array( + 'connections' => [ + 'default' => [ 'driver' => 'pdo_mysql', 'host' => '%database_host%', 'port' => '%database_port%', @@ -123,8 +123,8 @@ The following configuration code shows how you can configure two entity managers 'user' => '%database_user%', 'password' => '%database_password%', 'charset' => 'UTF8', - ), - 'customer' => array( + ], + 'customer' => [ 'driver' => 'pdo_mysql', 'host' => '%database_host2%', 'port' => '%database_port2%', @@ -132,29 +132,29 @@ The following configuration code shows how you can configure two entity managers 'user' => '%database_user2%', 'password' => '%database_password2%', 'charset' => 'UTF8', - ), - ), - ), + ], + ], + ], - 'orm' => array( + 'orm' => [ 'default_entity_manager' => 'default', - 'entity_managers' => array( - 'default' => array( + 'entity_managers' => [ + 'default' => [ 'connection' => 'default', - 'mappings' => array( + 'mappings' => [ 'AppBundle' => null, 'AcmeStoreBundle' => null, - ), - ), - 'customer' => array( + ], + ], + 'customer' => [ 'connection' => 'customer', - 'mappings' => array( + 'mappings' => [ 'AcmeCustomerBundle' => null, - ), - ), - ), - ), - )); + ], + ], + ], + ], + ]); In this case, you've defined two entity managers and called them ``default`` and ``customer``. The ``default`` entity manager manages entities in the diff --git a/doctrine/pdo_session_storage.rst b/doctrine/pdo_session_storage.rst index ccc5a494a8d..f47a6fea080 100644 --- a/doctrine/pdo_session_storage.rst +++ b/doctrine/pdo_session_storage.rst @@ -55,10 +55,10 @@ To use it, first register a new handler service: use Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler; $storageDefinition = $container->register(PdoSessionHandler::class) - ->setArguments(array( + ->setArguments([ 'mysql:dbname=mydatabase; host=myhost; port=myport', - array('db_username' => 'myuser', 'db_password' => 'mypassword'), - )) + ['db_username' => 'myuser', 'db_password' => 'mypassword'], + ]) ; .. tip:: @@ -93,13 +93,13 @@ Next, tell Symfony to use your service as the session handler: use Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler; // ... - $container->loadFromExtension('framework', array( + $container->loadFromExtension('framework', [ // ... - 'session' => array( + 'session' => [ // ... 'handler_id' => PdoSessionHandler::class, - ), - )); + ], + ]); Configuring the Table and Column Names -------------------------------------- @@ -151,10 +151,10 @@ a second array argument to ``PdoSessionHandler``: // ... $container->register(PdoSessionHandler::class) - ->setArguments(array( + ->setArguments([ 'mysql:dbname=mydatabase; host=myhost; port=myport', - array('db_table' => 'sessions', 'db_username' => 'myuser', 'db_password' => 'mypassword') - )) + ['db_table' => 'sessions', 'db_username' => 'myuser', 'db_password' => 'mypassword'] + ]) ; These are parameters that you can configure: @@ -221,10 +221,10 @@ of your project's data, you can use the connection settings from the // ... $container->register(PdoSessionHandler::class) - ->setArguments(array( + ->setArguments([ 'mysql:host=%database_host%;port=%database_port%;dbname=%database_name%', - array('db_username' => '%database_user%', 'db_password' => '%database_password%') - )) + ['db_username' => '%database_user%', 'db_password' => '%database_password%'] + ]) ; .. _example-sql-statements: diff --git a/doctrine/registration_form.rst b/doctrine/registration_form.rst index 9a3d8a176f8..5f71882c629 100644 --- a/doctrine/registration_form.rst +++ b/doctrine/registration_form.rst @@ -95,7 +95,7 @@ With some validation added, your class may look something like this:: public function __construct() { - $this->roles = array('ROLE_USER'); + $this->roles = ['ROLE_USER']; } // other properties and methods @@ -203,19 +203,19 @@ Next, create the form for the ``User`` entity:: $builder ->add('email', EmailType::class) ->add('username', TextType::class) - ->add('plainPassword', RepeatedType::class, array( + ->add('plainPassword', RepeatedType::class, [ 'type' => PasswordType::class, - 'first_options' => array('label' => 'Password'), - 'second_options' => array('label' => 'Repeat Password'), - )) + 'first_options' => ['label' => 'Password'], + 'second_options' => ['label' => 'Repeat Password'], + ]) ; } public function configureOptions(OptionsResolver $resolver) { - $resolver->setDefaults(array( + $resolver->setDefaults([ 'data_class' => User::class, - )); + ]); } } @@ -276,7 +276,7 @@ into the database:: return $this->render( 'registration/register.html.twig', - array('form' => $form->createView()) + ['form' => $form->createView()] ); } } @@ -312,11 +312,11 @@ encoder in the security configuration: // app/config/security.php use AppBundle\Entity\User; - $container->loadFromExtension('security', array( - 'encoders' => array( + $container->loadFromExtension('security', [ + 'encoders' => [ User::class => 'bcrypt', - ), - )); + ], + ]); In this case the recommended `bcrypt`_ algorithm is used. If needed, check out the :ref:`user password encoding ` article. @@ -355,9 +355,9 @@ the :ref:`user password encoding ` article. use Symfony\Component\Routing\Route; $routes = new RouteCollection(); - $routes->add('user_registration', new Route('/register', array( + $routes->add('user_registration', new Route('/register', [ '_controller' => 'AppBundle:Registration:register', - ))); + ])); return $routes; @@ -442,10 +442,10 @@ To do this, add a ``termsAccepted`` field to your form, but set its $builder ->add('email', EmailType::class); // ... - ->add('termsAccepted', CheckboxType::class, array( + ->add('termsAccepted', CheckboxType::class, [ 'mapped' => false, 'constraints' => new IsTrue(), - )) + ]) ); } } diff --git a/doctrine/resolve_target_entity.rst b/doctrine/resolve_target_entity.rst index 9c5901b354d..9dfa88387a8 100644 --- a/doctrine/resolve_target_entity.rst +++ b/doctrine/resolve_target_entity.rst @@ -146,14 +146,14 @@ about the replacement: use Acme\InvoiceBundle\Model\InvoiceSubjectInterface; use AppBundle\Entity\Customer; - $container->loadFromExtension('doctrine', array( - 'orm' => array( + $container->loadFromExtension('doctrine', [ + 'orm' => [ // ... - 'resolve_target_entities' => array( + 'resolve_target_entities' => [ InvoiceSubjectInterface::class => Customer::class, - ), - ), - )); + ], + ], + ]); Final Thoughts -------------- diff --git a/email.rst b/email.rst index 1ed48f76fd7..ed26b35fec6 100644 --- a/email.rst +++ b/email.rst @@ -60,12 +60,12 @@ already included: .. code-block:: php // app/config/config.php - $container->loadFromExtension('swiftmailer', array( + $container->loadFromExtension('swiftmailer', [ 'transport' => "%mailer_transport%", 'host' => "%mailer_host%", 'username' => "%mailer_user%", 'password' => "%mailer_password%", - )); + ]); These values (e.g. ``%mailer_transport%``), are reading from the parameters that are set in the :ref:`parameters.yml ` file. You @@ -110,7 +110,7 @@ an email is pretty straightforward:: $this->renderView( // app/Resources/views/Emails/registration.html.twig 'Emails/registration.html.twig', - array('name' => $name) + ['name' => $name] ), 'text/html' ) @@ -119,7 +119,7 @@ an email is pretty straightforward:: ->addPart( $this->renderView( 'Emails/registration.txt.twig', - array('name' => $name) + ['name' => $name] ), 'text/plain' ) diff --git a/email/cloud.rst b/email/cloud.rst index d7ddbd33f3b..07a998b7a8f 100644 --- a/email/cloud.rst +++ b/email/cloud.rst @@ -65,14 +65,14 @@ and complete the configuration with the provided ``username`` and ``password``: .. code-block:: php // app/config/config.php - $container->loadFromExtension('swiftmailer', array( + $container->loadFromExtension('swiftmailer', [ 'transport' => 'smtp', 'host' => 'email-smtp.us-east-1.amazonaws.com', 'port' => 587, 'encryption' => 'tls', 'username' => 'AWS_SES_SMTP_USERNAME', 'password' => 'AWS_SES_SMTP_PASSWORD', - )); + ]); The ``port`` and ``encryption`` keys are not present in the Symfony Standard Edition configuration by default, but you can simply add them as needed. diff --git a/email/dev_environment.rst b/email/dev_environment.rst index 81c23901a73..127e22867aa 100644 --- a/email/dev_environment.rst +++ b/email/dev_environment.rst @@ -47,9 +47,9 @@ will not be sent when you run tests, but will continue to be sent in the .. code-block:: php // app/config/config_test.php - $container->loadFromExtension('swiftmailer', array( + $container->loadFromExtension('swiftmailer', [ 'disable_delivery' => "true", - )); + ]); If you'd also like to disable deliver in the ``dev`` environment, simply add this same configuration to the ``config_dev.yml`` file. @@ -91,9 +91,9 @@ via the ``delivery_addresses`` option: .. code-block:: php // app/config/config_dev.php - $container->loadFromExtension('swiftmailer', array( - 'delivery_addresses' => array("dev@example.com"), - )); + $container->loadFromExtension('swiftmailer', [ + 'delivery_addresses' => ["dev@example.com"], + ]); Now, suppose you're sending an email to ``recipient@example.com``:: @@ -105,7 +105,7 @@ Now, suppose you're sending an email to ``recipient@example.com``:: ->setBody( $this->renderView( 'HelloBundle:Hello:email.txt.twig', - array('name' => $name) + ['name' => $name] ) ) ; @@ -174,15 +174,15 @@ by adding the ``delivery_whitelist`` option: .. code-block:: php // app/config/config_dev.php - $container->loadFromExtension('swiftmailer', array( - 'delivery_addresses' => array("dev@example.com"), - 'delivery_whitelist' => array( + $container->loadFromExtension('swiftmailer', [ + 'delivery_addresses' => ["dev@example.com"], + 'delivery_whitelist' => [ // all email addresses matching these regexes will be delivered // like normal, as well as being sent to dev@example.com '/@specialdomain\.com$/', '/^admin@mydomain\.com$/', - ), - )); + ], + ]); In the above example all email messages will be redirected to ``dev@example.com`` and messages sent to the ``admin@mydomain.com`` address or to any email address @@ -236,9 +236,9 @@ you to open the report with details of the sent emails. .. code-block:: php // app/config/config_dev.php - $container->loadFromExtension('web_profiler', array( + $container->loadFromExtension('web_profiler', [ 'intercept_redirects' => 'true', - )); + ]); .. tip:: diff --git a/email/gmail.rst b/email/gmail.rst index e34604bae0a..c8b3362753b 100644 --- a/email/gmail.rst +++ b/email/gmail.rst @@ -44,11 +44,11 @@ In the development configuration file, change the ``transport`` setting to .. code-block:: php // app/config/config_dev.php - $container->loadFromExtension('swiftmailer', array( + $container->loadFromExtension('swiftmailer', [ 'transport' => 'gmail', 'username' => 'your_gmail_username', 'password' => 'your_gmail_password', - )); + ]); .. tip:: @@ -96,11 +96,11 @@ In the development configuration file, change the ``transport`` setting to .. code-block:: php // app/config/config_dev.php - $container->loadFromExtension('swiftmailer', array( + $container->loadFromExtension('swiftmailer', [ 'transport' => 'gmail', 'username' => '%mailer_user%', 'password' => '%mailer_password%', - )); + ]); Redefining the Default Configuration Parameters ----------------------------------------------- diff --git a/email/spool.rst b/email/spool.rst index b4115c86767..006cea056a3 100644 --- a/email/spool.rst +++ b/email/spool.rst @@ -50,10 +50,10 @@ swiftmailer with the memory option, use the following configuration: .. code-block:: php // app/config/config.php - $container->loadFromExtension('swiftmailer', array( + $container->loadFromExtension('swiftmailer', [ // ... - 'spool' => array('type' => 'memory'), - )); + 'spool' => ['type' => 'memory'], + ]); .. _spool-using-a-file: @@ -100,14 +100,14 @@ In order to use the spool with files, use the following configuration: .. code-block:: php // app/config/config.php - $container->loadFromExtension('swiftmailer', array( + $container->loadFromExtension('swiftmailer', [ // ... - 'spool' => array( + 'spool' => [ 'type' => 'file', 'path' => '/path/to/spooldir', - ), - )); + ], + ]); .. tip:: diff --git a/event_dispatcher.rst b/event_dispatcher.rst index af7a8f8c26f..edd79f985d7 100644 --- a/event_dispatcher.rst +++ b/event_dispatcher.rst @@ -104,7 +104,7 @@ using a special "tag": $container ->autowire(ExceptionListener::class) - ->addTag('kernel.event_listener', array('event' => 'kernel.exception')) + ->addTag('kernel.event_listener', ['event' => 'kernel.exception']) ; .. note:: @@ -151,13 +151,13 @@ listen to the same ``kernel.exception`` event:: public static function getSubscribedEvents() { // return the subscribed events, their methods and priorities - return array( - KernelEvents::EXCEPTION => array( - array('processException', 10), - array('logException', 0), - array('notifyException', -10), - ) - ); + return [ + KernelEvents::EXCEPTION => [ + ['processException', 10], + ['logException', 0], + ['notifyException', -10], + ] + ]; } public function processException(GetResponseForExceptionEvent $event) diff --git a/event_dispatcher/before_after_filters.rst b/event_dispatcher/before_after_filters.rst index 6e38cfe4846..afd5a6af014 100644 --- a/event_dispatcher/before_after_filters.rst +++ b/event_dispatcher/before_after_filters.rst @@ -66,10 +66,10 @@ parameters key: .. code-block:: php // app/config/config.php - $container->setParameter('tokens', array( + $container->setParameter('tokens', [ 'client1' => 'pass1', 'client2' => 'pass2', - )); + ]); Tag Controllers to Be Checked ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -152,9 +152,9 @@ event listeners, you can learn more about them at :doc:`/event_dispatcher`:: public static function getSubscribedEvents() { - return array( + return [ KernelEvents::CONTROLLER => 'onKernelController', - ); + ]; } } @@ -227,10 +227,10 @@ header on the response if it's found:: public static function getSubscribedEvents() { - return array( + return [ KernelEvents::CONTROLLER => 'onKernelController', KernelEvents::RESPONSE => 'onKernelResponse', - ); + ]; } That's it! The ``TokenSubscriber`` is now notified before every controller is diff --git a/event_dispatcher/method_behavior.rst b/event_dispatcher/method_behavior.rst index ffd58b25d9c..2b179039c29 100644 --- a/event_dispatcher/method_behavior.rst +++ b/event_dispatcher/method_behavior.rst @@ -129,9 +129,9 @@ could listen to the ``mailer.post_send`` event and change the method's return va public static function getSubscribedEvents() { - return array( + return [ 'mailer.post_send' => 'onMailerPostSend' - ); + ]; } } diff --git a/form/action_method.rst b/form/action_method.rst index 40a236292b0..dbb47685341 100644 --- a/form/action_method.rst +++ b/form/action_method.rst @@ -89,10 +89,10 @@ options: { // ... - $form = $this->createForm(TaskType::class, $task, array( + $form = $this->createForm(TaskType::class, $task, [ 'action' => $this->generateUrl('target_route'), 'method' => 'GET', - )); + ]); // ... } @@ -109,10 +109,10 @@ options: $formFactory = $formFactoryBuilder->getFormFactory(); - $form = $formFactory->create(TaskType::class, $task, array( + $form = $formFactory->create(TaskType::class, $task, [ 'action' => '...', 'method' => 'GET', - )); + ]); Finally, you can override the action and method in the template by passing them to the ``form()`` or the ``form_start()`` helper functions: diff --git a/form/bootstrap4.rst b/form/bootstrap4.rst index 386015744d0..56a6bd5753e 100644 --- a/form/bootstrap4.rst +++ b/form/bootstrap4.rst @@ -55,13 +55,13 @@ configuration: .. code-block:: php // config/packages/twig.php - $container->loadFromExtension('twig', array( - 'form_themes' => array( + $container->loadFromExtension('twig', [ + 'form_themes' => [ 'bootstrap_4_layout.html.twig', - ), + ], // ... - )); + ]); If you prefer to apply the Bootstrap styles on a form to form basis, include the ``form_theme`` tag in the templates where those forms are used: diff --git a/form/button_based_validation.rst b/form/button_based_validation.rst index 925d1dcdd40..613e6f325f6 100644 --- a/form/button_based_validation.rst +++ b/form/button_based_validation.rst @@ -24,9 +24,9 @@ so we set its ``validation_groups`` option to false:: $form = $this->createFormBuilder($task) // ... - ->add('previousStep', SubmitType::class, array( + ->add('previousStep', SubmitType::class, [ 'validation_groups' => false, - )) + ]) ->getForm(); Now the form will skip your validation constraints. It will still validate diff --git a/form/create_custom_field_type.rst b/form/create_custom_field_type.rst index 37b7bfc8461..ace88c6d166 100644 --- a/form/create_custom_field_type.rst +++ b/form/create_custom_field_type.rst @@ -30,14 +30,14 @@ for form fields, which is ``\Form\Type``. Make sure the field extend { public function configureOptions(OptionsResolver $resolver) { - $resolver->setDefaults(array( - 'choices' => array( + $resolver->setDefaults([ + 'choices' => [ 'Standard Shipping' => 'standard', 'Expedited Shipping' => 'expedited', 'Priority Shipping' => 'priority', - ), + ], 'choices_as_values' => true, - )); + ]); } public function getParent() @@ -183,11 +183,11 @@ link for details), create a ``shipping_widget`` block to handle this: .. code-block:: php // app/config/config.php - $container->loadFromExtension('twig', array( - 'form_themes' => array( + $container->loadFromExtension('twig', [ + 'form_themes' => [ 'form/fields.html.twig', - ), - )); + ], + ]); For the PHP templating engine, your configuration should look like this: @@ -224,15 +224,15 @@ link for details), create a ``shipping_widget`` block to handle this: .. code-block:: php // app/config/config.php - $container->loadFromExtension('framework', array( - 'templating' => array( - 'form' => array( - 'resources' => array( + $container->loadFromExtension('framework', [ + 'templating' => [ + 'form' => [ + 'resources' => [ ':form:fields.html.php', - ), - ), - ), - )); + ], + ], + ], + ]); Using the Field Type -------------------- @@ -251,9 +251,9 @@ new instance of the type in one of your forms:: { public function buildForm(FormBuilderInterface $builder, array $options) { - $builder->add('shipping_code', ShippingType::class, array( + $builder->add('shipping_code', ShippingType::class, [ 'placeholder' => 'Choose a delivery option', - )); + ]); } } diff --git a/form/create_form_type_extension.rst b/form/create_form_type_extension.rst index f90dfff1a4f..d11dfeb173d 100644 --- a/form/create_form_type_extension.rst +++ b/form/create_form_type_extension.rst @@ -99,9 +99,9 @@ your class as a service and using the ``form.type_extension`` tag: use Symfony\Component\Form\Extension\Core\Type\FileType; $container->autowire(ImageTypeExtension::class) - ->addTag('form.type_extension', array( + ->addTag('form.type_extension', [ 'extended_type' => FileType::class - )) + ]) ; The ``extended_type`` key of the tag must match the class you're returning from @@ -189,7 +189,7 @@ For example:: public function configureOptions(OptionsResolver $resolver) { // makes it legal for FileType fields to have an image_property option - $resolver->setDefined(array('image_property')); + $resolver->setDefined(['image_property']); } public function buildView(FormView $view, FormInterface $form, array $options) @@ -262,7 +262,7 @@ next to the file field. For example:: { $builder ->add('name', TextType::class) - ->add('file', FileType::class, array('image_property' => 'webPath')); + ->add('file', FileType::class, ['image_property' => 'webPath']); } } diff --git a/form/csrf_protection.rst b/form/csrf_protection.rst index 266555579c0..b46de4e67e9 100644 --- a/form/csrf_protection.rst +++ b/form/csrf_protection.rst @@ -40,13 +40,13 @@ The CSRF token can be customized on a form-by-form basis. For example:: public function configureOptions(OptionsResolver $resolver) { - $resolver->setDefaults(array( + $resolver->setDefaults([ 'data_class' => Task::class, 'csrf_protection' => true, 'csrf_field_name' => '_token', // a unique key to help generate the secret token 'csrf_token_id' => 'task_item', - )); + ]); } // ... diff --git a/form/data_based_validation.rst b/form/data_based_validation.rst index 3e31be7cd67..de8e297f680 100644 --- a/form/data_based_validation.rst +++ b/form/data_based_validation.rst @@ -14,12 +14,12 @@ to an array callback:: // ... public function configureOptions(OptionsResolver $resolver) { - $resolver->setDefaults(array( - 'validation_groups' => array( + $resolver->setDefaults([ + 'validation_groups' => [ Client::class, 'determineValidationGroups', - ), - )); + ], + ]); } This will call the static method ``determineValidationGroups()`` on the @@ -34,17 +34,17 @@ You can also define whole logic inline by using a ``Closure``:: // ... public function configureOptions(OptionsResolver $resolver) { - $resolver->setDefaults(array( + $resolver->setDefaults([ 'validation_groups' => function (FormInterface $form) { $data = $form->getData(); if (Client::TYPE_PERSON == $data->getType()) { - return array('person'); + return ['person']; } - return array('company'); + return ['company']; }, - )); + ]); } Using the ``validation_groups`` option overrides the default validation @@ -58,17 +58,17 @@ of the entity as well you have to adjust the option as follows:: // ... public function configureOptions(OptionsResolver $resolver) { - $resolver->setDefaults(array( + $resolver->setDefaults([ 'validation_groups' => function (FormInterface $form) { $data = $form->getData(); if (Client::TYPE_PERSON == $data->getType()) { - return array('Default', 'person'); + return ['Default', 'person']; } - return array('Default', 'company'); + return ['Default', 'company']; }, - )); + ]); } You can find more information about how the validation groups and the default constraints diff --git a/form/data_mappers.rst b/form/data_mappers.rst index 30dbb7375eb..23bb8939fa8 100644 --- a/form/data_mappers.rst +++ b/form/data_mappers.rst @@ -159,17 +159,17 @@ method to configure the data mapper:: public function buildForm(FormBuilderInterface $builder, array $options) { $builder - ->add('red', IntegerType::class, array( + ->add('red', IntegerType::class, [ // enforce the strictness of the type to ensure the constructor // of the Color class doesn't break 'empty_data' => '0', - )) - ->add('green', IntegerType::class, array( + ]) + ->add('green', IntegerType::class, [ 'empty_data' => '0', - )) - ->add('blue', IntegerType::class, array( + ]) + ->add('blue', IntegerType::class, [ 'empty_data' => '0', - )) + ]) ->setDataMapper(new ColorMapper()) ; } diff --git a/form/data_transformers.rst b/form/data_transformers.rst index 85a00d8803f..d330fa2719c 100644 --- a/form/data_transformers.rst +++ b/form/data_transformers.rst @@ -47,9 +47,9 @@ Suppose you have a Task form with a tags ``text`` type:: public function configureOptions(OptionsResolver $resolver) { - $resolver->setDefaults(array( + $resolver->setDefaults([ 'data_class' => Task::class, - )); + ]); } // ... @@ -146,9 +146,9 @@ Start by setting up the text field like normal:: public function configureOptions(OptionsResolver $resolver) { - $resolver->setDefaults(array( + $resolver->setDefaults([ 'data_class' => Task::class, - )); + ]); } // ... @@ -277,10 +277,10 @@ and type-hint the new class:: { $builder ->add('description', TextareaType::class) - ->add('issue', TextType::class, array( + ->add('issue', TextType::class, [ // validation message if the data transformer fails 'invalid_message' => 'That is not a valid issue number', - )); + ]); // ... @@ -363,9 +363,9 @@ First, create the custom field type class:: public function configureOptions(OptionsResolver $resolver) { - $resolver->setDefaults(array( + $resolver->setDefaults([ 'invalid_message' => 'The selected issue does not exist', - )); + ]); } public function getParent() diff --git a/form/direct_submit.rst b/form/direct_submit.rst index 855043affc5..d53d6195f71 100644 --- a/form/direct_submit.rst +++ b/form/direct_submit.rst @@ -24,9 +24,9 @@ submissions:: return $this->redirectToRoute('task_success'); } - return $this->render('product/new.html.twig', array( + return $this->render('product/new.html.twig', [ 'form' => $form->createView(), - )); + ]); } .. tip:: @@ -63,9 +63,9 @@ method, pass the submitted data directly to } } - return $this->render('product/new.html.twig', array( + return $this->render('product/new.html.twig', [ 'form' => $form->createView(), - )); + ]); } .. tip:: diff --git a/form/disabling_validation.rst b/form/disabling_validation.rst index cf02e417ef0..f23cc73dbbf 100644 --- a/form/disabling_validation.rst +++ b/form/disabling_validation.rst @@ -11,9 +11,9 @@ these cases you can set the ``validation_groups`` option to ``false``:: public function configureOptions(OptionsResolver $resolver) { - $resolver->setDefaults(array( + $resolver->setDefaults([ 'validation_groups' => false, - )); + ]); } Note that when you do that, the form will still run basic integrity checks, diff --git a/form/dynamic_form_modification.rst b/form/dynamic_form_modification.rst index 025bc472df4..eef66d03de6 100644 --- a/form/dynamic_form_modification.rst +++ b/form/dynamic_form_modification.rst @@ -53,9 +53,9 @@ a bare form class looks like:: public function configureOptions(OptionsResolver $resolver) { - $resolver->setDefaults(array( + $resolver->setDefaults([ 'data_class' => Product::class, - )); + ]); } } @@ -155,7 +155,7 @@ you can also move the logic for creating the ``name`` field to an { // Tells the dispatcher that you want to listen on the form.pre_set_data // event and that the preSetData method should be called. - return array(FormEvents::PRE_SET_DATA => 'preSetData'); + return [FormEvents::PRE_SET_DATA => 'preSetData']; } public function preSetData(FormEvent $event) @@ -294,14 +294,14 @@ security helper to fill in the listener logic:: $form = $event->getForm(); - $formOptions = array( + $formOptions = [ 'class' => User::class, 'choice_label' => 'fullName', 'query_builder' => function (UserRepository $userRepository) use ($user) { // call a method on your repository that returns the query builder // return $userRepository->createFriendsQueryBuilder($user); }, - ); + ]; // create the field, this is similar the $builder->add() // field name, field type, field options @@ -385,10 +385,10 @@ sport like this:: public function buildForm(FormBuilderInterface $builder, array $options) { $builder - ->add('sport', EntityType::class, array( + ->add('sport', EntityType::class, [ 'class' => 'AppBundle:Sport', 'placeholder' => '', - )) + ]) ; $builder->addEventListener( @@ -400,13 +400,13 @@ sport like this:: $data = $event->getData(); $sport = $data->getSport(); - $positions = null === $sport ? array() : $sport->getAvailablePositions(); + $positions = null === $sport ? [] : $sport->getAvailablePositions(); - $form->add('position', EntityType::class, array( + $form->add('position', EntityType::class, [ 'class' => 'AppBundle:Position', 'placeholder' => '', 'choices' => $positions, - )); + ]); } ); } @@ -449,20 +449,20 @@ The type would now look like:: public function buildForm(FormBuilderInterface $builder, array $options) { $builder - ->add('sport', EntityType::class, array( + ->add('sport', EntityType::class, [ 'class' => 'AppBundle:Sport', 'placeholder' => '', - )); + ]); ; $formModifier = function (FormInterface $form, Sport $sport = null) { - $positions = null === $sport ? array() : $sport->getAvailablePositions(); + $positions = null === $sport ? [] : $sport->getAvailablePositions(); - $form->add('position', EntityType::class, array( + $form->add('position', EntityType::class, [ 'class' => 'AppBundle:Position', 'placeholder' => '', 'choices' => $positions, - )); + ]); }; $builder->addEventListener( @@ -528,7 +528,7 @@ your application. Assume that you have a sport meetup creation controller:: return $this->render( 'meetup/create.html.twig', - array('form' => $form->createView()) + ['form' => $form->createView()] ); } diff --git a/form/embedded.rst b/form/embedded.rst index 0a1fc2b997b..a5b000727b3 100644 --- a/form/embedded.rst +++ b/form/embedded.rst @@ -83,9 +83,9 @@ create a form class so that a ``Category`` object can be modified by the user:: public function configureOptions(OptionsResolver $resolver) { - $resolver->setDefaults(array( + $resolver->setDefaults([ 'data_class' => Category::class, - )); + ]); } } diff --git a/form/events.rst b/form/events.rst index 3f1f9079c1f..380db9d1eca 100644 --- a/form/events.rst +++ b/form/events.rst @@ -318,7 +318,7 @@ callback for better readability:: ->add('show_email', CheckboxType::class) ->addEventListener( FormEvents::PRE_SET_DATA, - array($this, 'onPreSetData') + [$this, 'onPreSetData'] ) ; } @@ -352,10 +352,10 @@ Event subscribers have different uses: { public static function getSubscribedEvents() { - return array( + return [ FormEvents::PRE_SET_DATA => 'onPreSetData', FormEvents::PRE_SUBMIT => 'onPreSubmit', - ); + ]; } public function onPreSetData(FormEvent $event) diff --git a/form/form_collections.rst b/form/form_collections.rst index f8e0b13ca02..fa04ac38c8e 100644 --- a/form/form_collections.rst +++ b/form/form_collections.rst @@ -101,9 +101,9 @@ Then, create a form class so that a ``Tag`` object can be modified by the user:: public function configureOptions(OptionsResolver $resolver) { - $resolver->setDefaults(array( + $resolver->setDefaults([ 'data_class' => Tag::class, - )); + ]); } } @@ -129,17 +129,17 @@ Notice that you embed a collection of ``TagType`` forms using the { $builder->add('description'); - $builder->add('tags', CollectionType::class, array( + $builder->add('tags', CollectionType::class, [ 'entry_type' => TagType::class, - 'entry_options' => array('label' => false), - )); + 'entry_options' => ['label' => false], + ]); } public function configureOptions(OptionsResolver $resolver) { - $resolver->setDefaults(array( + $resolver->setDefaults([ 'data_class' => Task::class, - )); + ]); } } @@ -178,9 +178,9 @@ In your controller, you'll create a new form from the ``TaskType``:: // ... maybe do some form processing, like saving the Task and Tag objects } - return $this->render('task/new.html.twig', array( + return $this->render('task/new.html.twig', [ 'form' => $form->createView(), - )); + ]); } } @@ -263,11 +263,11 @@ add the ``allow_add`` option to your collection field:: { $builder->add('description'); - $builder->add('tags', CollectionType::class, array( + $builder->add('tags', CollectionType::class, [ 'entry_type' => TagType::class, - 'entry_options' => array('label' => false), + 'entry_options' => ['label' => false], 'allow_add' => true, - )); + ]); } In addition to telling the field to accept any number of submitted objects, the @@ -426,10 +426,10 @@ Next, add a ``by_reference`` option to the ``tags`` field and set it to ``false` { // ... - $builder->add('tags', CollectionType::class, array( + $builder->add('tags', CollectionType::class, [ // ... 'by_reference' => false, - )); + ]); } With these two changes, when the form is submitted, each new ``Tag`` object @@ -558,10 +558,10 @@ Start by adding the ``allow_delete`` option in the form Type:: { // ... - $builder->add('tags', CollectionType::class, array( + $builder->add('tags', CollectionType::class, [ // ... 'allow_delete' => true, - )); + ]); } Now, you need to put some code into the ``removeTag()`` method of ``Task``:: @@ -697,7 +697,7 @@ the relationship between the removed ``Tag`` and ``Task`` object. $entityManager->flush(); // redirect back to some edit page - return $this->redirectToRoute('task_edit', array('id' => $id)); + return $this->redirectToRoute('task_edit', ['id' => $id]); } // render some form template diff --git a/form/form_customization.rst b/form/form_customization.rst index cc60fdcdcdc..e5140506ce7 100644 --- a/form/form_customization.rst +++ b/form/form_customization.rst @@ -450,13 +450,13 @@ rendered. .. code-block:: php // app/config/config.php - $container->loadFromExtension('twig', array( - 'form_themes' => array( + $container->loadFromExtension('twig', [ + 'form_themes' => [ 'form/fields.html.twig', - ), + ], // ... - )); + ]); By default, Twig uses a *div* layout when rendering forms. Some people, however, may prefer to render forms in a *table* layout. Use the ``form_table_layout.html.twig`` @@ -493,13 +493,13 @@ resource to use such a layout: .. code-block:: php // app/config/config.php - $container->loadFromExtension('twig', array( - 'form_themes' => array( + $container->loadFromExtension('twig', [ + 'form_themes' => [ 'form_table_layout.html.twig', - ), + ], // ... - )); + ]); If you only want to make the change in one template, add the following line to your template file rather than adding the template as a resource: @@ -555,9 +555,9 @@ field whose *id* is ``product_name`` (and name is ``product[name]``). { // ... - $builder->add('name', TextType::class, array( + $builder->add('name', TextType::class, [ 'block_name' => 'custom_name', - )); + ]); } Then the block name will be ``_product_custom_name_widget``. diff --git a/form/form_dependencies.rst b/form/form_dependencies.rst index 977eef9d0c8..49a99c541bd 100644 --- a/form/form_dependencies.rst +++ b/form/form_dependencies.rst @@ -39,9 +39,9 @@ create your form:: $entityManager = $this->getDoctrine()->getManager(); $task = ...; - $form = $this->createForm(TaskType::class, $task, array( + $form = $this->createForm(TaskType::class, $task, [ 'entity_manager' => $entityManager, - )); + ]); // ... } diff --git a/form/form_themes.rst b/form/form_themes.rst index 0cda20b727f..3fb3b3e0303 100644 --- a/form/form_themes.rst +++ b/form/form_themes.rst @@ -204,13 +204,13 @@ file: .. code-block:: php // app/config/config.php - $container->loadFromExtension('twig', array( - 'form_themes' => array( + $container->loadFromExtension('twig', [ + 'form_themes' => [ '...', 'form/fields.html.twig', - ), + ], // ... - )); + ]); .. note:: @@ -297,16 +297,16 @@ file: .. code-block:: php // app/config/config.php - $container->loadFromExtension('framework', array( - 'templating' => array( - 'form' => array( - 'resources' => array( + $container->loadFromExtension('framework', [ + 'templating' => [ + 'form' => [ + 'resources' => [ 'form', - ), - ), - ), + ], + ], + ], // ... - )); + ]); Any fragments inside the ``app/Resources/views/form`` directory are now used globally to define form output. diff --git a/form/inherit_data_option.rst b/form/inherit_data_option.rst index 024bc52c00d..07f53826529 100644 --- a/form/inherit_data_option.rst +++ b/form/inherit_data_option.rst @@ -105,9 +105,9 @@ for that:: public function configureOptions(OptionsResolver $resolver) { - $resolver->setDefaults(array( + $resolver->setDefaults([ 'inherit_data' => true, - )); + ]); } } @@ -133,9 +133,9 @@ Finally, make this work by adding the location form to your two original forms:: { // ... - $builder->add('foo', LocationType::class, array( + $builder->add('foo', LocationType::class, [ 'data_class' => Company::class, - )); + ]); } .. code-block:: php @@ -148,9 +148,9 @@ Finally, make this work by adding the location form to your two original forms:: { // ... - $builder->add('bar', LocationType::class, array( + $builder->add('bar', LocationType::class, [ 'data_class' => Customer::class, - )); + ]); } That's it! You have extracted duplicated field definitions to a separate diff --git a/form/multiple_buttons.rst b/form/multiple_buttons.rst index 21ea8fcb579..1965e941f62 100644 --- a/form/multiple_buttons.rst +++ b/form/multiple_buttons.rst @@ -11,8 +11,8 @@ To do this, add a second button with the caption "Save and add" to your form:: $form = $this->createFormBuilder($task) ->add('task', TextType::class) ->add('dueDate', DateType::class) - ->add('save', SubmitType::class, array('label' => 'Create Task')) - ->add('saveAndAdd', SubmitType::class, array('label' => 'Save and Add')) + ->add('save', SubmitType::class, ['label' => 'Create Task']) + ->add('saveAndAdd', SubmitType::class, ['label' => 'Save and Add']) ->getForm(); In your controller, use the button's diff --git a/form/type_guesser.rst b/form/type_guesser.rst index bdfc2f0cfbf..489901b2bba 100644 --- a/form/type_guesser.rst +++ b/form/type_guesser.rst @@ -108,25 +108,25 @@ With this knowledge, you can easily implement the ``guessType()`` method of the case 'string': // there is a high confidence that the type is text when // @var string is used - return new TypeGuess(TextType::class, array(), Guess::HIGH_CONFIDENCE); + return new TypeGuess(TextType::class, [], Guess::HIGH_CONFIDENCE); case 'int': case 'integer': // integers can also be the id of an entity or a checkbox (0 or 1) - return new TypeGuess(IntegerType::class, array(), Guess::MEDIUM_CONFIDENCE); + return new TypeGuess(IntegerType::class, [], Guess::MEDIUM_CONFIDENCE); case 'float': case 'double': case 'real': - return new TypeGuess(NumberType::class, array(), Guess::MEDIUM_CONFIDENCE); + return new TypeGuess(NumberType::class, [], Guess::MEDIUM_CONFIDENCE); case 'boolean': case 'bool': - return new TypeGuess(CheckboxType::class, array(), Guess::HIGH_CONFIDENCE); + return new TypeGuess(CheckboxType::class, [], Guess::HIGH_CONFIDENCE); default: // there is a very low confidence that this one is correct - return new TypeGuess(TextType::class, array(), Guess::LOW_CONFIDENCE); + return new TypeGuess(TextType::class, [], Guess::LOW_CONFIDENCE); } } @@ -136,7 +136,7 @@ With this knowledge, you can easily implement the ``guessType()`` method of the $phpdoc = $reflectionProperty->getDocComment(); // parse the $phpdoc into an array like: - // array('var' => 'string', 'since' => '1.0') + // ['var' => 'string', 'since' => '1.0'] $phpdocTags = ...; return $phpdocTags; diff --git a/form/unit_testing.rst b/form/unit_testing.rst index 36c515c6932..fff9274ad42 100644 --- a/form/unit_testing.rst +++ b/form/unit_testing.rst @@ -42,10 +42,10 @@ The simplest ``TypeTestCase`` implementation looks like the following:: { public function testSubmitValidData() { - $formData = array( + $formData = [ 'test' => 'test', 'test2' => 'test2', - ); + ]; $objectToCompare = new TestObject(); // $objectToCompare will retrieve data from the form submission; pass it as the second argument @@ -150,10 +150,10 @@ make sure the ``FormRegistry`` uses the created instance:: // create a type instance with the mocked dependencies $type = new TestedType($this->objectManager); - return array( + return [ // register the type instances with the PreloadedExtension - new PreloadedExtension(array($type), array()), - ); + new PreloadedExtension([$type], []), + ]; } public function testSubmitValidData() @@ -205,9 +205,9 @@ allows you to return a list of extensions to register:: ->method('getMetadataFor') ->will($this->returnValue(new ClassMetadata(Form::class))); - return array( + return [ new ValidatorExtension($this->validator), - ); + ]; } // ... your tests diff --git a/form/use_empty_data.rst b/form/use_empty_data.rst index 8591d0ef865..284dd12c863 100644 --- a/form/use_empty_data.rst +++ b/form/use_empty_data.rst @@ -62,9 +62,9 @@ that constructor with no arguments:: public function configureOptions(OptionsResolver $resolver) { - $resolver->setDefaults(array( + $resolver->setDefaults([ 'empty_data' => new Blog($this->someDependency), - )); + ]); } } @@ -93,9 +93,9 @@ The closure must accept a ``FormInterface`` instance as the first argument:: public function configureOptions(OptionsResolver $resolver) { - $resolver->setDefaults(array( + $resolver->setDefaults([ 'empty_data' => function (FormInterface $form) { return new Blog($form->get('title')->getData()); }, - )); + ]); } diff --git a/form/validation_group_service_resolver.rst b/form/validation_group_service_resolver.rst index ec575067696..c77c92f66aa 100644 --- a/form/validation_group_service_resolver.rst +++ b/form/validation_group_service_resolver.rst @@ -29,7 +29,7 @@ parameter:: */ public function __invoke(FormInterface $form) { - $groups = array(); + $groups = []; // ... determine which groups to apply and return an array @@ -58,9 +58,9 @@ Then in your form, inject the resolver and set it as the ``validation_groups``:: // ... public function configureOptions(OptionsResolver $resolver) { - $resolver->setDefaults(array( + $resolver->setDefaults([ 'validation_groups' => $this->groupResolver, - )); + ]); } } diff --git a/form/validation_groups.rst b/form/validation_groups.rst index 6d8f75196ba..2b8d87e43e5 100644 --- a/form/validation_groups.rst +++ b/form/validation_groups.rst @@ -10,9 +10,9 @@ Validation Groups If your object takes advantage of :doc:`validation groups `, you'll need to specify which validation group(s) your form should use:: - $form = $this->createFormBuilder($user, array( - 'validation_groups' => array('registration'), - ))->add(...); + $form = $this->createFormBuilder($user, [ + 'validation_groups' => ['registration'], + ])->add(...); If you're creating :ref:`form classes ` (a good practice), then you'll need to add the following to the ``configureOptions()`` @@ -22,13 +22,13 @@ method:: public function configureOptions(OptionsResolver $resolver) { - $resolver->setDefaults(array( - 'validation_groups' => array('registration'), - )); + $resolver->setDefaults([ + 'validation_groups' => ['registration'], + ]); } In both of these cases, *only* the ``registration`` validation group will be used to validate the underlying object. To apply the ``registration`` group *and* all constraints that are not in a group, use:: - 'validation_groups' => array('Default', 'registration') + 'validation_groups' => ['Default', 'registration'] diff --git a/form/without_class.rst b/form/without_class.rst index e0a6959582e..5934d12ac58 100644 --- a/form/without_class.rst +++ b/form/without_class.rst @@ -17,7 +17,7 @@ an array of the submitted data. This is actually really easy:: public function contactAction(Request $request) { - $defaultData = array('message' => 'Type your message here'); + $defaultData = ['message' => 'Type your message here']; $form = $this->createFormBuilder($defaultData) ->add('name', TextType::class) ->add('email', EmailType::class) @@ -87,15 +87,15 @@ but here's a short example:: public function buildForm(FormBuilderInterface $builder, array $options) { $builder - ->add('firstName', TextType::class, array( - 'constraints' => new Length(array('min' => 3)), - )) - ->add('lastName', TextType::class, array( - 'constraints' => array( + ->add('firstName', TextType::class, [ + 'constraints' => new Length(['min' => 3]), + ]) + ->add('lastName', TextType::class, [ + 'constraints' => [ new NotBlank(), - new Length(array('min' => 3)), - ), - )) + new Length(['min' => 3]), + ], + ]) ; } @@ -107,7 +107,7 @@ but here's a short example:: .. code-block:: php - new NotBlank(array('groups' => array('create', 'update'))); + new NotBlank(['groups' => ['create', 'update']]); .. tip:: diff --git a/forms.rst b/forms.rst index 771462b60ea..0596254d57e 100644 --- a/forms.rst +++ b/forms.rst @@ -100,12 +100,12 @@ from inside a controller:: $form = $this->createFormBuilder($task) ->add('task', TextType::class) ->add('dueDate', DateType::class) - ->add('save', SubmitType::class, array('label' => 'Create Task')) + ->add('save', SubmitType::class, ['label' => 'Create Task']) ->getForm(); - return $this->render('default/new.html.twig', array( + return $this->render('default/new.html.twig', [ 'form' => $form->createView(), - )); + ]); } } @@ -224,7 +224,7 @@ your controller:: $form = $this->createFormBuilder($task) ->add('task', TextType::class) ->add('dueDate', DateType::class) - ->add('save', SubmitType::class, array('label' => 'Create Task')) + ->add('save', SubmitType::class, ['label' => 'Create Task']) ->getForm(); $form->handleRequest($request); @@ -243,9 +243,9 @@ your controller:: return $this->redirectToRoute('task_success'); } - return $this->render('default/new.html.twig', array( + return $this->render('default/new.html.twig', [ 'form' => $form->createView(), - )); + ]); } .. caution:: @@ -444,7 +444,7 @@ boxes. However, the :doc:`DateType ` can be configured to be rendered as a single text box (where the user would enter the date as a string in the box):: - ->add('dueDate', DateType::class, array('widget' => 'single_text')) + ->add('dueDate', DateType::class, ['widget' => 'single_text']) .. image:: /_images/form/simple-form-2.png :align: center @@ -462,10 +462,10 @@ the documentation for each type. :ref:`disable HTML5 validation ` or set the ``required`` option on your field to ``false``:: - ->add('dueDate', DateType::class, array( + ->add('dueDate', DateType::class, [ 'widget' => 'single_text', 'required' => false - )) + ]) Also note that setting the ``required`` option to ``true`` will **not** result in server-side validation to be applied. In other words, if a @@ -481,10 +481,10 @@ the documentation for each type. The label for the form field can be set using the ``label`` option, which can be applied to any field:: - ->add('dueDate', DateType::class, array( + ->add('dueDate', DateType::class, [ 'widget' => 'single_text', 'label' => 'Due Date', - )) + ]) The label for a field can also be set in the template rendering the form, see below. If you don't need a label associated to your input, @@ -510,7 +510,7 @@ guess from the validation rules that both the ``task`` field is a normal $form = $this->createFormBuilder($task) ->add('task') - ->add('dueDate', null, array('widget' => 'single_text')) + ->add('dueDate', null, ['widget' => 'single_text']) ->add('save', SubmitType::class) ->getForm(); } @@ -563,7 +563,7 @@ the correct values of a number of field options. If you'd like to change one of the guessed values, you can override it by passing the option in the options field array:: - ->add('task', null, array('attr' => array('maxlength' => 4))) + ->add('task', null, ['attr' => ['maxlength' => 4]]) .. index:: single: Forms; Creating form classes @@ -591,7 +591,7 @@ that will house the logic for building the task form:: { $builder ->add('task') - ->add('dueDate', null, array('widget' => 'single_text')) + ->add('dueDate', null, ['widget' => 'single_text']) ->add('save', SubmitType::class) ; } @@ -634,9 +634,9 @@ the choice is ultimately up to you. // ... public function configureOptions(OptionsResolver $resolver) { - $resolver->setDefaults(array( + $resolver->setDefaults([ 'data_class' => Task::class, - )); + ]); } .. tip:: @@ -656,7 +656,7 @@ the choice is ultimately up to you. $builder ->add('task') ->add('dueDate') - ->add('agreeTerms', CheckboxType::class, array('mapped' => false)) + ->add('agreeTerms', CheckboxType::class, ['mapped' => false]) ->add('save', SubmitType::class) ; } diff --git a/frontend/assetic/apply_to_option.rst b/frontend/assetic/apply_to_option.rst index 02507a8028f..983792f748c 100644 --- a/frontend/assetic/apply_to_option.rst +++ b/frontend/assetic/apply_to_option.rst @@ -51,15 +51,15 @@ An example configuration might look like this: .. code-block:: php // app/config/config.php - $container->loadFromExtension('assetic', array( - 'filters' => array( - 'coffee' => array( + $container->loadFromExtension('assetic', [ + 'filters' => [ + 'coffee' => [ 'bin' => '/usr/bin/coffee', 'node' => '/usr/bin/node', - 'node_paths' => array('/usr/lib/node_modules/'), - ), - ), - )); + 'node_paths' => ['/usr/lib/node_modules/'], + ], + ], + ]); Filter a single File -------------------- @@ -147,16 +147,16 @@ In this case you can specify that the ``coffee`` filter is applied to all .. code-block:: php // app/config/config.php - $container->loadFromExtension('assetic', array( - 'filters' => array( - 'coffee' => array( + $container->loadFromExtension('assetic', [ + 'filters' => [ + 'coffee' => [ 'bin' => '/usr/bin/coffee', 'node' => '/usr/bin/node', - 'node_paths' => array('/usr/lib/node_modules/'), + 'node_paths' => ['/usr/lib/node_modules/'], 'apply_to' => '\.coffee$', - ), - ), - )); + ], + ], + ]); With this option, you no longer need to specify the ``coffee`` filter in the template. You can also list regular JavaScript files, all of which will be diff --git a/frontend/assetic/asset_management.rst b/frontend/assetic/asset_management.rst index 62f9d50734f..748d6f2dbc5 100644 --- a/frontend/assetic/asset_management.rst +++ b/frontend/assetic/asset_management.rst @@ -26,10 +26,10 @@ Then, enable the bundle in the ``AppKernel.php`` file of your Symfony applicatio public function registerBundles() { - $bundles = array( + $bundles = [ // ... new Symfony\Bundle\AsseticBundle\AsseticBundle(), - ); + ]; // ... } @@ -73,14 +73,14 @@ your application: .. code-block:: php // app/config/config.php - $container->loadFromExtension('assetic', array( + $container->loadFromExtension('assetic', [ 'debug' => '%kernel.debug%', 'use_controller' => '%kernel.debug%', - 'filters' => array( + 'filters' => [ 'cssrewrite' => null, - ), + ], // ... - )); + ]); // ... @@ -338,16 +338,16 @@ configuration under the ``assetic`` section. Read more in the .. code-block:: php // app/config/config.php - $container->loadFromExtension('assetic', array( - 'assets' => array( - 'jquery_and_ui' => array( - 'inputs' => array( + $container->loadFromExtension('assetic', [ + 'assets' => [ + 'jquery_and_ui' => [ + 'inputs' => [ '@AppBundle/Resources/public/js/thirdparty/jquery.js', '@AppBundle/Resources/public/js/thirdparty/jquery.ui.js', - ), - ), - ), - )); + ], + ], + ], + ]); After you have defined the named assets, you can reference them in your templates with the ``@named_asset`` notation: @@ -418,13 +418,13 @@ should be defined: .. code-block:: php // app/config/config.php - $container->loadFromExtension('assetic', array( - 'filters' => array( - 'uglifyjs2' => array( + $container->loadFromExtension('assetic', [ + 'filters' => [ + 'uglifyjs2' => [ 'bin' => '/usr/local/bin/uglifyjs', - ), - ), - )); + ], + ], + ]); Now, to actually *use* the filter on a group of JavaScript files, add it into your template: @@ -542,9 +542,9 @@ the following change in your ``config_dev.yml`` file: .. code-block:: php // app/config/config_dev.php - $container->loadFromExtension('assetic', array( + $container->loadFromExtension('assetic', [ 'use_controller' => false, - )); + ]); Next, since Symfony is no longer generating these assets for you, you'll need to dump them manually. To do so, run the following command: diff --git a/frontend/assetic/jpeg_optimize.rst b/frontend/assetic/jpeg_optimize.rst index 324975cbae7..17d8dfb4d5c 100644 --- a/frontend/assetic/jpeg_optimize.rst +++ b/frontend/assetic/jpeg_optimize.rst @@ -51,13 +51,13 @@ using the ``bin`` option of the ``jpegoptim`` filter: .. code-block:: php // app/config/config.php - $container->loadFromExtension('assetic', array( - 'filters' => array( - 'jpegoptim' => array( + $container->loadFromExtension('assetic', [ + 'filters' => [ + 'jpegoptim' => [ 'bin' => 'path/to/jpegoptim', - ), - ), - )); + ], + ], + ]); It can now be used from a template: @@ -109,14 +109,14 @@ to ``true``: .. code-block:: php // app/config/config.php - $container->loadFromExtension('assetic', array( - 'filters' => array( - 'jpegoptim' => array( + $container->loadFromExtension('assetic', [ + 'filters' => [ + 'jpegoptim' => [ 'bin' => 'path/to/jpegoptim', 'strip_all' => 'true', - ), - ), - )); + ], + ], + ]); Lowering Maximum Quality ~~~~~~~~~~~~~~~~~~~~~~~~ @@ -160,14 +160,14 @@ be at the expense of its quality: .. code-block:: php // app/config/config.php - $container->loadFromExtension('assetic', array( - 'filters' => array( - 'jpegoptim' => array( + $container->loadFromExtension('assetic', [ + 'filters' => [ + 'jpegoptim' => [ 'bin' => 'path/to/jpegoptim', 'max' => '70', - ), - ), - )); + ], + ], + ]); Shorter Syntax: Twig Function ----------------------------- @@ -215,16 +215,16 @@ following configuration: .. code-block:: php // app/config/config.php - $container->loadFromExtension('assetic', array( - 'filters' => array( - 'jpegoptim' => array( + $container->loadFromExtension('assetic', [ + 'filters' => [ + 'jpegoptim' => [ 'bin' => 'path/to/jpegoptim', - ), - ), - 'twig' => array( - 'functions' => array('jpegoptim'), - ), - )); + ], + ], + 'twig' => [ + 'functions' => ['jpegoptim'], + ], + ]); The Twig template can now be changed to the following: @@ -275,20 +275,20 @@ file: .. code-block:: php // app/config/config.php - $container->loadFromExtension('assetic', array( - 'filters' => array( - 'jpegoptim' => array( + $container->loadFromExtension('assetic', [ + 'filters' => [ + 'jpegoptim' => [ 'bin' => 'path/to/jpegoptim', - ), - ), - 'twig' => array( - 'functions' => array( - 'jpegoptim' => array( + ], + ], + 'twig' => [ + 'functions' => [ + 'jpegoptim' => [ 'output' => 'images/*.jpg', - ), - ), - ), - )); + ], + ], + ], + ]); .. tip:: diff --git a/frontend/assetic/php.rst b/frontend/assetic/php.rst index bea6f2f8946..2ed40409430 100644 --- a/frontend/assetic/php.rst +++ b/frontend/assetic/php.rst @@ -106,14 +106,14 @@ First, configure a new ``scssphp`` Assetic filter: .. code-block:: php // app/config/config.php - $container->loadFromExtension('assetic', array( - 'filters' => array( - 'scssphp' => array( + $container->loadFromExtension('assetic', [ + 'filters' => [ + 'scssphp' => [ 'formatter' => 'Leafo\ScssPhp\Formatter\Compressed', - ), + ], // ... - ), - )); + ], + ]); The value of the ``formatter`` option is the fully qualified class name of the formatter used by the filter to produce the compiled CSS file. Using the @@ -179,12 +179,12 @@ First, configure a new ``jsqueeze`` Assetic filter as follows: .. code-block:: php // app/config/config.php - $container->loadFromExtension('assetic', array( - 'filters' => array( + $container->loadFromExtension('assetic', [ + 'filters' => [ 'jsqueeze' => null, // ... - ), - )); + ], + ]); Next, update the code of your Twig template to add the ``{% javascripts %}`` tag defined by Assetic: diff --git a/frontend/assetic/uglifyjs.rst b/frontend/assetic/uglifyjs.rst index c255c309121..2a322495dd1 100644 --- a/frontend/assetic/uglifyjs.rst +++ b/frontend/assetic/uglifyjs.rst @@ -111,14 +111,14 @@ your JavaScripts: .. code-block:: php // app/config/config.php - $container->loadFromExtension('assetic', array( - 'filters' => array( - 'uglifyjs2' => array( + $container->loadFromExtension('assetic', [ + 'filters' => [ + 'uglifyjs2' => [ // the path to the uglifyjs executable 'bin' => '/usr/local/bin/uglifyjs', - ), - ), - )); + ], + ], + ]); .. note:: @@ -179,13 +179,13 @@ can configure its location using the ``node`` key: .. code-block:: php // app/config/config.php - $container->loadFromExtension('assetic', array( + $container->loadFromExtension('assetic', [ 'node' => '/usr/bin/nodejs', - 'uglifyjs2' => array( + 'uglifyjs2' => [ // the path to the uglifyjs executable 'bin' => '/usr/local/bin/uglifyjs', - ), - )); + ], + ]); Minify your Assets ------------------ @@ -282,13 +282,13 @@ Next, add the configuration for this filter: .. code-block:: php // app/config/config.php - $container->loadFromExtension('assetic', array( - 'filters' => array( - 'uglifycss' => array( + $container->loadFromExtension('assetic', [ + 'filters' => [ + 'uglifycss' => [ 'bin' => '/usr/local/bin/uglifycss', - ), - ), - )); + ], + ], + ]); To use the filter for your CSS files, add the filter to the Assetic ``stylesheets`` helper: diff --git a/frontend/assetic/yuicompressor.rst b/frontend/assetic/yuicompressor.rst index 6a02a005545..0f6eb5820e7 100644 --- a/frontend/assetic/yuicompressor.rst +++ b/frontend/assetic/yuicompressor.rst @@ -67,17 +67,17 @@ stylesheets: .. code-block:: php // app/config/config.php - $container->loadFromExtension('assetic', array( + $container->loadFromExtension('assetic', [ // 'java' => '/usr/bin/java', - 'filters' => array( - 'yui_css' => array( + 'filters' => [ + 'yui_css' => [ 'jar' => '%kernel.project_dir%/app/Resources/java/yuicompressor.jar', - ), - 'yui_js' => array( + ], + 'yui_js' => [ 'jar' => '%kernel.project_dir%/app/Resources/java/yuicompressor.jar', - ), - ), - )); + ], + ], + ]); .. note:: diff --git a/frontend/custom_version_strategy.rst b/frontend/custom_version_strategy.rst index 1dcd2754667..5979bae7d65 100644 --- a/frontend/custom_version_strategy.rst +++ b/frontend/custom_version_strategy.rst @@ -151,10 +151,10 @@ After creating the strategy PHP class, register it as a Symfony service. $container->autowire(GulpBusterVersionStrategy::class) ->setArguments( - array( + [ '%kernel.project_dir%/busters.json', '%%s?version=%%s', - ) + ] )->setPublic(false); Finally, enable the new asset versioning for all the application assets or just @@ -191,11 +191,11 @@ the :ref:`version_strategy ` option: // app/config/config.php use AppBundle\Asset\VersionStrategy\GulpBusterVersionStrategy; - $container->loadFromExtension('framework', array( + $container->loadFromExtension('framework', [ // ... - 'assets' => array( + 'assets' => [ 'version_strategy' => GulpBusterVersionStrategy::class, - ), - )); + ], + ]); .. _`gulp-buster`: https://www.npmjs.com/package/gulp-buster diff --git a/http_cache.rst b/http_cache.rst index 0001b357d29..2f77a314a22 100644 --- a/http_cache.rst +++ b/http_cache.rst @@ -127,10 +127,10 @@ method:: { protected function getOptions() { - return array( + return [ 'default_ttl' => 0, // ... - ); + ]; } } @@ -318,14 +318,14 @@ Additionally, most cache-related HTTP headers can be set via the single :method:`Symfony\\Component\\HttpFoundation\\Response::setCache` method:: // sets cache settings in one call - $response->setCache(array( + $response->setCache([ 'etag' => $etag, 'last_modified' => $date, 'max_age' => 10, 's_maxage' => 10, 'public' => true, // 'private' => true, - )); + ]); Cache Invalidation ------------------ diff --git a/http_cache/cache_vary.rst b/http_cache/cache_vary.rst index 04348dd05a8..1dbbf9a0fc4 100644 --- a/http_cache/cache_vary.rst +++ b/http_cache/cache_vary.rst @@ -39,7 +39,7 @@ header:: $response->setVary('Accept-Encoding'); // sets multiple vary headers - $response->setVary(array('Accept-Encoding', 'User-Agent')); + $response->setVary(['Accept-Encoding', 'User-Agent']); The ``setVary()`` method takes a header name or an array of header names for which the response varies. diff --git a/http_cache/esi.rst b/http_cache/esi.rst index e414f1c4833..b22d3582b58 100644 --- a/http_cache/esi.rst +++ b/http_cache/esi.rst @@ -88,10 +88,10 @@ First, to use ESI, be sure to enable it in your application configuration: .. code-block:: php // app/config/config.php - $container->loadFromExtension('framework', array( + $container->loadFromExtension('framework', [ // ... - 'esi' => array('enabled' => true), - )); + 'esi' => ['enabled' => true], + ]); Now, suppose you have a page that is relatively static, except for a news ticker at the bottom of the content. With ESI, you can cache the news ticker @@ -218,10 +218,10 @@ that must be enabled in your configuration: .. code-block:: php // app/config/config.php - $container->loadFromExtension('framework', array( + $container->loadFromExtension('framework', [ // ... - 'fragments' => array('path' => '/_fragment'), - )); + 'fragments' => ['path' => '/_fragment'], + ]); One great advantage of the ESI renderer is that you can make your application as dynamic as needed and at the same time, hit the application as little as diff --git a/http_cache/validation.rst b/http_cache/validation.rst index 15e76ec4212..7951cb7d618 100644 --- a/http_cache/validation.rst +++ b/http_cache/validation.rst @@ -217,10 +217,10 @@ exposing a simple and efficient pattern:: $comments = ...; // or render a template with the $response you've already started - return $this->render('article/show.html.twig', array( + return $this->render('article/show.html.twig', [ 'article' => $article, 'comments' => $comments, - ), $response); + ], $response); } } diff --git a/introduction/from_flat_php_to_symfony2.rst b/introduction/from_flat_php_to_symfony2.rst index 17907f1c047..bd678900a5c 100644 --- a/introduction/from_flat_php_to_symfony2.rst +++ b/introduction/from_flat_php_to_symfony2.rst @@ -91,7 +91,7 @@ the code that prepares the HTML "presentation":: $result = $connection->query('SELECT id, title FROM post'); - $posts = array(); + $posts = []; while ($row = $result->fetch(PDO::FETCH_ASSOC)) { $posts[] = $row; } @@ -163,7 +163,7 @@ of the application are isolated in a new file called ``model.php``:: $result = $connection->query('SELECT id, title FROM post'); - $posts = array(); + $posts = []; while ($row = $result->fetch(PDO::FETCH_ASSOC)) { $posts[] = $row; } @@ -486,7 +486,7 @@ incidentally, acts quite a bit like the Symfony templating engine:: function list_action() { $posts = get_all_posts(); - $html = render_template('templates/list.php', array('posts' => $posts)); + $html = render_template('templates/list.php', ['posts' => $posts]); return new Response($html); } @@ -494,7 +494,7 @@ incidentally, acts quite a bit like the Symfony templating engine:: function show_action($id) { $post = get_post_by_id($id); - $html = render_template('templates/show.php', array('post' => $post)); + $html = render_template('templates/show.php', ['post' => $post]); return new Response($html); } @@ -555,7 +555,7 @@ them for you. Here's the same sample application, now built in Symfony:: ->createQuery('SELECT p FROM AppBundle:Post p') ->execute(); - return $this->render('Blog/list.html.php', array('posts' => $posts)); + return $this->render('Blog/list.html.php', ['posts' => $posts]); } public function showAction($id) @@ -569,7 +569,7 @@ them for you. Here's the same sample application, now built in Symfony:: throw $this->createNotFoundException(); } - return $this->render('Blog/show.html.php', array('post' => $post)); + return $this->render('Blog/show.html.php', ['post' => $post]); } } @@ -595,7 +595,7 @@ database and the Templating component to render a template and return a
  • getTitle() ?> diff --git a/introduction/http_fundamentals.rst b/introduction/http_fundamentals.rst index 4d261617dc3..13c14800dc9 100644 --- a/introduction/http_fundamentals.rst +++ b/introduction/http_fundamentals.rst @@ -337,7 +337,7 @@ A very simple front controller might look like this:: $request = Request::createFromGlobals(); $path = $request->getPathInfo(); // the URI path being requested - if (in_array($path, array('', '/'))) { + if (in_array($path, ['', '/'])) { $response = new Response('Welcome to the homepage.'); } elseif ('/contact' === $path) { $response = new Response('Contact us'); diff --git a/logging.rst b/logging.rst index 56a3675bc44..a44d51a4e98 100644 --- a/logging.rst +++ b/logging.rst @@ -35,10 +35,10 @@ To log a message, inject the default logger in your controller:: $logger->info('I just got the logger'); $logger->error('An error occurred'); - $logger->critical('I left the oven on!', array( + $logger->critical('I left the oven on!', [ // include extra "context" info in your logs 'cause' => 'in_hurry', - )); + ]); // ... } @@ -147,19 +147,19 @@ to write logs using the :phpfunction:`syslog` function: .. code-block:: php // app/config/config.php - $container->loadFromExtension('monolog', array( - 'handlers' => array( - 'file_log' => array( + $container->loadFromExtension('monolog', [ + 'handlers' => [ + 'file_log' => [ 'type' => 'stream', 'path' => '%kernel.logs_dir%/%kernel.environment%.log', 'level' => 'debug', - ), - 'syslog_handler' => array( + ], + 'syslog_handler' => [ 'type' => 'syslog', 'level' => 'error', - ), - ), - )); + ], + ], + ]); This defines a *stack* of handlers and each handler is called in the order that it's defined. @@ -232,24 +232,24 @@ one of the messages reaches an ``action_level``. Take this example: .. code-block:: php // app/config/config.php - $container->loadFromExtension('monolog', array( - 'handlers' => array( - 'filter_for_errors' => array( + $container->loadFromExtension('monolog', [ + 'handlers' => [ + 'filter_for_errors' => [ 'type' => 'fingers_crossed', 'action_level' => 'error', 'handler' => 'file_log', - ), - 'file_log' => array( + ], + 'file_log' => [ 'type' => 'stream', 'path' => '%kernel.logs_dir%/%kernel.environment%.log', 'level' => 'debug', - ), - 'syslog_handler' => array( + ], + 'syslog_handler' => [ 'type' => 'syslog', 'level' => 'error', - ), + ], ), - )); + ]); Now, if even one log entry has an ``error`` level or higher, then *all* log entries for that request are saved to a file via the ``file_log`` handler. That means that @@ -329,18 +329,18 @@ option of your handler to ``rotating_file``: .. code-block:: php // app/config/config_dev.php - $container->loadFromExtension('monolog', array( - 'handlers' => array( - 'main' => array( + $container->loadFromExtension('monolog', [ + 'handlers' => [ + 'main' => [ 'type' => 'rotating_file', 'path' => '%kernel.logs_dir%/%kernel.environment%.log', 'level' => 'debug', // max number of log files to keep // defaults to zero, which means infinite files 'max_files' => 10, - ), - ), - )); + ], + ], + ]); Using a Logger inside a Service ------------------------------- diff --git a/logging/channels_handlers.rst b/logging/channels_handlers.rst index 76ed1ee6efa..7ac4ff60f86 100644 --- a/logging/channels_handlers.rst +++ b/logging/channels_handlers.rst @@ -77,23 +77,23 @@ in all environments, or just ``config_prod.yml`` to happen only in ``prod``: .. code-block:: php // app/config/config.php - $container->loadFromExtension('monolog', array( - 'handlers' => array( - 'security' => array( + $container->loadFromExtension('monolog', [ + 'handlers' => [ + 'security' => [ 'type' => 'stream', 'path' => '%kernel.logs_dir%/security.log', - 'channels' => array( + 'channels' => [ 'security', - ), - ), - 'main' => array( + ], + ], + 'main' => [ // ... - 'channels' => array( + 'channels' => [ '!security', - ), - ), - ), - )); + ], + ], + ], + ]); .. caution:: @@ -162,12 +162,12 @@ You can also configure additional channels without the need to tag your services .. code-block:: php // app/config/config.php - $container->loadFromExtension('monolog', array( - 'channels' => array( + $container->loadFromExtension('monolog', [ + 'channels' => [ 'foo', 'bar', - ), - )); + ], + ]); Symfony automatically registers one service per channel (in this example, the channel ``foo`` creates a service called ``monolog.logger.foo``). In order to diff --git a/logging/disable_microsecond_precision.rst b/logging/disable_microsecond_precision.rst index 5e090b45072..442c742c768 100644 --- a/logging/disable_microsecond_precision.rst +++ b/logging/disable_microsecond_precision.rst @@ -45,13 +45,13 @@ log generation. This is recommended for systems that generate a large number of .. code-block:: php // app/config/config.php - $container->loadFromExtension('monolog', array( + $container->loadFromExtension('monolog', [ 'use_microseconds' => false, - 'handlers' => array( - 'applog' => array( + 'handlers' => [ + 'applog' => [ 'type' => 'stream', 'path' => '/var/log/symfony.log', 'level' => 'error', - ), - ), - )); + ], + ], + ]); diff --git a/logging/formatter.rst b/logging/formatter.rst index 56c0d0cb986..f5a0683c549 100644 --- a/logging/formatter.rst +++ b/logging/formatter.rst @@ -64,12 +64,12 @@ configure your handler to use it: $container->register(JsonFormatter::class); // app/config/config_prod.php (or config_dev.php) - $container->loadFromExtension('monolog', array( - 'handlers' => array( - 'file' => array( + $container->loadFromExtension('monolog', [ + 'handlers' => [ + 'file' => [ 'type' => 'stream', 'level' => 'debug', 'formatter' => JsonFormatter::class, - ), - ), - )); + ], + ], + ]); diff --git a/logging/monolog_console.rst b/logging/monolog_console.rst index 293f4b86e99..36013cd7835 100644 --- a/logging/monolog_console.rst +++ b/logging/monolog_console.rst @@ -98,15 +98,15 @@ example, in ``config_dev.yml``: .. code-block:: php // app/config/config.php - $container->loadFromExtension('monolog', array( - 'handlers' => array( - 'console' => array( - 'type' => 'console', - 'process_psr_3_messages' => false, - 'channels' => array('!event', '!doctrine', '!console'), - ), - ), - )); + $container->loadFromExtension('monolog', [ + 'handlers' => [ + 'console' => [ + 'type' => 'console', + 'process_psr_3_messages' => false, + 'channels' => ['!event', '!doctrine', '!console'], + ], + ], + ]); Now, log messages will be shown on the console based on the log levels and verbosity. By default (normal verbosity level), warnings and higher will be shown. But in diff --git a/logging/monolog_email.rst b/logging/monolog_email.rst index f6845f57990..2a989655be8 100644 --- a/logging/monolog_email.rst +++ b/logging/monolog_email.rst @@ -94,36 +94,36 @@ it is broken down. .. code-block:: php // app/config/config_prod.php - $container->loadFromExtension('monolog', array( - 'handlers' => array( - 'main' => array( + $container->loadFromExtension('monolog', [ + 'handlers' => [ + 'main' => [ 'type' => 'fingers_crossed', // 500 errors are logged at the critical level 'action_level' => 'critical', // to also log 400 level errors (but not 404's): // 'action_level' => 'error', - // 'excluded_404s' => array( + // 'excluded_404s' => [ // '^/', - // ), + // ], 'handler' => 'deduplicated', - ), - 'deduplicated' => array( + ], + 'deduplicated' => [ 'type' => 'deduplication', 'handler' => 'swift', - ), - 'swift' => array( + ], + 'swift' => [ 'type' => 'swift_mailer', 'from_email' => 'error@example.com', 'to_email' => 'error@example.com', // or a list of recipients - // 'to_email' => array('dev1@example.com', 'dev2@example.com', ...), + // 'to_email' => ['dev1@example.com', 'dev2@example.com', ...], 'subject' => 'An Error Occurred! %%message%%', 'level' => 'debug', 'formatter' => 'monolog.formatter.html', 'content_type' => 'text/html', - ), - ), - )); + ], + ], + ]); The ``main`` handler is a ``fingers_crossed`` handler which means that it is only triggered when the action level, in this case ``critical`` is reached. @@ -172,15 +172,15 @@ You can adjust the time period using the ``time`` option: .. code-block:: php // app/config/config_prod.php - $container->loadFromExtension('monolog', array( - 'handlers' => array( + $container->loadFromExtension('monolog', [ + 'handlers' => [ // ... - 'deduplicated' => array( + 'deduplicated' => [ 'type' => 'deduplication', // the time in seconds during which duplicate entries are discarded (default: 60) 'time' => 10, 'handler' => 'swift', - ) + ] The messages are then passed to the ``swift`` handler. This is the handler that actually deals with emailing you the error. The settings for this are @@ -278,39 +278,39 @@ get logged on the server as well as the emails being sent: .. code-block:: php // app/config/config_prod.php - $container->loadFromExtension('monolog', array( - 'handlers' => array( - 'main' => array( + $container->loadFromExtension('monolog', [ + 'handlers' => [ + 'main' => [ 'type' => 'fingers_crossed', 'action_level' => 'critical', 'handler' => 'grouped', - ), - 'grouped' => array( + ], + 'grouped' => [ 'type' => 'group', - 'members' => array('streamed', 'deduplicated'), - ), - 'streamed' => array( + 'members' => ['streamed', 'deduplicated'], + ], + 'streamed' => [ 'type' => 'stream', 'path' => '%kernel.logs_dir%/%kernel.environment%.log', 'level' => 'debug', - ), - 'deduplicated' => array( + ], + 'deduplicated' => [ 'type' => 'deduplication', 'handler' => 'swift', - ), - 'swift' => array( + ], + 'swift' => [ 'type' => 'swift_mailer', 'from_email' => 'error@example.com', 'to_email' => 'error@example.com', // or a list of recipients - // 'to_email' => array('dev1@example.com', 'dev2@example.com', ...), + // 'to_email' => ['dev1@example.com', 'dev2@example.com', ...], 'subject' => 'An Error Occurred! %%message%%', 'level' => 'debug', 'formatter' => 'monolog.formatter.html', 'content_type' => 'text/html', - ), - ), - )); + ], + ], + ]); This uses the ``group`` handler to send the messages to the two group members, the ``deduplicated`` and the ``stream`` handlers. The messages will diff --git a/logging/monolog_regex_based_excludes.rst b/logging/monolog_regex_based_excludes.rst index 51df5adf716..7bb2f8a99cc 100644 --- a/logging/monolog_regex_based_excludes.rst +++ b/logging/monolog_regex_based_excludes.rst @@ -48,15 +48,15 @@ configuration: .. code-block:: php // app/config/config.php - $container->loadFromExtension('monolog', array( - 'handlers' => array( - 'main' => array( + $container->loadFromExtension('monolog', [ + 'handlers' => [ + 'main' => [ // ... 'type' => 'fingers_crossed', 'handler' => ..., - 'excluded_404s' => array( + 'excluded_404s' => [ '^/phpmyadmin', - ), - ), - ), - )); + ], + ], + ], + ]); diff --git a/logging/processors.rst b/logging/processors.rst index 1ba38aaaae3..70da931b02e 100644 --- a/logging/processors.rst +++ b/logging/processors.rst @@ -102,7 +102,7 @@ information: $container ->autowire(SessionRequestProcessor::class) - ->addTag('monolog.processor', array('method' => 'processRecord')); + ->addTag('monolog.processor', ['method' => 'processRecord']); Finally, set the formatter to be used on whatever handler you want: @@ -145,16 +145,16 @@ Finally, set the formatter to be used on whatever handler you want: .. code-block:: php // app/config/config.php - $container->loadFromExtension('monolog', array( - 'handlers' => array( - 'main' => array( + $container->loadFromExtension('monolog', [ + 'handlers' => [ + 'main' => [ 'type' => 'stream', 'path' => '%kernel.logs_dir%/%kernel.environment%.log', 'level' => 'debug', 'formatter' => 'monolog.formatter.session_request', - ), - ), - )); + ], + ], + ]); If you use several handlers, you can also register a processor at the handler level or at the channel level instead of registering it globally @@ -203,7 +203,7 @@ the ``monolog.processor`` tag: // ... $container ->autowire(SessionRequestProcessor::class) - ->addTag('monolog.processor', array('handler' => 'main')); + ->addTag('monolog.processor', ['handler' => 'main']); Registering Processors per Channel ---------------------------------- @@ -248,4 +248,4 @@ the ``monolog.processor`` tag: // ... $container ->autowire(SessionRequestProcessor::class) - ->addTag('monolog.processor', array('channel' => 'main')); + ->addTag('monolog.processor', ['channel' => 'main']); diff --git a/page_creation.rst b/page_creation.rst index 7e86bb78860..441b869f170 100644 --- a/page_creation.rst +++ b/page_creation.rst @@ -131,9 +131,9 @@ variable so we can render that:: { $number = random_int(0, 100); - return $this->render('lucky/number.html.twig', array( + return $this->render('lucky/number.html.twig', [ 'number' => $number, - )); + ]); } } @@ -207,11 +207,11 @@ Bundles are registered in your ``app/AppKernel.php`` file (a rare PHP file in th { public function registerBundles() { - $bundles = array( + $bundles = [ new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), // ... - ); + ]; // ... return $bundles; diff --git a/profiler/data_collector.rst b/profiler/data_collector.rst index 3eb694d64af..809aaa51b4c 100644 --- a/profiler/data_collector.rst +++ b/profiler/data_collector.rst @@ -32,15 +32,15 @@ request:: { public function collect(Request $request, Response $response, \Exception $exception = null) { - $this->data = array( + $this->data = [ 'method' => $request->getMethod(), 'acceptable_content_types' => $request->getAcceptableContentTypes(), - ); + ]; } public function reset() { - $this->data = array(); + $this->data = []; } public function getName() @@ -278,11 +278,11 @@ to specify a tag that contains the template: $container ->autowire(RequestCollector::class) ->setPublic(false) - ->addTag('data_collector', array( + ->addTag('data_collector', [ 'template' => 'data_collector/template.html.twig', 'id' => 'app.request_collector', // 'priority' => 300, - )) + ]) ; The position of each panel in the toolbar is determined by the priority defined diff --git a/profiler/matchers.rst b/profiler/matchers.rst index c3ec0d51281..3e88de8c2ea 100644 --- a/profiler/matchers.rst +++ b/profiler/matchers.rst @@ -58,14 +58,14 @@ configuration: .. code-block:: php // app/config/config.php - $container->loadFromExtension('framework', array( + $container->loadFromExtension('framework', [ // ... - 'profiler' => array( - 'matcher' => array( + 'profiler' => [ + 'matcher' => [ 'ip' => '168.0.0.1', - ) - ), - )); + ] + ], + ]); You can also set a ``path`` option to define the path on which the profiler should be enabled. For instance, setting it to ``^/admin/`` will enable the @@ -153,11 +153,11 @@ profiler to use this service as the matcher: // app/config/config.php use AppBundle\Profiler\SuperAdminMatcher; - $container->loadFromExtension('framework', array( + $container->loadFromExtension('framework', [ // ... - 'profiler' => array( - 'matcher' => array( + 'profiler' => [ + 'matcher' => [ 'service' => SuperAdminMatcher::class, - ) - ), - )); + ] + ], + ]); diff --git a/profiler/storage.rst b/profiler/storage.rst index f4bdaaca061..b4879540ef8 100644 --- a/profiler/storage.rst +++ b/profiler/storage.rst @@ -43,11 +43,11 @@ directory. If you want to use another location to store the profiles, define the // app/config/config.php // ... - $container->loadFromExtension('framework', array( - 'profiler' => array( + $container->loadFromExtension('framework', [ + 'profiler' => [ 'dsn' => 'file:/tmp/symfony/profiler', - ), - )); + ], + ]); You can also create your own profile storage service implementing the :class:`Symfony\\Component\\HttpKernel\\Profiler\\ProfilerStorageInterface` and diff --git a/quick_tour/the_architecture.rst b/quick_tour/the_architecture.rst index 4130cd063ae..1c0b6325663 100644 --- a/quick_tour/the_architecture.rst +++ b/quick_tour/the_architecture.rst @@ -111,7 +111,7 @@ a single Bundle class that describes it:: // app/AppKernel.php public function registerBundles() { - $bundles = array( + $bundles = [ new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\SecurityBundle\SecurityBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), @@ -121,9 +121,9 @@ a single Bundle class that describes it:: new Symfony\Bundle\AsseticBundle\AsseticBundle(), new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(), new AppBundle\AppBundle(), - ); + ]; - if (in_array($this->getEnvironment(), array('dev', 'test'))) { + if (in_array($this->getEnvironment(), ['dev', 'test'])) { $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle(); $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle(); $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle(); diff --git a/quick_tour/the_controller.rst b/quick_tour/the_controller.rst index bd299aca51a..9aef4a9b155 100644 --- a/quick_tour/the_controller.rst +++ b/quick_tour/the_controller.rst @@ -69,9 +69,9 @@ a new method called ``helloAction()`` with the following content:: */ public function helloAction($name) { - return $this->render('default/hello.html.twig', array( + return $this->render('default/hello.html.twig', [ 'name' => $name, - )); + ]); } } @@ -123,9 +123,9 @@ as its default value:: */ public function helloAction($name, $_format) { - return $this->render('default/hello.'.$_format.'.twig', array( + return $this->render('default/hello.'.$_format.'.twig', [ 'name' => $name, - )); + ]); } Obviously, when you support several request formats, you have to provide @@ -165,9 +165,9 @@ option of the ``@Route()`` annotation:: */ public function helloAction($name, $_format) { - return $this->render('default/hello.'.$_format.'.twig', array( + return $this->render('default/hello.'.$_format.'.twig', [ 'name' => $name, - )); + ]); } The ``hello`` action will now match URLs like ``/hello/fabien.xml`` or @@ -191,7 +191,7 @@ method:: */ public function indexAction() { - return $this->redirectToRoute('hello', array('name' => 'Fabien')); + return $this->redirectToRoute('hello', ['name' => 'Fabien']); } } @@ -267,7 +267,7 @@ forget to add the new ``use`` statement that imports this ``Request`` class):: $isAjax = $request->isXmlHttpRequest(); // what's the preferred language of the user? - $language = $request->getPreferredLanguage(array('en', 'fr')); + $language = $request->getPreferredLanguage(['en', 'fr']); // get the value of a $_GET parameter $pageName = $request->query->get('page'); diff --git a/quick_tour/the_view.rst b/quick_tour/the_view.rst index b3741557d23..db281a3780d 100644 --- a/quick_tour/the_view.rst +++ b/quick_tour/the_view.rst @@ -54,9 +54,9 @@ To render a template in Symfony, use the ``render()`` method from within a controller. If the template needs variables to generate its contents, pass them as an array using the second optional argument:: - $this->render('default/index.html.twig', array( + $this->render('default/index.html.twig', [ 'variable_name' => 'variable_value', - )); + ]); Variables passed to a template can be strings, arrays or even objects. Twig abstracts the difference between them and lets you access "attributes" of @@ -67,24 +67,24 @@ on its type: .. code-block:: twig {# 1. Simple variables #} - {# $this->render('template.html.twig', array( + {# $this->render('template.html.twig', [ 'name' => 'Fabien', - )) #} + ]) #} {{ name }} {# 2. Arrays #} - {# $this->render('template.html.twig', array( - 'user' => array('name' => 'Fabien')) - ) #} + {# $this->render('template.html.twig', [ + 'user' => ['name' => 'Fabien'] + ]) #} {{ user.name }} {# alternative syntax for arrays #} {{ user['name'] }} {# 3. Objects #} - {# $this->render('template.html.twig', array( - 'user' => new User('Fabien')) - ) #} + {# $this->render('template.html.twig', [ + 'user' => new User('Fabien') + ]) #} {{ user.name }} {{ user.getName }} @@ -221,9 +221,9 @@ later):: // look for the most popular articles in the database $articles = ...; - return $this->render('default/top_articles.html.twig', array( + return $this->render('default/top_articles.html.twig', [ 'articles' => $articles, - )); + ]); } // ... diff --git a/reference/configuration/debug.rst b/reference/configuration/debug.rst index 944a98c46e2..c57c26b1fac 100644 --- a/reference/configuration/debug.rst +++ b/reference/configuration/debug.rst @@ -98,6 +98,6 @@ destination for dumps. Typically, you would set this to ``php://stderr``: .. code-block:: php // app/config/config.php - $container->loadFromExtension('debug', array( + $container->loadFromExtension('debug', [ 'dump_destination' => 'php://stderr', - )); + ]); diff --git a/reference/configuration/doctrine.rst b/reference/configuration/doctrine.rst index de6b79da878..e263d47d241 100644 --- a/reference/configuration/doctrine.rst +++ b/reference/configuration/doctrine.rst @@ -341,14 +341,14 @@ directory instead: .. code-block:: php - $container->loadFromExtension('doctrine', array( - 'orm' => array( + $container->loadFromExtension('doctrine', [ + 'orm' => [ 'auto_mapping' => true, - 'mappings' => array( - 'AppBundle' => array('dir' => 'SomeResources/config/doctrine', 'type' => 'xml'), - ), - ), - )); + 'mappings' => [ + 'AppBundle' => ['dir' => 'SomeResources/config/doctrine', 'type' => 'xml'], + ], + ], + ]); Mapping Entities Outside of a Bundle ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -400,20 +400,20 @@ namespace in the ``src/Entity`` directory and gives them an ``App`` alias .. code-block:: php - $container->loadFromExtension('doctrine', array( - 'orm' => array( + $container->loadFromExtension('doctrine', [ + 'orm' => [ 'auto_mapping' => true, - 'mappings' => array( - 'SomeEntityNamespace' => array( + 'mappings' => [ + 'SomeEntityNamespace' => [ 'type' => 'annotation', 'dir' => '%kernel.project_dir%/src/Entity', 'is_bundle' => false, 'prefix' => 'App\Entity', 'alias' => 'App', - ), - ), - ), - )); + ], + ], + ], + ]); Detecting a Mapping Configuration Format ........................................ diff --git a/reference/configuration/framework.rst b/reference/configuration/framework.rst index be562afb786..fc07929a40f 100644 --- a/reference/configuration/framework.rst +++ b/reference/configuration/framework.rst @@ -302,9 +302,9 @@ doubling them to prevent Symfony from interpreting them as container parameters) .. code-block:: php // app/config/config.php - $container->loadFromExtension('framework', array( + $container->loadFromExtension('framework', [ 'ide' => 'myide://open?url=file://%%f&line=%%l', - )); + ]); Since every developer uses a different IDE, the recommended way to enable this feature is to configure it on a system level. This can be done by setting the @@ -374,7 +374,7 @@ method. trusted_hosts ~~~~~~~~~~~~~ -**type**: ``array`` | ``string`` **default**: ``array()`` +**type**: ``array`` | ``string`` **default**: ``[]`` A lot of different attacks have been discovered relying on inconsistencies in handling the ``Host`` header by various software (web servers, reverse @@ -424,9 +424,9 @@ the application won't respond and the user will receive a 400 response. .. code-block:: php // app/config/config.php - $container->loadFromExtension('framework', array( - 'trusted_hosts' => array('^example\.com$', '^example\.org$'), - )); + $container->loadFromExtension('framework', [ + 'trusted_hosts' => ['^example\.com$', '^example\.org$'], + ]); Hosts can also be configured to respond to any subdomain, via ``^(.+\.)?example\.com$`` for instance. @@ -435,7 +435,7 @@ In addition, you can also set the trusted hosts in the front controller using the ``Request::setTrustedHosts()`` method:: // web/app.php - Request::setTrustedHosts(array('^(.+\.)?example\.com$', '^(.+\.)?example\.org$')); + Request::setTrustedHosts(['^(.+\.)?example\.com$', '^(.+\.)?example\.org$']); The default value for this option is an empty array, meaning that the application can respond to any given host. @@ -538,9 +538,9 @@ You can also set ``esi`` to ``true`` to enable it: .. code-block:: php // app/config/config.php - $container->loadFromExtension('framework', array( + $container->loadFromExtension('framework', [ 'esi' => true, - )); + ]); fragments ~~~~~~~~~ @@ -727,13 +727,13 @@ To configure a ``jsonp`` format: .. code-block:: php // app/config/config.php - $container->loadFromExtension('framework', array( - 'request' => array( - 'formats' => array( + $container->loadFromExtension('framework', [ + 'request' => [ + 'formats' => [ 'jsonp' => 'application/javascript', - ), - ), - )); + ], + ], + ]); router ~~~~~~ @@ -941,11 +941,11 @@ setting the value to ``null``: .. code-block:: php // app/config/config.php - $container->loadFromExtension('framework', array( - 'session' => array( + $container->loadFromExtension('framework', [ + 'session' => [ 'save_path' => null, - ), - )); + ], + ]); .. _reference-session-metadata-update-threshold: @@ -998,11 +998,11 @@ Whether to enable the session support in the framework. .. code-block:: php // app/config/config.php - $container->loadFromExtension('framework', array( - 'session' => array( + $container->loadFromExtension('framework', [ + 'session' => [ 'enabled' => true, - ), - )); + ], + ]); assets ~~~~~~ @@ -1045,12 +1045,12 @@ This option allows you to define a base path to be used for assets: .. code-block:: php // app/config/config.php - $container->loadFromExtension('framework', array( + $container->loadFromExtension('framework', [ // ... - 'assets' => array( + 'assets' => [ 'base_path' => '/images', - ), - )); + ], + ]); .. _reference-templating-base-urls: .. _reference-assets-base-urls: @@ -1094,12 +1094,12 @@ collection each time it generates an asset's path: .. code-block:: php // app/config/config.php - $container->loadFromExtension('framework', array( + $container->loadFromExtension('framework', [ // ... - 'assets' => array( - 'base_urls' => array('http://cdn.example.com/'), - ), - )); + 'assets' => [ + 'base_urls' => ['http://cdn.example.com/'], + ], + ]); .. _reference-framework-assets-packages: @@ -1143,16 +1143,16 @@ You can group assets into packages, to specify different base URLs for them: .. code-block:: php // app/config/config.php - $container->loadFromExtension('framework', array( + $container->loadFromExtension('framework', [ // ... - 'assets' => array( - 'packages' => array( - 'avatars' => array( + 'assets' => [ + 'packages' => [ + 'avatars' => [ 'base_urls' => 'http://static_cdn.example.com/avatars', - ), - ), - ), - )); + ], + ], + ], + ]); Now you can use the ``avatars`` package in your templates: @@ -1220,12 +1220,12 @@ Now, activate the ``version`` option: .. code-block:: php // app/config/config.php - $container->loadFromExtension('framework', array( + $container->loadFromExtension('framework', [ // ... - 'assets' => array( + 'assets' => [ 'version' => 'v2', - ), - )); + ], + ]); Now, the same asset will be rendered as ``/images/logo.png?v2`` If you use this feature, you **must** manually increment the ``version`` value @@ -1347,25 +1347,25 @@ individually for each asset package: .. code-block:: php // app/config/config.php - $container->loadFromExtension('framework', array( - 'assets' => array( + $container->loadFromExtension('framework', [ + 'assets' => [ 'version_strategy' => 'app.asset.my_versioning_strategy', - 'packages' => array( - 'foo_package' => array( + 'packages' => [ + 'foo_package' => [ // this package removes any versioning (its assets won't be versioned) 'version' => null, - ), - 'bar_package' => array( + ], + 'bar_package' => [ // this package uses its own strategy (the default strategy is ignored) 'version_strategy' => 'app.asset.another_version_strategy', - ), - 'baz_package' => array( + ], + 'baz_package' => [ // this package inherits the default strategy 'base_path' => '/images', - ), - ), - ), - )); + ], + ], + ], + ]); .. note:: @@ -1443,22 +1443,22 @@ package: .. code-block:: php // app/config/config.php - $container->loadFromExtension('framework', array( - 'assets' => array( + $container->loadFromExtension('framework', [ + 'assets' => [ // this manifest is applied to every asset (including packages) 'json_manifest_path' => '%kernel.project_dir%/web/assets/manifest.json', - 'packages' => array( - 'foo_package' => array( + 'packages' => [ + 'foo_package' => [ // this package uses its own manifest (the default file is ignored) 'json_manifest_path' => '%kernel.project_dir%/web/assets/a_different_manifest.json', - ), - 'bar_package' => array( + ], + 'bar_package' => [ // this package uses the global manifest (the default file is used) 'base_path' => '/images', - ), - ), - ), - )); + ], + ], + ], + ]); .. note:: @@ -1543,15 +1543,15 @@ Assume you have custom global form themes in .. code-block:: php // app/config/config.php - $container->loadFromExtension('framework', array( - 'templating' => array( - 'form' => array( - 'resources' => array( + $container->loadFromExtension('framework', [ + 'templating' => [ + 'form' => [ + 'resources' => [ 'WebsiteBundle:Form', - ), - ), - ), - )); + ], + ], + ], + ]); .. note:: @@ -1614,7 +1614,7 @@ Whether or not to enable the ``translator`` service in the service container. fallbacks ......... -**type**: ``string|array`` **default**: ``array('en')`` +**type**: ``string|array`` **default**: ``['en']`` This option is used when the translation key for the current locale wasn't found. @@ -2041,16 +2041,16 @@ To configure a Redis cache pool with a default lifetime of 1 hour, do the follow .. code-block:: php // config/packages/framework.php - $container->loadFromExtension('framework', array( - 'cache' => array( - 'pools' => array( - 'cache.mycache' => array( + $container->loadFromExtension('framework', [ + 'cache' => [ + 'pools' => [ + 'cache.mycache' => [ 'adapter' => 'cache.adapter.redis', 'default_lifetime' => 3600, - ), - ), - ), - )); + ], + ], + ], + ]); .. _reference-cache-pools-name: diff --git a/reference/configuration/security.rst b/reference/configuration/security.rst index dd392160b41..2d91606214c 100644 --- a/reference/configuration/security.rst +++ b/reference/configuration/security.rst @@ -318,15 +318,15 @@ Using the BCrypt Password Encoder // app/config/security.php use Symfony\Component\Security\Core\User\User; - $container->loadFromExtension('security', array( + $container->loadFromExtension('security', [ // ... - 'encoders' => array( - User::class => array( + 'encoders' => [ + User::class => [ 'algorithm' => 'bcrypt', 'cost' => 15, - ), - ), - )); + ], + ], + ]); The ``cost`` can be in the range of ``4-31`` and determines how long a password will be encoded. Each increment of ``cost`` *doubles* the time it takes @@ -395,14 +395,14 @@ Using the Argon2i Password Encoder // app/config/security.php use Symfony\Component\Security\Core\User\User; - $container->loadFromExtension('security', array( + $container->loadFromExtension('security', [ // ... - 'encoders' => array( - User::class => array( + 'encoders' => [ + User::class => [ 'algorithm' => 'argon2i', - ), - ), - )); + ], + ], + ]); A salt for each new password is generated automatically and need not be persisted. Since an encoded password contains the salt used to encode it, @@ -468,18 +468,18 @@ multiple firewalls, the "context" could actually be shared: .. code-block:: php // app/config/security.php - $container->loadFromExtension('security', array( - 'firewalls' => array( - 'somename' => array( + $container->loadFromExtension('security', [ + 'firewalls' => [ + 'somename' => [ // ... 'context' => 'my_context', - ), - 'othername' => array( + ], + 'othername' => [ // ... 'context' => 'my_context', - ), - ), - )); + ], + ], + ]); .. note:: @@ -539,16 +539,16 @@ To use HTTP-Digest authentication you need to provide a realm and a secret: .. code-block:: php // app/config/security.php - $container->loadFromExtension('security', array( - 'firewalls' => array( - 'somename' => array( - 'http_digest' => array( + $container->loadFromExtension('security', [ + 'firewalls' => [ + 'somename' => [ + 'http_digest' => [ 'secret' => '%secret%', 'realm' => 'secure-api', - ), - ), - ), - )); + ], + ], + ], + ]); .. _`PBKDF2`: https://en.wikipedia.org/wiki/PBKDF2 .. _`ircmaxell/password-compat`: https://packagist.org/packages/ircmaxell/password-compat diff --git a/reference/configuration/swiftmailer.rst b/reference/configuration/swiftmailer.rst index fec0550b7c0..d22c7980094 100644 --- a/reference/configuration/swiftmailer.rst +++ b/reference/configuration/swiftmailer.rst @@ -295,17 +295,17 @@ key (the default mailer is identified by the ``default_mailer`` option): .. code-block:: php - $container->loadFromExtension('swiftmailer', array( + $container->loadFromExtension('swiftmailer', [ 'default_mailer' => 'second_mailer', - 'mailers' => array( - 'first_mailer' => array( + 'mailers' => [ + 'first_mailer' => [ // ... - ), - 'second_mailer' => array( + ], + 'second_mailer' => [ // ... - ), - ), - )); + ], + ], + ]); Each mailer is registered as a service:: diff --git a/reference/configuration/twig.rst b/reference/configuration/twig.rst index b36d0e7e2d2..9e0ff7658eb 100644 --- a/reference/configuration/twig.rst +++ b/reference/configuration/twig.rst @@ -302,12 +302,12 @@ The values of the ``paths`` option are defined as ``key: value`` pairs where the .. code-block:: php // app/config/config.php - $container->loadFromExtension('twig', array( + $container->loadFromExtension('twig', [ // ... - 'paths' => array( - '%kernel.project_dir%/vendor/acme/foo-bar/templates' => null, - ), - )); + 'paths' => [ + '%kernel.project_dir%/vendor/acme/foo-bar/templates' => null, + ], + ]); The directories defined in the ``paths`` option have more priority than the default directories defined by Symfony. In the above example, if the template @@ -346,12 +346,12 @@ for that directory: .. code-block:: php # app/config/config.php - $container->loadFromExtension('twig', array( + $container->loadFromExtension('twig', [ // ... - 'paths' => array( - '%kernel.project_dir%/vendor/acme/foo-bar/templates' => 'foo_bar', - ), - )); + 'paths' => [ + '%kernel.project_dir%/vendor/acme/foo-bar/templates' => 'foo_bar', + ], + ]); This option is useful to not mess with the default template directories defined by Symfony. Besides, it simplifies how you refer to those templates: diff --git a/reference/constraints/All.rst b/reference/constraints/All.rst index d3116fd4e51..6ace66df389 100644 --- a/reference/constraints/All.rst +++ b/reference/constraints/All.rst @@ -38,7 +38,7 @@ entry in that array: * @Assert\Length(min=5) * }) */ - protected $favoriteColors = array(); + protected $favoriteColors = []; } .. code-block:: yaml @@ -86,12 +86,12 @@ entry in that array: { public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addPropertyConstraint('favoriteColors', new Assert\All(array( - 'constraints' => array( + $metadata->addPropertyConstraint('favoriteColors', new Assert\All([ + 'constraints' => [ new Assert\NotBlank(), - new Assert\Length(array('min' => 5)), - ), - ))); + new Assert\Length(['min' => 5]), + ], + ])); } } diff --git a/reference/constraints/Callback.rst b/reference/constraints/Callback.rst index 34450676483..85c1ce4db30 100644 --- a/reference/constraints/Callback.rst +++ b/reference/constraints/Callback.rst @@ -106,7 +106,7 @@ field those errors should be attributed:: public function validate(ExecutionContextInterface $context, $payload) { // somehow you have an array of "fake names" - $fakeNames = array(/* ... */); + $fakeNames = [/* ... */]; // check if the name is actually a fake name if (in_array($this->getFirstName(), $fakeNames)) { @@ -126,7 +126,7 @@ have access to the object instance, they receive the object as the first argumen public static function validate($object, ExecutionContextInterface $context, $payload) { // somehow you have an array of "fake names" - $fakeNames = array(/* ... */); + $fakeNames = [/* ... */]; // check if the name is actually a fake name if (in_array($object->getFirstName(), $fakeNames)) { @@ -211,10 +211,10 @@ You can then use the following configuration to invoke this validator: { public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addConstraint(new Assert\Callback(array( + $metadata->addConstraint(new Assert\Callback([ Validator::class, 'validate', - ))); + ])); } } @@ -264,7 +264,7 @@ callback method: * A **string** containing the name of a concrete or static method; -* An array callable with the format ``array('', '')``; +* An array callable with the format ``['', '']``; * A closure. diff --git a/reference/constraints/CardScheme.rst b/reference/constraints/CardScheme.rst index 1b93186cf88..26784173e82 100644 --- a/reference/constraints/CardScheme.rst +++ b/reference/constraints/CardScheme.rst @@ -87,12 +87,12 @@ on an object that will contain a credit card number. public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addPropertyConstraint('cardNumber', new Assert\CardScheme(array( - 'schemes' => array( + $metadata->addPropertyConstraint('cardNumber', new Assert\CardScheme([ + 'schemes' => [ 'VISA', - ), + ], 'message' => 'Your credit card number is invalid.', - ))); + ])); } } diff --git a/reference/constraints/Choice.rst b/reference/constraints/Choice.rst index 89a67af8d3b..f671e7a36dd 100644 --- a/reference/constraints/Choice.rst +++ b/reference/constraints/Choice.rst @@ -113,13 +113,13 @@ If your valid choice list is simple, you can pass them in directly via the { $metadata->addPropertyConstraint( 'city', - new Assert\Choice(array('New York', 'Berlin', 'Tokyo')) - ); + new Assert\Choice(['New York', 'Berlin', 'Tokyo']) + ); - $metadata->addPropertyConstraint('genre', new Assert\Choice(array( - 'choices' => array('fiction', 'non-fiction'), + $metadata->addPropertyConstraint('genre', new Assert\Choice([ + 'choices' => ['fiction', 'non-fiction'], 'message' => 'Choose a valid genre.', - ))); + ])); } } @@ -138,7 +138,7 @@ form element:: { public static function getGenres() { - return array('fiction', 'non-fiction'); + return ['fiction', 'non-fiction']; } } @@ -205,9 +205,9 @@ constraint. public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addPropertyConstraint('genre', new Assert\Choice(array( + $metadata->addPropertyConstraint('genre', new Assert\Choice([ 'callback' => 'getGenres', - ))); + ])); } } @@ -274,9 +274,9 @@ you can pass the class name and the method as an array. public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addPropertyConstraint('genre', new Assert\Choice(array( - 'callback' => array(Genre::class, 'getGenres'), - ))); + $metadata->addPropertyConstraint('genre', new Assert\Choice([ + 'callback' => [Genre::class, 'getGenres'], + ])); } } diff --git a/reference/constraints/Collection.rst b/reference/constraints/Collection.rst index 629957312fa..19d8205a107 100644 --- a/reference/constraints/Collection.rst +++ b/reference/constraints/Collection.rst @@ -37,10 +37,10 @@ of a collection individually. Take the following example:: class Author { - protected $profileData = array( + protected $profileData = [ 'personal_email' => '...', 'short_bio' => '...', - ); + ]; public function setProfileData($key, $value) { @@ -79,10 +79,10 @@ following: * allowMissingFields = true * ) */ - protected $profileData = array( + protected $profileData = [ 'personal_email' => '...', 'short_bio' => '...', - ); + ]; } .. code-block:: yaml @@ -140,23 +140,23 @@ following: class Author { - private $options = array(); + private $options = []; public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addPropertyConstraint('profileData', new Assert\Collection(array( - 'fields' => array( + $metadata->addPropertyConstraint('profileData', new Assert\Collection([ + 'fields' => [ 'personal_email' => new Assert\Email(), - 'short_bio' => array( + 'short_bio' => [ new Assert\NotBlank(), - new Assert\Length(array( + new Assert\Length([ 'max' => 100, 'maxMessage' => 'Your short bio is too long!', - )), - ), - ), + ]), + ], + ], 'allowMissingFields' => true, - ))); + ])); } } @@ -207,7 +207,7 @@ you can do the following: * } * ) */ - protected $profileData = array('personal_email'); + protected $profileData = ['personal_email']; } .. code-block:: yaml @@ -265,18 +265,18 @@ you can do the following: class Author { - protected $profileData = array('personal_email'); + protected $profileData = ['personal_email']; public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addPropertyConstraint('profileData', new Assert\Collection(array( - 'fields' => array( + $metadata->addPropertyConstraint('profileData', new Assert\Collection([ + 'fields' => [ 'personal_email' => new Assert\Required( - array(new Assert\NotBlank(), new Assert\Email()) + [new Assert\NotBlank(), new Assert\Email()] ), 'alternate_email' => new Assert\Optional(new Assert\Email()), - ), - ))); + ], + ])); } } diff --git a/reference/constraints/Count.rst b/reference/constraints/Count.rst index f1e2a716935..caa9e2a4103 100644 --- a/reference/constraints/Count.rst +++ b/reference/constraints/Count.rst @@ -44,7 +44,7 @@ you might add the following: * maxMessage = "You cannot specify more than {{ limit }} emails" * ) */ - protected $emails = array(); + protected $emails = []; } .. code-block:: yaml @@ -91,12 +91,12 @@ you might add the following: { public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addPropertyConstraint('emails', new Assert\Count(array( + $metadata->addPropertyConstraint('emails', new Assert\Count([ 'min' => 1, 'max' => 5, 'minMessage' => 'You must specify at least one email', 'maxMessage' => 'You cannot specify more than {{ limit }} emails', - ))); + ])); } } diff --git a/reference/constraints/Email.rst b/reference/constraints/Email.rst index 66a7bac0814..bf54c0d4563 100644 --- a/reference/constraints/Email.rst +++ b/reference/constraints/Email.rst @@ -81,10 +81,10 @@ Basic Usage { public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addPropertyConstraint('email', new Assert\Email(array( + $metadata->addPropertyConstraint('email', new Assert\Email([ 'message' => 'The email "{{ value }}" is not a valid email.', 'checkMX' => true, - ))); + ])); } } diff --git a/reference/constraints/EqualTo.rst b/reference/constraints/EqualTo.rst index 71cf6c052d7..824c57811c1 100644 --- a/reference/constraints/EqualTo.rst +++ b/reference/constraints/EqualTo.rst @@ -100,9 +100,9 @@ and that the ``age`` is ``20``, you could do the following: { $metadata->addPropertyConstraint('firstName', new Assert\EqualTo('Mary')); - $metadata->addPropertyConstraint('age', new Assert\EqualTo(array( + $metadata->addPropertyConstraint('age', new Assert\EqualTo([ 'value' => 20, - ))); + ])); } } diff --git a/reference/constraints/Expression.rst b/reference/constraints/Expression.rst index 9e591090e92..3f105be7683 100644 --- a/reference/constraints/Expression.rst +++ b/reference/constraints/Expression.rst @@ -118,10 +118,10 @@ One way to accomplish this is with the Expression constraint: { public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addConstraint(new Assert\Expression(array( + $metadata->addConstraint(new Assert\Expression([ 'expression' => 'this.getCategory() in ["php", "symfony"] or !this.isTechnicalPost()', 'message' => 'If this is a tech post, the category should be either php or symfony!', - ))); + ])); } // ... @@ -207,10 +207,10 @@ more about the expression language syntax, see { public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addPropertyConstraint('isTechnicalPost', new Assert\Expression(array( + $metadata->addPropertyConstraint('isTechnicalPost', new Assert\Expression([ 'expression' => 'this.getCategory() in ["php", "symfony"] or value == false', 'message' => 'If this is a tech post, the category should be either php or symfony!', - ))); + ])); } // ... diff --git a/reference/constraints/File.rst b/reference/constraints/File.rst index fa81991621e..8d440e3fed2 100644 --- a/reference/constraints/File.rst +++ b/reference/constraints/File.rst @@ -140,14 +140,14 @@ below a certain file size and a valid PDF, add the following: { public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addPropertyConstraint('bioFile', new Assert\File(array( + $metadata->addPropertyConstraint('bioFile', new Assert\File([ 'maxSize' => '1024k', - 'mimeTypes' => array( + 'mimeTypes' => [ 'application/pdf', 'application/x-pdf', - ), + ], 'mimeTypesMessage' => 'Please upload a valid PDF', - ))); + ])); } } diff --git a/reference/constraints/GreaterThan.rst b/reference/constraints/GreaterThan.rst index 0778b77b49e..ed0d9eded18 100644 --- a/reference/constraints/GreaterThan.rst +++ b/reference/constraints/GreaterThan.rst @@ -99,9 +99,9 @@ The following constraints ensure that: { $metadata->addPropertyConstraint('siblings', new Assert\GreaterThan(5)); - $metadata->addPropertyConstraint('age', new Assert\GreaterThan(array( + $metadata->addPropertyConstraint('age', new Assert\GreaterThan([ 'value' => 18, - ))); + ])); } } diff --git a/reference/constraints/GreaterThanOrEqual.rst b/reference/constraints/GreaterThanOrEqual.rst index b789a67a78f..59c46801812 100644 --- a/reference/constraints/GreaterThanOrEqual.rst +++ b/reference/constraints/GreaterThanOrEqual.rst @@ -97,9 +97,9 @@ The following constraints ensure that: { $metadata->addPropertyConstraint('siblings', new Assert\GreaterThanOrEqual(5)); - $metadata->addPropertyConstraint('age', new Assert\GreaterThanOrEqual(array( + $metadata->addPropertyConstraint('age', new Assert\GreaterThanOrEqual([ 'value' => 18, - ))); + ])); } } diff --git a/reference/constraints/Iban.rst b/reference/constraints/Iban.rst index 84b25ee425a..b4877f6c19f 100644 --- a/reference/constraints/Iban.rst +++ b/reference/constraints/Iban.rst @@ -84,9 +84,9 @@ will contain an International Bank Account Number. public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addPropertyConstraint('bankAccountNumber', new Assert\Iban(array( + $metadata->addPropertyConstraint('bankAccountNumber', new Assert\Iban([ 'message' => 'This is not a valid International Bank Account Number (IBAN).', - ))); + ])); } } diff --git a/reference/constraints/IdenticalTo.rst b/reference/constraints/IdenticalTo.rst index 81d1aefcc65..3db2cd3b87c 100644 --- a/reference/constraints/IdenticalTo.rst +++ b/reference/constraints/IdenticalTo.rst @@ -103,9 +103,9 @@ The following constraints ensure that: { $metadata->addPropertyConstraint('firstName', new Assert\IdenticalTo('Mary')); - $metadata->addPropertyConstraint('age', new Assert\IdenticalTo(array( + $metadata->addPropertyConstraint('age', new Assert\IdenticalTo([ 'value' => 20, - ))); + ])); } } diff --git a/reference/constraints/Image.rst b/reference/constraints/Image.rst index e1d1b68b610..9691f59f19c 100644 --- a/reference/constraints/Image.rst +++ b/reference/constraints/Image.rst @@ -142,12 +142,12 @@ that it is between a certain size, add the following: { public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addPropertyConstraint('headshot', new Assert\Image(array( + $metadata->addPropertyConstraint('headshot', new Assert\Image([ 'minWidth' => 200, 'maxWidth' => 400, 'minHeight' => 200, 'maxHeight' => 400, - ))); + ])); } } @@ -214,10 +214,10 @@ following code: public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addPropertyConstraint('headshot', new Assert\Image(array( + $metadata->addPropertyConstraint('headshot', new Assert\Image([ 'allowLandscape' => false, 'allowPortrait' => false, - ))); + ])); } } diff --git a/reference/constraints/IsFalse.rst b/reference/constraints/IsFalse.rst index 093c7fd78df..9562911d2ce 100644 --- a/reference/constraints/IsFalse.rst +++ b/reference/constraints/IsFalse.rst @@ -28,7 +28,7 @@ you want to guarantee that some ``state`` property is *not* in a dynamic protected $state; - protected $invalidStates = array(); + protected $invalidStates = []; public function isStateInvalid() { diff --git a/reference/constraints/IsTrue.rst b/reference/constraints/IsTrue.rst index 14dc8a05105..7f05b98e66d 100644 --- a/reference/constraints/IsTrue.rst +++ b/reference/constraints/IsTrue.rst @@ -103,9 +103,9 @@ Then you can constrain this method with ``IsTrue``. public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addGetterConstraint('tokenValid', new IsTrue(array( + $metadata->addGetterConstraint('tokenValid', new IsTrue([ 'message' => 'The token is invalid.', - ))); + ])); } public function isTokenValid() diff --git a/reference/constraints/Isbn.rst b/reference/constraints/Isbn.rst index 95abc23e085..9522f209de5 100644 --- a/reference/constraints/Isbn.rst +++ b/reference/constraints/Isbn.rst @@ -87,10 +87,10 @@ on an object that will contain an ISBN. public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addPropertyConstraint('isbn', new Assert\Isbn(array( + $metadata->addPropertyConstraint('isbn', new Assert\Isbn([ 'type' => 'isbn10', 'message' => 'This value is not valid.', - ))); + ])); } } diff --git a/reference/constraints/Length.rst b/reference/constraints/Length.rst index 159e048e8ff..f1877ebf391 100644 --- a/reference/constraints/Length.rst +++ b/reference/constraints/Length.rst @@ -102,12 +102,12 @@ and "50", you might add the following: { public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addPropertyConstraint('firstName', new Assert\Length(array( + $metadata->addPropertyConstraint('firstName', new Assert\Length([ 'min' => 2, 'max' => 50, 'minMessage' => 'Your first name must be at least {{ limit }} characters long', 'maxMessage' => 'Your first name cannot be longer than {{ limit }} characters', - ))); + ])); } } diff --git a/reference/constraints/LessThan.rst b/reference/constraints/LessThan.rst index cce8f46e2f2..08f991c2423 100644 --- a/reference/constraints/LessThan.rst +++ b/reference/constraints/LessThan.rst @@ -99,9 +99,9 @@ The following constraints ensure that: { $metadata->addPropertyConstraint('siblings', new Assert\LessThan(5)); - $metadata->addPropertyConstraint('age', new Assert\LessThan(array( + $metadata->addPropertyConstraint('age', new Assert\LessThan([ 'value' => 80, - ))); + ])); } } diff --git a/reference/constraints/LessThanOrEqual.rst b/reference/constraints/LessThanOrEqual.rst index 0d09f90289c..ad0dc025df6 100644 --- a/reference/constraints/LessThanOrEqual.rst +++ b/reference/constraints/LessThanOrEqual.rst @@ -97,9 +97,9 @@ The following constraints ensure that: { $metadata->addPropertyConstraint('siblings', new Assert\LessThanOrEqual(5)); - $metadata->addPropertyConstraint('age', new Assert\LessThanOrEqual(array( + $metadata->addPropertyConstraint('age', new Assert\LessThanOrEqual([ 'value' => 80, - ))); + ])); } } diff --git a/reference/constraints/Luhn.rst b/reference/constraints/Luhn.rst index 78e73f29926..d89c2cc7b58 100644 --- a/reference/constraints/Luhn.rst +++ b/reference/constraints/Luhn.rst @@ -79,9 +79,9 @@ will contain a credit card number. public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addPropertyConstraint('cardNumber', new Assert\Luhn(array( + $metadata->addPropertyConstraint('cardNumber', new Assert\Luhn([ 'message' => 'Please check your credit card number', - ))); + ])); } } diff --git a/reference/constraints/NotEqualTo.rst b/reference/constraints/NotEqualTo.rst index 499ca0e1e8c..7a2d88cdfa7 100644 --- a/reference/constraints/NotEqualTo.rst +++ b/reference/constraints/NotEqualTo.rst @@ -102,9 +102,9 @@ the following: { $metadata->addPropertyConstraint('firstName', new Assert\NotEqualTo('Mary')); - $metadata->addPropertyConstraint('age', new Assert\NotEqualTo(array( + $metadata->addPropertyConstraint('age', new Assert\NotEqualTo([ 'value' => 15, - ))); + ])); } } diff --git a/reference/constraints/NotIdenticalTo.rst b/reference/constraints/NotIdenticalTo.rst index b87d9aca433..bbac8b1b1d8 100644 --- a/reference/constraints/NotIdenticalTo.rst +++ b/reference/constraints/NotIdenticalTo.rst @@ -103,9 +103,9 @@ The following constraints ensure that: { $metadata->addPropertyConstraint('age', new Assert\NotIdenticalTo('Mary')); - $metadata->addPropertyConstraint('age', new Assert\NotIdenticalTo(array( + $metadata->addPropertyConstraint('age', new Assert\NotIdenticalTo([ 'value' => 15, - ))); + ])); } } diff --git a/reference/constraints/Range.rst b/reference/constraints/Range.rst index 9ef728ec8fa..b854af61e46 100644 --- a/reference/constraints/Range.rst +++ b/reference/constraints/Range.rst @@ -90,12 +90,12 @@ you might add the following: { public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addPropertyConstraint('height', new Assert\Range(array( + $metadata->addPropertyConstraint('height', new Assert\Range([ 'min' => 120, 'max' => 180, 'minMessage' => 'You must be at least {{ limit }}cm tall to enter', 'maxMessage' => 'You cannot be taller than {{ limit }}cm to enter', - ))); + ])); } } @@ -167,10 +167,10 @@ date must lie within the current year like this: { public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addPropertyConstraint('startDate', new Assert\Range(array( + $metadata->addPropertyConstraint('startDate', new Assert\Range([ 'min' => 'first day of January', 'max' => 'first day of January next year', - ))); + ])); } } @@ -237,10 +237,10 @@ dates. If you want to fix the timezone, append it to the date string: { public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addPropertyConstraint('startDate', new Assert\Range(array( + $metadata->addPropertyConstraint('startDate', new Assert\Range([ 'min' => 'first day of January UTC', 'max' => 'first day of January next year UTC', - ))); + ])); } } @@ -307,10 +307,10 @@ can check that a delivery date starts within the next five hours like this: { public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addPropertyConstraint('deliveryDate', new Assert\Range(array( + $metadata->addPropertyConstraint('deliveryDate', new Assert\Range([ 'min' => 'now', 'max' => '+5 hours', - ))); + ])); } } diff --git a/reference/constraints/Regex.rst b/reference/constraints/Regex.rst index ee4f114b077..a8ff93bfe4b 100644 --- a/reference/constraints/Regex.rst +++ b/reference/constraints/Regex.rst @@ -79,9 +79,9 @@ more word characters at the beginning of your string: { public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addPropertyConstraint('description', new Assert\Regex(array( + $metadata->addPropertyConstraint('description', new Assert\Regex([ 'pattern' => '/^\w+/', - ))); + ])); } } @@ -153,11 +153,11 @@ it a custom message: { public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addPropertyConstraint('firstName', new Assert\Regex(array( + $metadata->addPropertyConstraint('firstName', new Assert\Regex([ 'pattern' => '/\d/', 'match' => false, 'message' => 'Your name cannot contain a number', - ))); + ])); } } @@ -253,10 +253,10 @@ need to specify the HTML5 compatible pattern in the ``htmlPattern`` option: { public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addPropertyConstraint('name', new Assert\Regex(array( + $metadata->addPropertyConstraint('name', new Assert\Regex([ 'pattern' => '/^[a-z]+$/i', 'htmlPattern' => '^[a-zA-Z]+$', - ))); + ])); } } diff --git a/reference/constraints/Type.rst b/reference/constraints/Type.rst index 5a4ec564c32..16bc72bcbc8 100644 --- a/reference/constraints/Type.rst +++ b/reference/constraints/Type.rst @@ -98,10 +98,10 @@ This will check if ``firstName`` is of type ``string`` and that ``age`` is an { $metadata->addPropertyConstraint('firstName', new Assert\Type('string')); - $metadata->addPropertyConstraint('age', new Assert\Type(array( + $metadata->addPropertyConstraint('age', new Assert\Type([ 'type' => 'integer', 'message' => 'The value {{ value }} is not a valid {{ type }}.', - ))); + ])); } } diff --git a/reference/constraints/UniqueEntity.rst b/reference/constraints/UniqueEntity.rst index 7098fcb75bf..8b1697b07d5 100644 --- a/reference/constraints/UniqueEntity.rst +++ b/reference/constraints/UniqueEntity.rst @@ -102,9 +102,9 @@ your user table: { public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addConstraint(new UniqueEntity(array( + $metadata->addConstraint(new UniqueEntity([ 'fields' => 'email', - ))); + ])); $metadata->addPropertyConstraint('email', new Assert\Email()); } @@ -279,11 +279,11 @@ Consider this example: public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addConstraint(new UniqueEntity(array( - 'fields' => array('host', 'port'), + $metadata->addConstraint(new UniqueEntity([ + 'fields' => ['host', 'port'], 'errorPath' => 'port', 'message' => 'This port is already in use on that host.', - ))); + ])); } } diff --git a/reference/constraints/Url.rst b/reference/constraints/Url.rst index 39aa005a0eb..b3fecab262f 100644 --- a/reference/constraints/Url.rst +++ b/reference/constraints/Url.rst @@ -153,16 +153,16 @@ You can use the following parameters in this message: { public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addPropertyConstraint('bioUrl', new Assert\Url(array( + $metadata->addPropertyConstraint('bioUrl', new Assert\Url([ 'message' => 'The url "{{ value }}" is not a valid url.', - ))); + ])); } } protocols ~~~~~~~~~ -**type**: ``array`` **default**: ``array('http', 'https')`` +**type**: ``array`` **default**: ``['http', 'https']`` The protocols considered to be valid for the URL. For example, if you also consider the ``ftp://`` type URLs to be valid, redefine the ``protocols`` array, listing @@ -228,9 +228,9 @@ the ``ftp://`` type URLs to be valid, redefine the ``protocols`` array, listing { public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addPropertyConstraint('bioUrl', new Assert\Url(array( - 'protocols' => array('http', 'https', 'ftp'), - ))); + $metadata->addPropertyConstraint('bioUrl', new Assert\Url([ + 'protocols' => ['http', 'https', 'ftp'], + ])); } } @@ -302,9 +302,9 @@ option to the value of any of the ``CHECK_DNS_TYPE_*`` constants in the { public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addPropertyConstraint('bioUrl', new Assert\Url(array( + $metadata->addPropertyConstraint('bioUrl', new Assert\Url([ 'checkDNS' => Assert\Url::CHECK_DNS_TYPE_ANY, - ))); + ])); } } @@ -375,8 +375,8 @@ DNS check failed. { public static function loadValidatorMetadata(ClassMetadata $metadata) { - $metadata->addPropertyConstraint('bioUrl', new Assert\Url(array( + $metadata->addPropertyConstraint('bioUrl', new Assert\Url([ 'dnsMessage' => 'The host "{{ value }}" could not be resolved.', - ))); + ])); } } diff --git a/reference/constraints/UserPassword.rst b/reference/constraints/UserPassword.rst index 560a3f51bb8..6140cfdbc91 100644 --- a/reference/constraints/UserPassword.rst +++ b/reference/constraints/UserPassword.rst @@ -90,9 +90,9 @@ the user's current password: { $metadata->addPropertyConstraint( 'oldPassword', - new SecurityAssert\UserPassword(array( + new SecurityAssert\UserPassword([ 'message' => 'Wrong value for your current password', - )) + ]) ); } } diff --git a/reference/constraints/Valid.rst b/reference/constraints/Valid.rst index 990b07050c5..72c4fb55792 100644 --- a/reference/constraints/Valid.rst +++ b/reference/constraints/Valid.rst @@ -159,7 +159,7 @@ stores an ``Address`` instance in the ``$address`` property:: { $metadata->addPropertyConstraint('street', new Assert\NotBlank()); $metadata->addPropertyConstraint('zipCode', new Assert\NotBlank()); - $metadata->addPropertyConstraint('zipCode', new Assert\Length(array("max" => 5))); + $metadata->addPropertyConstraint('zipCode', new Assert\Length(["max" => 5])); } } @@ -178,7 +178,7 @@ stores an ``Address`` instance in the ``$address`` property:: public static function loadValidatorMetadata(ClassMetadata $metadata) { $metadata->addPropertyConstraint('firstName', new Assert\NotBlank()); - $metadata->addPropertyConstraint('firstName', new Assert\Length(array("min" => 4))); + $metadata->addPropertyConstraint('firstName', new Assert\Length(["min" => 4])); $metadata->addPropertyConstraint('lastName', new Assert\NotBlank()); } } diff --git a/reference/dic_tags.rst b/reference/dic_tags.rst index e34d682288f..082d7d4967f 100644 --- a/reference/dic_tags.rst +++ b/reference/dic_tags.rst @@ -172,7 +172,7 @@ Second, define a service: $container ->register(CustomFilter::class) - ->addTag('assetic.filter', array('alias' => 'my_filter')) + ->addTag('assetic.filter', ['alias' => 'my_filter']) ; Finally, apply the filter: @@ -335,7 +335,7 @@ the generic ``app.lock`` service can be defined as follows: $container->register('app.sqlite_lock', SqliteLock::class)->setPublic(false); $container->register('app.lock') - ->addTag('auto_alias', array('format' => 'app.%database_type%_lock')); + ->addTag('auto_alias', ['format' => 'app.%database_type%_lock']); The ``format`` option defines the expression used to construct the name of the service to alias. This expression can use any container parameter (as usual, @@ -566,7 +566,7 @@ can also register it manually: $container ->register(MyCustomWarmer::class) - ->addTag('kernel.cache_warmer', array('priority' => 0)) + ->addTag('kernel.cache_warmer', ['priority' => 0]) ; .. note:: @@ -676,7 +676,7 @@ channel when injecting the logger in a service. $container->register(CustomLogger::class) ->addArgument(new Reference('logger')) - ->addTag('monolog.logger', array('channel' => 'app')); + ->addTag('monolog.logger', ['channel' => 'app']); .. tip:: @@ -771,7 +771,7 @@ attribute: $container ->register(IntrospectionProcessor::class) - ->addTag('monolog.processor', array('handler' => 'firephp')) + ->addTag('monolog.processor', ['handler' => 'firephp']) ; You can also add a processor for a specific logging channel by using the @@ -808,7 +808,7 @@ You can also add a processor for a specific logging channel by using the $container ->register(IntrospectionProcessor::class) - ->addTag('monolog.processor', array('channel' => 'security')) + ->addTag('monolog.processor', ['channel' => 'security']) ; .. note:: @@ -994,7 +994,7 @@ templates): use AppBundle\Templating\AppHelper; $container->register(AppHelper::class) - ->addTag('templating.helper', array('alias' => 'alias_name')) + ->addTag('templating.helper', ['alias' => 'alias_name']) ; .. _dic-tags-translation-loader: @@ -1044,7 +1044,7 @@ Now, register your loader as a service and tag it with ``translation.loader``: $container ->register(MyCustomLoader::class) - ->addTag('translation.loader', array('alias' => 'bin')) + ->addTag('translation.loader', ['alias' => 'bin']) ; The ``alias`` option is required and very important: it defines the file @@ -1138,7 +1138,7 @@ required option: ``alias``, which defines the name of the extractor:: use AppBundle\Translation\CustomExtractor; $container->register(CustomExtractor::class) - ->addTag('translation.extractor', array('alias' => 'foo')); + ->addTag('translation.extractor', ['alias' => 'foo']); translation.dumper ------------------ @@ -1195,7 +1195,7 @@ This is the name that's used to determine which dumper should be used. use AppBundle\Translation\JsonFileDumper; $container->register(JsonFileDumper::class) - ->addTag('translation.dumper', array('alias' => 'json')); + ->addTag('translation.dumper', ['alias' => 'json']); .. seealso:: @@ -1330,7 +1330,7 @@ also register it manually: $container ->register(CustomLoader::class) - ->addTag('twig.loader', array('priority' => 0)) + ->addTag('twig.loader', ['priority' => 0]) ; .. note:: diff --git a/reference/forms/types/birthday.rst b/reference/forms/types/birthday.rst index 056fe21ad3e..04f78c8b88b 100644 --- a/reference/forms/types/birthday.rst +++ b/reference/forms/types/birthday.rst @@ -77,18 +77,18 @@ If your widget option is set to ``choice``, then this field will be represented as a series of ``select`` boxes. When the placeholder value is a string, it will be used as the **blank value** of all select boxes:: - $builder->add('birthdate', BirthdayType::class, array( + $builder->add('birthdate', BirthdayType::class, [ 'placeholder' => 'Select a value', - )); + ]); Alternatively, you can use an array that configures different placeholder values for the year, month and day fields:: - $builder->add('birthdate', BirthdayType::class, array( - 'placeholder' => array( + $builder->add('birthdate', BirthdayType::class, [ + 'placeholder' => [ 'year' => 'Year', 'month' => 'Month', 'day' => 'Day', - ) - )); + ] + ]); .. include:: /reference/forms/types/options/date_format.rst.inc diff --git a/reference/forms/types/button.rst b/reference/forms/types/button.rst index f7586fc7f33..62e76989a80 100644 --- a/reference/forms/types/button.rst +++ b/reference/forms/types/button.rst @@ -31,7 +31,7 @@ of the form type tree (i.e. it cannot be used as a form type on its own). attr ~~~~ -**type**: ``array`` **default**: ``array()`` +**type**: ``array`` **default**: ``[]`` If you want to add extra attributes to the HTML representation of the button, you can use ``attr`` option. It's an associative array with HTML attribute @@ -40,9 +40,9 @@ as a key. This can be useful when you need to set a custom class for the button: use Symfony\Component\Form\Extension\Core\Type\ButtonType; // ... - $builder->add('save', ButtonType::class, array( - 'attr' => array('class' => 'save'), - )); + $builder->add('save', ButtonType::class, [ + 'attr' => ['class' => 'save'], + ]); .. include:: /reference/forms/types/options/button_disabled.rst.inc diff --git a/reference/forms/types/checkbox.rst b/reference/forms/types/checkbox.rst index 8f87683f180..fc180ec9175 100644 --- a/reference/forms/types/checkbox.rst +++ b/reference/forms/types/checkbox.rst @@ -39,10 +39,10 @@ Example Usage use Symfony\Component\Form\Extension\Core\Type\CheckboxType; // ... - $builder->add('public', CheckboxType::class, array( + $builder->add('public', CheckboxType::class, [ 'label' => 'Show this entry publicly?', 'required' => false, - )); + ]); Field Options ------------- diff --git a/reference/forms/types/choice.rst b/reference/forms/types/choice.rst index 032d7425572..b26b6b1ab52 100644 --- a/reference/forms/types/choice.rst +++ b/reference/forms/types/choice.rst @@ -58,13 +58,13 @@ the ``choices`` option:: use Symfony\Component\Form\Extension\Core\Type\ChoiceType; // ... - $builder->add('isAttending', ChoiceType::class, array( - 'choices' => array( + $builder->add('isAttending', ChoiceType::class, [ + 'choices' => [ 'Maybe' => null, 'Yes' => true, 'No' => false, - ), - )); + ], + ]); This will create a ``select`` drop-down like this: @@ -135,18 +135,18 @@ by passing a multi-dimensional ``choices`` array:: use Symfony\Component\Form\Extension\Core\Type\ChoiceType; // ... - $builder->add('stockStatus', ChoiceType::class, array( - 'choices' => array( - 'Main Statuses' => array( + $builder->add('stockStatus', ChoiceType::class, [ + 'choices' => [ + 'Main Statuses' => [ 'Yes' => 'stock_yes', 'No' => 'stock_no', - ), - 'Out of Stock Statuses' => array( + ], + 'Out of Stock Statuses' => [ 'Backordered' => 'stock_backordered', 'Discontinued' => 'stock_discontinued', - ), - ), - )); + ], + ], + ]); .. image:: /_images/reference/form/choice-example4.png :align: center @@ -159,7 +159,7 @@ Field Options choices ~~~~~~~ -**type**: ``array`` **default**: ``array()`` +**type**: ``array`` **default**: ``[]`` This is the most basic way to specify the choices that should be used by this field. The ``choices`` option is an array, where the array key @@ -168,9 +168,9 @@ is the item's label and the array value is the item's value:: use Symfony\Component\Form\Extension\Core\Type\ChoiceType; // ... - $builder->add('inStock', ChoiceType::class, array( - 'choices' => array('In Stock' => true, 'Out of Stock' => false), - )); + $builder->add('inStock', ChoiceType::class, [ + 'choices' => ['In Stock' => true, 'Out of Stock' => false], + ]); If there are choice values that are not scalar or the stringified representation is not unique Symfony will use incrementing integers @@ -204,11 +204,11 @@ if you want to take advantage of lazy loading:: use Symfony\Component\Form\Extension\Core\Type\ChoiceType; // ... - $builder->add('constants', ChoiceType::class, array( + $builder->add('constants', ChoiceType::class, [ 'choice_loader' => new CallbackChoiceLoader(function() { return StaticClass::getConstants(); }), - )); + ]); This will cause the call of ``StaticClass::getConstants()`` to not happen if the request is redirected and if there is no pre set or submitted data. Otherwise @@ -254,7 +254,7 @@ The actual default value of this option depends on other field options: * If ``multiple`` is ``false`` and ``expanded`` is ``false``, then ``''`` (empty string); -* Otherwise ``array()`` (empty array). +* Otherwise ``[]`` (empty array). .. include:: /reference/forms/types/options/empty_data.rst.inc :start-after: DEFAULT_PLACEHOLDER diff --git a/reference/forms/types/collection.rst b/reference/forms/types/collection.rst index 51d2357486f..71865153f57 100644 --- a/reference/forms/types/collection.rst +++ b/reference/forms/types/collection.rst @@ -57,14 +57,14 @@ address as its own input text box:: use Symfony\Component\Form\Extension\Core\Type\EmailType; // ... - $builder->add('emails', CollectionType::class, array( + $builder->add('emails', CollectionType::class, [ // each entry in the array will be an "email" field 'entry_type' => EmailType::class, // these options are passed to each "email" type - 'entry_options' => array( - 'attr' => array('class' => 'email-box'), - ), - )); + 'entry_options' => [ + 'attr' => ['class' => 'email-box'], + ], + ]); The simplest way to render this is all at once: @@ -278,12 +278,12 @@ the value is removed from the collection. For example:: use Symfony\Component\Form\Extension\Core\Type\CollectionType; // ... - $builder->add('users', CollectionType::class, array( + $builder->add('users', CollectionType::class, [ // ... 'delete_empty' => function (User $user = null) { return null === $user || empty($user->getFirstName()); }, - )); + ]); Using a callable is particularly useful in case of compound form types, which may define complex conditions for considering them empty. @@ -296,7 +296,7 @@ may define complex conditions for considering them empty. entry_options ~~~~~~~~~~~~~ -**type**: ``array`` **default**: ``array()`` +**type**: ``array`` **default**: ``[]`` This is the array that's passed to the form type specified in the `entry_type`_ option. For example, if you used the :doc:`ChoiceType ` @@ -308,17 +308,17 @@ type:: use Symfony\Component\Form\Extension\Core\Type\ChoiceType; // ... - $builder->add('favorite_cities', CollectionType::class, array( + $builder->add('favorite_cities', CollectionType::class, [ 'entry_type' => ChoiceType::class, - 'entry_options' => array( - 'choices' => array( + 'entry_options' => [ + 'choices' => [ 'Nashville' => 'nashville', 'Paris' => 'paris', 'Berlin' => 'berlin', 'London' => 'london', - ), - ), - )); + ], + ], + ]); entry_type ~~~~~~~~~~ @@ -379,12 +379,12 @@ for all entries with the `entry_options`_ option will be used. use Symfony\Component\Form\Extension\Core\Type\TextType; // ... - $builder->add('tags', CollectionType::class, array( + $builder->add('tags', CollectionType::class, [ 'entry_type' => TextType::class, 'allow_add' => true, 'prototype' => true, 'prototype_data' => 'New Tag Placeholder', - )); + ]); prototype_name ~~~~~~~~~~~~~~ @@ -408,7 +408,7 @@ Not all options are listed here - only the most applicable to this type: .. include:: /reference/forms/types/options/empty_data.rst.inc :end-before: DEFAULT_PLACEHOLDER -The default value is ``array()`` (empty array). +The default value is ``[]`` (empty array). .. include:: /reference/forms/types/options/empty_data.rst.inc :start-after: DEFAULT_PLACEHOLDER diff --git a/reference/forms/types/country.rst b/reference/forms/types/country.rst index cb4a11afabc..85c07cb27c7 100644 --- a/reference/forms/types/country.rst +++ b/reference/forms/types/country.rst @@ -99,7 +99,7 @@ The actual default value of this option depends on other field options: * If ``multiple`` is ``false`` and ``expanded`` is ``false``, then ``''`` (empty string); -* Otherwise ``array()`` (empty array). +* Otherwise ``[]`` (empty array). .. include:: /reference/forms/types/options/empty_data.rst.inc :start-after: DEFAULT_PLACEHOLDER diff --git a/reference/forms/types/currency.rst b/reference/forms/types/currency.rst index bbe9a4fb01c..249003551d6 100644 --- a/reference/forms/types/currency.rst +++ b/reference/forms/types/currency.rst @@ -88,7 +88,7 @@ The actual default value of this option depends on other field options: * If ``multiple`` is ``false`` and ``expanded`` is ``false``, then ``''`` (empty string); -* Otherwise ``array()`` (empty array). +* Otherwise ``[]`` (empty array). .. include:: /reference/forms/types/options/empty_data.rst.inc :start-after: DEFAULT_PLACEHOLDER diff --git a/reference/forms/types/date.rst b/reference/forms/types/date.rst index feca602bac1..373c5e7b7b6 100644 --- a/reference/forms/types/date.rst +++ b/reference/forms/types/date.rst @@ -58,9 +58,9 @@ field as **three different choice fields**:: use Symfony\Component\Form\Extension\Core\Type\DateType; // ... - $builder->add('publishedAt', DateType::class, array( + $builder->add('publishedAt', DateType::class, [ 'widget' => 'choice', - )); + ]); If your underlying date is *not* a ``DateTime`` object (e.g. it's a unix timestamp), configure the `input`_ option. @@ -75,10 +75,10 @@ use the ``single_text`` widget:: use Symfony\Component\Form\Extension\Core\Type\DateType; // ... - $builder->add('publishedAt', DateType::class, array( + $builder->add('publishedAt', DateType::class, [ // renders it as a single text box 'widget' => 'single_text', - )); + ]); This will render as an ``input type="date"`` HTML5 field, which means that **some - but not all - browsers will add nice date picker functionality to the field**. If you @@ -91,7 +91,7 @@ make the following changes:: use Symfony\Component\Form\Extension\Core\Type\DateType; // ... - $builder->add('publishedAt', DateType::class, array( + $builder->add('publishedAt', DateType::class, [ 'widget' => 'single_text', // prevents rendering it as type="date", to avoid HTML5 date pickers @@ -99,7 +99,7 @@ make the following changes:: // adds a class that can be selected in JavaScript 'attr' => ['class' => 'js-datepicker'], - )); + ]); Then, add the following JavaScript code in your template to initialize the date picker: @@ -143,18 +143,18 @@ If your widget option is set to ``choice``, then this field will be represented as a series of ``select`` boxes. When the placeholder value is a string, it will be used as the **blank value** of all select boxes:: - $builder->add('dueDate', DateType::class, array( + $builder->add('dueDate', DateType::class, [ 'placeholder' => 'Select a value', - )); + ]); Alternatively, you can use an array that configures different placeholder values for the year, month and day fields:: - $builder->add('dueDate', DateType::class, array( - 'placeholder' => array( + $builder->add('dueDate', DateType::class, [ + 'placeholder' => [ 'year' => 'Year', 'month' => 'Month', 'day' => 'Day', - ) - )); + ] + ]); .. _reference-forms-type-date-format: diff --git a/reference/forms/types/dateinterval.rst b/reference/forms/types/dateinterval.rst index 89602f24796..d37874e8f43 100644 --- a/reference/forms/types/dateinterval.rst +++ b/reference/forms/types/dateinterval.rst @@ -62,7 +62,7 @@ options are `input`_ and `widget`_. You can configure *a lot* of different options, including exactly *which* range options to show (e.g. don't show "months", but *do* show "days"):: - $builder->add('remindEvery', DateIntervalType::class, array( + $builder->add('remindEvery', DateIntervalType::class, [ 'widget' => 'integer', // render a text field for each part // 'input' => 'string', // if you want the field to return a ISO 8601 string back to you @@ -71,7 +71,7 @@ options to show (e.g. don't show "months", but *do* show "days"):: 'with_months' => false, 'with_days' => true, 'with_hours' => true, - )); + ]); Field Options ------------- @@ -95,15 +95,15 @@ If your widget option is set to ``choice``, then this field will be represented as a series of ``select`` boxes. The ``placeholder`` option can be used to add a "blank" entry to the top of each select box:: - $builder->add('remindEvery', DateIntervalType::class, array( + $builder->add('remindEvery', DateIntervalType::class, [ 'placeholder' => '', - )); + ]); Alternatively, you can specify a string to be displayed for the "blank" value:: - $builder->add('remindEvery', DateIntervalType::class, array( - 'placeholder' => array('years' => 'Years', 'months' => 'Months', 'days' => 'Days') - )); + $builder->add('remindEvery', DateIntervalType::class, [ + 'placeholder' => ['years' => 'Years', 'months' => 'Months', 'days' => 'Days'] + ]); hours ~~~~~ @@ -125,7 +125,7 @@ your underlying object. Valid values are: * ``string`` (a string formatted with `ISO 8601`_ standard, e.g. ``P7Y6M5DT12H15M30S``) * ``dateinterval`` (a ``DateInterval`` object) -* ``array`` (e.g. ``array('days' => '1', 'hours' => '12',)``) +* ``array`` (e.g. ``['days' => '1', 'hours' => '12',]``) The value that comes back from the form will also be normalized back into this format. @@ -143,7 +143,7 @@ The labels displayed for each of the elements of this type. The default values are ``null``, so they display the "humanized version" of the child names (``Invert``, ``Years``, etc.):: - 'labels' => array( + 'labels' => [ 'invert' => null, 'years' => null, 'months' => null, @@ -151,7 +151,7 @@ are ``null``, so they display the "humanized version" of the child names (``Inve 'hours' => null, 'minutes' => null, 'seconds' => null, - ) + ] minutes ~~~~~~~ diff --git a/reference/forms/types/datetime.rst b/reference/forms/types/datetime.rst index 2ba9eba96e9..3d400ba66cb 100644 --- a/reference/forms/types/datetime.rst +++ b/reference/forms/types/datetime.rst @@ -84,21 +84,21 @@ it will be used as the **blank value** of all select boxes:: use Symfony\Component\Form\Extension\Core\Type\DateTimeType; - $builder->add('startDateTime', DateTimeType::class, array( + $builder->add('startDateTime', DateTimeType::class, [ 'placeholder' => 'Select a value', - )); + ]); Alternatively, you can use an array that configures different placeholder values for the year, month, day, hour, minute and second fields:: use Symfony\Component\Form\Extension\Core\Type\DateTimeType; - $builder->add('startDateTime', DateTimeType::class, array( - 'placeholder' => array( + $builder->add('startDateTime', DateTimeType::class, [ + 'placeholder' => [ 'year' => 'Year', 'month' => 'Month', 'day' => 'Day', 'hour' => 'Hour', 'minute' => 'Minute', 'second' => 'Second', - ) - )); + ] + ]); format ~~~~~~ @@ -126,7 +126,7 @@ on your underlying object. Valid values are: * ``string`` (e.g. ``2011-06-05 12:15:00``) * ``datetime`` (a ``DateTime`` object) -* ``array`` (e.g. ``array(2011, 06, 05, 12, 15, 0)``) +* ``array`` (e.g. ``[2011, 06, 05, 12, 15, 0]``) * ``timestamp`` (e.g. ``1307276100``) The value that comes back from the form will also be normalized back into diff --git a/reference/forms/types/entity.rst b/reference/forms/types/entity.rst index 95c7f287a2a..20c33be7af2 100644 --- a/reference/forms/types/entity.rst +++ b/reference/forms/types/entity.rst @@ -61,7 +61,7 @@ be listed inside the choice field:: use Symfony\Bridge\Doctrine\Form\Type\EntityType; // ... - $builder->add('users', EntityType::class, array( + $builder->add('users', EntityType::class, [ // looks for choices from this entity 'class' => 'AppBundle:User', @@ -71,7 +71,7 @@ be listed inside the choice field:: // used to render a select box, check boxes or radios // 'multiple' => true, // 'expanded' => true, - )); + ]); This will build a ``select`` drop-down containing *all* of the ``User`` objects in the database. To render radio buttons or checkboxes instead, change the @@ -90,14 +90,14 @@ the `query_builder`_ option:: use Symfony\Bridge\Doctrine\Form\Type\EntityType; // ... - $builder->add('users', EntityType::class, array( + $builder->add('users', EntityType::class, [ 'class' => 'AppBundle:User', 'query_builder' => function (EntityRepository $er) { return $er->createQueryBuilder('u') ->orderBy('u.username', 'ASC'); }, 'choice_label' => 'username', - )); + ]); .. _reference-forms-entity-choices: @@ -114,10 +114,10 @@ then you can supply the ``choices`` option directly:: use Symfony\Bridge\Doctrine\Form\Type\EntityType; // ... - $builder->add('users', EntityType::class, array( + $builder->add('users', EntityType::class, [ 'class' => 'AppBundle:User', 'choices' => $group->getUsers(), - )); + ]); .. include:: /reference/forms/types/options/select_how_rendered.rst.inc @@ -135,10 +135,10 @@ the HTML element:: use Symfony\Bridge\Doctrine\Form\Type\EntityType; // ... - $builder->add('category', EntityType::class, array( + $builder->add('category', EntityType::class, [ 'class' => 'AppBundle:Category', 'choice_label' => 'displayName', - )); + ]); If left blank, the entity object will be cast to a string and so must have a ``__toString()`` method. You can also pass a callback function for more control:: @@ -146,12 +146,12 @@ method. You can also pass a callback function for more control:: use Symfony\Bridge\Doctrine\Form\Type\EntityType; // ... - $builder->add('category', EntityType::class, array( + $builder->add('category', EntityType::class, [ 'class' => 'AppBundle:Category', 'choice_label' => function ($category) { return $category->getDisplayName(); } - )); + ]); The method is called for each entity in the list and passed to the function. For more details, see the main :ref:`choice_label ` documentation. @@ -168,10 +168,10 @@ more details, see the main :ref:`choice_label ` doc use Symfony\Bridge\Doctrine\Form\Type\EntityType; // ... - $builder->add('genre', EntityType::class, array( + $builder->add('genre', EntityType::class, [ 'class' => 'MyBundle:Genre', 'choice_label' => 'translations[en].name', - )); + ]); class ~~~~~ @@ -270,7 +270,7 @@ These options inherit from the :doc:`ChoiceType ` preferred_choices ~~~~~~~~~~~~~~~~~ -**type**: ``array`` or ``callable`` **default**: ``array()`` +**type**: ``array`` or ``callable`` **default**: ``[]`` This option allows you to move certain choices to the top of your list with a visual separator between them and the rest of the options. This option expects an array @@ -280,11 +280,11 @@ of entity objects:: use Symfony\Bridge\Doctrine\Form\Type\EntityType; // ... - $builder->add('users', EntityType::class, array( + $builder->add('users', EntityType::class, [ 'class' => User::class, // this method must return an array of User entities 'preferred_choices' => $group->getPreferredUsers(), - )); + ]); The preferred choices are only meaningful when rendering a ``select`` element (i.e. ``expanded`` false). The preferred choices and normal choices are separated @@ -313,7 +313,7 @@ The actual default value of this option depends on other field options: * If ``multiple`` is ``false`` and ``expanded`` is ``false``, then ``''`` (empty string); -* Otherwise ``array()`` (empty array). +* Otherwise ``[]`` (empty array). .. include:: /reference/forms/types/options/empty_data.rst.inc :start-after: DEFAULT_PLACEHOLDER diff --git a/reference/forms/types/form.rst b/reference/forms/types/form.rst index 648420384e7..b03732aadc4 100644 --- a/reference/forms/types/form.rst +++ b/reference/forms/types/form.rst @@ -85,7 +85,7 @@ The actual default value of this option depends on other field options: * If ``data_class`` is set and ``required`` is ``true``, then ``new $data_class()``; * If ``data_class`` is set and ``required`` is ``false``, then ``null``; -* If ``data_class`` is not set and ``compound`` is ``true``, then ``array()`` +* If ``data_class`` is not set and ``compound`` is ``true``, then ``[]`` (empty array); * If ``data_class`` is not set and ``compound`` is ``false``, then ``''`` (empty string). diff --git a/reference/forms/types/language.rst b/reference/forms/types/language.rst index 11269c6ce2a..2a60be33e9e 100644 --- a/reference/forms/types/language.rst +++ b/reference/forms/types/language.rst @@ -101,7 +101,7 @@ The actual default value of this option depends on other field options: * If ``multiple`` is ``false`` and ``expanded`` is ``false``, then ``''`` (empty string); -* Otherwise ``array()`` (empty array). +* Otherwise ``[]`` (empty array). .. include:: /reference/forms/types/options/empty_data.rst.inc :start-after: DEFAULT_PLACEHOLDER diff --git a/reference/forms/types/locale.rst b/reference/forms/types/locale.rst index 8f1a0a56936..99998ec4104 100644 --- a/reference/forms/types/locale.rst +++ b/reference/forms/types/locale.rst @@ -102,7 +102,7 @@ The actual default value of this option depends on other field options: * If ``multiple`` is ``false`` and ``expanded`` is ``false``, then ``''`` (empty string); -* Otherwise ``array()`` (empty array). +* Otherwise ``[]`` (empty array). .. include:: /reference/forms/types/options/empty_data.rst.inc :start-after: DEFAULT_PLACEHOLDER diff --git a/reference/forms/types/money.rst b/reference/forms/types/money.rst index 3f6af5941ef..5b706654fbb 100644 --- a/reference/forms/types/money.rst +++ b/reference/forms/types/money.rst @@ -68,9 +68,9 @@ For example:: use Symfony\Component\Form\Extension\Core\Type\MoneyType; // ... - $builder->add('price', MoneyType::class, array( + $builder->add('price', MoneyType::class, [ 'divisor' => 100, - )); + ]); In this case, if the ``price`` field is set to ``9900``, then the value ``99`` will actually be rendered to the user. When the user submits the diff --git a/reference/forms/types/options/attr.rst.inc b/reference/forms/types/options/attr.rst.inc index 46238ac023b..d7ecc7e46dd 100644 --- a/reference/forms/types/options/attr.rst.inc +++ b/reference/forms/types/options/attr.rst.inc @@ -1,12 +1,12 @@ attr ~~~~ -**type**: ``array`` **default**: ``array()`` +**type**: ``array`` **default**: ``[]`` If you want to add extra attributes to an HTML field representation you can use the ``attr`` option. It's an associative array with HTML attributes as keys. This can be useful when you need to set a custom class for some widget:: - $builder->add('body', TextareaType::class, array( - 'attr' => array('class' => 'tinymce'), - )); + $builder->add('body', TextareaType::class, [ + 'attr' => ['class' => 'tinymce'], + ]); diff --git a/reference/forms/types/options/button_label.rst.inc b/reference/forms/types/options/button_label.rst.inc index 9af1a0fcbcb..28ec3d7edd1 100644 --- a/reference/forms/types/options/button_label.rst.inc +++ b/reference/forms/types/options/button_label.rst.inc @@ -14,4 +14,4 @@ be directly set inside the template: .. code-block:: html+php - widget($form['save'], array('label' => 'Click me')) ?> + widget($form['save'], ['label' => 'Click me']) ?> diff --git a/reference/forms/types/options/by_reference.rst.inc b/reference/forms/types/options/by_reference.rst.inc index b1c855c28fc..c3921c58a72 100644 --- a/reference/forms/types/options/by_reference.rst.inc +++ b/reference/forms/types/options/by_reference.rst.inc @@ -19,7 +19,7 @@ To explain this further, here's a simple example:: $builder ->add('title', TextType::class) ->add( - $builder->create('author', FormType::class, array('by_reference' => ?)) + $builder->create('author', FormType::class, ['by_reference' => ?]) ->add('name', TextType::class) ->add('email', EmailType::class) ) diff --git a/reference/forms/types/options/choice_attr.rst.inc b/reference/forms/types/options/choice_attr.rst.inc index e185ae1c763..87c467f7773 100644 --- a/reference/forms/types/options/choice_attr.rst.inc +++ b/reference/forms/types/options/choice_attr.rst.inc @@ -1,7 +1,7 @@ choice_attr ~~~~~~~~~~~ -**type**: ``array``, ``callable`` or ``string`` **default**: ``array()`` +**type**: ``array``, ``callable`` or ``string`` **default**: ``[]`` Use this to add additional HTML attributes to each choice. This can be an associative array where the keys match the choice keys and the values @@ -13,14 +13,14 @@ If an array, the keys of the ``choices`` array must be used as keys:: use Symfony\Component\Form\Extension\Core\Type\ChoiceType; // ... - $builder->add('attending', ChoiceType::class, array( - 'choices' => array( + $builder->add('attending', ChoiceType::class, [ + 'choices' => [ 'Yes' => true, 'No' => false, 'Maybe' => null, - ), + ], 'choice_attr' => function($choiceValue, $key, $value) { // adds a class like attending_yes, attending_no, etc return ['class' => 'attending_'.strtolower($key)]; }, - )); + ]); diff --git a/reference/forms/types/options/choice_label.rst.inc b/reference/forms/types/options/choice_label.rst.inc index bc71a87ea5f..8935757b7e0 100644 --- a/reference/forms/types/options/choice_label.rst.inc +++ b/reference/forms/types/options/choice_label.rst.inc @@ -10,12 +10,12 @@ more control:: use Symfony\Component\Form\Extension\Core\Type\ChoiceType; // ... - $builder->add('attending', ChoiceType::class, array( - 'choices' => array( + $builder->add('attending', ChoiceType::class, [ + 'choices' => [ 'yes' => true, 'no' => false, 'maybe' => null, - ), + ], 'choice_label' => function ($choiceValue, $key, $value) { if ($value == $choiceValue) { return 'Definitely!'; @@ -26,7 +26,7 @@ more control:: // or if you want to translate some key //return 'form.choice.'.$key; }, - )); + ]); This method is called for *each* choice, passing you the choice ``$value`` and the ``$key`` from the choices array (``$index`` is related to `choice_value`_). This @@ -42,14 +42,14 @@ If your choice values are objects, then ``choice_label`` can also be a use Symfony\Component\Form\Extension\Core\Type\ChoiceType; // ... - $builder->add('attending', ChoiceType::class, array( - 'choices' => array( + $builder->add('attending', ChoiceType::class, [ + 'choices' => [ new Status(Status::YES), new Status(Status::NO), new Status(Status::MAYBE), - ), + ], 'choice_label' => 'displayName', - )); + ]); If set to ``false``, all the tag labels will be discarded for radio or checkbox inputs. You can also return ``false`` from the callable to discard certain labels. diff --git a/reference/forms/types/options/data.rst.inc b/reference/forms/types/options/data.rst.inc index 70f3f73365c..9698ff822a6 100644 --- a/reference/forms/types/options/data.rst.inc +++ b/reference/forms/types/options/data.rst.inc @@ -12,9 +12,9 @@ an individual field, you can set it in the data option:: use Symfony\Component\Form\Extension\Core\Type\HiddenType; // ... - $builder->add('token', HiddenType::class, array( + $builder->add('token', HiddenType::class, [ 'data' => 'abcdef', - )); + ]); .. caution:: diff --git a/reference/forms/types/options/data_class.rst.inc b/reference/forms/types/options/data_class.rst.inc index 3808032e489..10d6b478210 100644 --- a/reference/forms/types/options/data_class.rst.inc +++ b/reference/forms/types/options/data_class.rst.inc @@ -10,6 +10,6 @@ form, so you can use it for any form field type which requires an object:: use AppBundle\Form\MediaType; // ... - $builder->add('media', MediaType::class, array( + $builder->add('media', MediaType::class, [ 'data_class' => Media::class, - )); + ]); diff --git a/reference/forms/types/options/date_format.rst.inc b/reference/forms/types/options/date_format.rst.inc index b1ac8498240..961a8ef63ae 100644 --- a/reference/forms/types/options/date_format.rst.inc +++ b/reference/forms/types/options/date_format.rst.inc @@ -16,11 +16,11 @@ For more information on valid formats, see `Date/Time Format Syntax`_:: use Symfony\Component\Form\Extension\Core\Type\DateType; // ... - $builder->add('date_created', DateType::class, array( + $builder->add('date_created', DateType::class, [ 'widget' => 'single_text', // this is actually the default format for single_text 'format' => 'yyyy-MM-dd', - )); + ]); .. note:: diff --git a/reference/forms/types/options/date_input.rst.inc b/reference/forms/types/options/date_input.rst.inc index e1078d88b6b..4de4643677c 100644 --- a/reference/forms/types/options/date_input.rst.inc +++ b/reference/forms/types/options/date_input.rst.inc @@ -8,7 +8,7 @@ on your underlying object. Valid values are: * ``string`` (e.g. ``2011-06-05``) * ``datetime`` (a ``DateTime`` object) -* ``array`` (e.g. ``array('year' => 2011, 'month' => 06, 'day' => 05)``) +* ``array`` (e.g. ``['year' => 2011, 'month' => 06, 'day' => 05]``) * ``timestamp`` (e.g. ``1307232000``) The value that comes back from the form will also be normalized back into diff --git a/reference/forms/types/options/empty_data.rst.inc b/reference/forms/types/options/empty_data.rst.inc index bec4fdc3cd5..e3df385a3f9 100644 --- a/reference/forms/types/options/empty_data.rst.inc +++ b/reference/forms/types/options/empty_data.rst.inc @@ -17,10 +17,10 @@ This means it helps you handling form submission with blank fields. For example, if you want the ``name`` field to be explicitly set to ``John Doe`` when no value is selected, you can do it like this:: - $builder->add('name', null, array( + $builder->add('name', null, [ 'required' => false, 'empty_data' => 'John Doe', - )); + ]); This will still render an empty text box, but upon submission the ``John Doe`` value will be set. Use the ``data`` or ``placeholder`` options to show this diff --git a/reference/forms/types/options/error_mapping.rst.inc b/reference/forms/types/options/error_mapping.rst.inc index dd45aa9c3e1..ce50f2f1126 100644 --- a/reference/forms/types/options/error_mapping.rst.inc +++ b/reference/forms/types/options/error_mapping.rst.inc @@ -1,7 +1,7 @@ error_mapping ~~~~~~~~~~~~~ -**type**: ``array`` **default**: ``array()`` +**type**: ``array`` **default**: ``[]`` This option allows you to modify the target of a validation error. @@ -15,11 +15,11 @@ field so that it displays above it:: public function configureOptions(OptionsResolver $resolver) { - $resolver->setDefaults(array( - 'error_mapping' => array( + $resolver->setDefaults([ + 'error_mapping' => [ 'matchingCityAndZipCode' => 'city', - ), - )); + ], + ]); } Here are the rules for the left and the right side of the mapping: @@ -38,8 +38,8 @@ parent form. You can use the dot (``.``) on the left side to map errors of all unmapped properties to a particular field. For instance, to map all these errors to the ``city`` field, use:: - $resolver->setDefaults(array( - 'error_mapping' => array( + $resolver->setDefaults([ + 'error_mapping' => [ '.' => 'city', - ), - )); + ], + ]); diff --git a/reference/forms/types/options/group_by.rst.inc b/reference/forms/types/options/group_by.rst.inc index 15061135aa9..563ebbfee03 100644 --- a/reference/forms/types/options/group_by.rst.inc +++ b/reference/forms/types/options/group_by.rst.inc @@ -15,13 +15,13 @@ Take the following example:: use Symfony\Component\Form\Extension\Core\Type\ChoiceType; // ... - $builder->add('publishAt', ChoiceType::class, array( - 'choices' => array( + $builder->add('publishAt', ChoiceType::class, [ + 'choices' => [ 'now' => new \DateTime('now'), 'tomorrow' => new \DateTime('+1 day'), '1 week' => new \DateTime('+1 week'), '1 month' => new \DateTime('+1 month'), - ), + ], 'group_by' => function($choiceValue, $key, $value) { if ($choiceValue <= new \DateTime('+3 days')) { return 'Soon'; @@ -29,7 +29,7 @@ Take the following example:: return 'Later'; } }, - )); + ]); This groups the dates that are within 3 days into "Soon" and everything else into a "Later" ````: diff --git a/reference/forms/types/options/invalid_message_parameters.rst.inc b/reference/forms/types/options/invalid_message_parameters.rst.inc index b877f04bb72..aadc9817428 100644 --- a/reference/forms/types/options/invalid_message_parameters.rst.inc +++ b/reference/forms/types/options/invalid_message_parameters.rst.inc @@ -1,14 +1,14 @@ invalid_message_parameters ~~~~~~~~~~~~~~~~~~~~~~~~~~ -**type**: ``array`` **default**: ``array()`` +**type**: ``array`` **default**: ``[]`` When setting the ``invalid_message`` option, you may need to include some variables in the string. This can be done by adding placeholders to that option and including the variables in this option:: - $builder->add('some_field', SomeFormType::class, array( + $builder->add('some_field', SomeFormType::class, [ // ... 'invalid_message' => 'You entered an invalid value, it should include %num% letters', - 'invalid_message_parameters' => array('%num%' => 6), - )); + 'invalid_message_parameters' => ['%num%' => 6], + ]); diff --git a/reference/forms/types/options/label_attr.rst.inc b/reference/forms/types/options/label_attr.rst.inc index 6817483dcbd..48e0dfa9191 100644 --- a/reference/forms/types/options/label_attr.rst.inc +++ b/reference/forms/types/options/label_attr.rst.inc @@ -1,7 +1,7 @@ label_attr ~~~~~~~~~~ -**type**: ``array`` **default**: ``array()`` +**type**: ``array`` **default**: ``[]`` Sets the HTML attributes for the ``