Merge branch '3.4' into 4.1

* 3.4:
  Use the short array syntax notation in all examples
This commit is contained in:
Javier Eguiluz
2019-01-15 19:02:25 +01:00
307 changed files with 2578 additions and 2475 deletions

View File

@@ -232,7 +232,6 @@ Then, this bundle is enabled automatically, but only for the ``dev`` and
``test`` environments::
// config/bundles.php
return [
// ...
Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle::class => ['dev' => true, 'test' => true],

View File

@@ -317,10 +317,10 @@ following standardized instructions in your ``README.md`` file.
{
public function registerBundles()
{
$bundles = array(
$bundles = [
// ...
new <vendor>\<bundle-name>\<bundle-long-name>(),
);
];
// ...
}
@@ -375,11 +375,11 @@ following standardized instructions in your ``README.md`` file.
{
public function registerBundles()
{
$bundles = array(
$bundles = [
// ...
new <vendor>\<bundle-name>\<bundle-long-name>(),
);
];
// ...
}

View File

@@ -40,9 +40,9 @@ as integration of other related components:
.. code-block:: php
$container->loadFromExtension('framework', array(
$container->loadFromExtension('framework', [
'form' => true,
));
]);
Using the Bundle Extension
--------------------------
@@ -81,10 +81,10 @@ allow users to configure it with some configuration that looks like this:
.. code-block:: php
// config/packages/acme_social.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,
@@ -129,14 +129,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 several
@@ -144,21 +144,21 @@ configuration resources. For example, if ``acme_social`` appears in another
configuration file - say ``config/packages/dev/acme_social.yaml`` - with
different values beneath it, the incoming array might look like this::
array(
[
// values from config/packages/acme_social.yaml
array(
'twitter' => array(
[
'twitter' => [
'client_id' => 123,
'client_secret' => 'your_secret',
),
),
],
],
// values from config/packages/dev/acme_social.yaml
array(
'twitter' => array(
[
'twitter' => [
'client_id' => 456,
),
),
)
],
],
]
The order of the two arrays depends on which one is set first.
@@ -304,7 +304,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);

View File

@@ -126,14 +126,14 @@ performance. Define the list of annotated classes to compile in the
{
// ...
$this->addAnnotatedClassesToCompile(array(
$this->addAnnotatedClassesToCompile([
// you can define the fully qualified class names...
'App\\Controller\\DefaultController',
// ... but glob patterns are also supported:
'**Bundle\\Controller\\',
// ...
));
]);
}
.. note::

View File

@@ -63,7 +63,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':
@@ -89,7 +89,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 @@ registered and the ``entity_manager_name`` setting for ``acme_hello`` is set to
.. code-block:: php
// config/packages/acme_something.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
----------------------------------------------------

View File

@@ -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);

View File

@@ -220,7 +220,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

View File

@@ -85,20 +85,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
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

View File

@@ -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();

View File

@@ -57,12 +57,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...
));
]);
The `Data Source Name (DSN)`_ for this adapter must use the following format:
@@ -81,7 +81,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'
@@ -96,7 +96,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
---------------------
@@ -110,14 +110,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

View File

@@ -28,7 +28,7 @@ third, and forth parameters::
$defaultLifetime = 0,
// an array of options for configuring the database table and connection
$options = array()
$options = []
);
.. tip::

View File

@@ -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

View File

@@ -10,22 +10,22 @@ Php Files Cache Adapter
Similarly to :ref:`Filesystem Adapter <component-cache-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::
<?php return array(
<?php return [
// the cache item expiration
0 => 9223372036854775807,
// the cache item contents
1 => array (
1 => [
0 => 'my',
1 => 'cached',
2 => 'array',
),
],
);
];
.. note::

View File

@@ -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,
)
]
);

View File

@@ -32,7 +32,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`,
@@ -40,7 +40,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');

View File

@@ -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

View File

@@ -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``
@@ -195,13 +195,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

View File

@@ -35,7 +35,7 @@ should be regenerated::
// fill this with an array of 'users.yaml' file paths
$yamlUserFiles = ...;
$resources = array();
$resources = [];
foreach ($yamlUserFiles as $yamlUserFile) {
// see the article "Loading resources" to

View File

@@ -143,7 +143,7 @@ values::
$rootNode
->children()
->enumNode('delivery')
->values(array('standard', 'expedited', 'priority'))
->values(['standard', 'expedited', 'priority'])
->end()
->end()
;
@@ -498,9 +498,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()
@@ -731,7 +731,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()
@@ -756,7 +756,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()
@@ -851,7 +851,7 @@ Otherwise the result is a clean array of configuration values::
file_get_contents(__DIR__.'/src/Matthias/config/config_extra.yaml')
);
$configs = array($config, $extraConfig);
$configs = [$config, $extraConfig];
$processor = new Processor();
$databaseConfiguration = new DatabaseConfiguration();

View File

@@ -19,7 +19,7 @@ files. This can be done with the :class:`Symfony\\Component\\Config\\FileLocator
use Symfony\Component\Config\FileLocator;
$configDirectories = array(__DIR__.'/config');
$configDirectories = [__DIR__.'/config'];
$fileLocator = new FileLocator($configDirectories);
$yamlUserFiles = $fileLocator->locate('users.yaml', 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

View File

@@ -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

View File

@@ -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);

View File

@@ -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);

View File

@@ -335,7 +335,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');

View File

@@ -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);
@@ -351,17 +351,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());
}

View File

@@ -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
@@ -251,12 +251,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();
@@ -277,9 +277,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'],
))
// ...
@@ -302,15 +302,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();

View File

@@ -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
------

View File

@@ -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
----------

View File

@@ -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 </components/config>` to
@@ -486,7 +486,7 @@ dump it::
$dumper = new PhpDumper($containerBuilder);
file_put_contents(
$file,
$dumper->dump(array('class' => 'MyCachedContainer'))
$dumper->dump(['class' => 'MyCachedContainer'])
);
}
@@ -519,7 +519,7 @@ application::
$dumper = new PhpDumper($containerBuilder);
file_put_contents(
$file,
$dumper->dump(array('class' => 'MyCachedContainer'))
$dumper->dump(['class' => 'MyCachedContainer'])
);
}
}
@@ -552,7 +552,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()
);
}

View File

@@ -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::
@@ -264,7 +264,7 @@ and :phpclass:`DOMNode` objects::
$crawler->addDocument($domDocument);
$crawler->addNodeList($nodeList);
$crawler->addNodes(array($node));
$crawler->addNodes([$node]);
$crawler->addNode($node);
$crawler->add($domDocument);
@@ -417,9 +417,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::
@@ -443,10 +443,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();
@@ -466,13 +466,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,
@@ -488,7 +488,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');

View File

@@ -140,7 +140,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:
@@ -213,10 +213,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)
@@ -343,13 +343,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)

View File

@@ -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

View File

@@ -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`

View File

@@ -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()
;

View File

@@ -51,7 +51,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
@@ -62,7 +62,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

View File

@@ -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);
}),
);
];
}
}
@@ -107,10 +107,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());
@@ -125,7 +125,7 @@ or by using the second argument of the constructor::
class ExpressionLanguage extends BaseExpressionLanguage
{
public function __construct(CacheItemPoolInterface $parser = null, array $providers = array())
public function __construct(CacheItemPoolInterface $parser = null, array $providers = [])
{
// prepends the default provider to let users override it easily
array_unshift($providers, new StringExpressionLanguageProvider());

View File

@@ -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

View File

@@ -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::

View File

@@ -92,7 +92,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');

View File

@@ -202,16 +202,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)
@@ -406,9 +406,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
@@ -432,9 +432,9 @@ is created from the form factory.
->add('dueDate', DateType::class)
->getForm();
return $this->render('task/new.html.twig', array(
return $this->render('task/new.html.twig', [
'form' => $form->createView(),
));
]);
}
}
@@ -462,9 +462,9 @@ an "edit" form), pass in the default data when creating your form builder:
// ...
$defaults = array(
$defaults = [
'dueDate' => new \DateTime('tomorrow'),
);
];
$form = $formFactory->createBuilder(FormType::class, $defaults)
->add('task', TextType::class)
@@ -484,9 +484,9 @@ an "edit" form), pass in the default data when creating your form builder:
{
public function new(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 search()
{
$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 new(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();
// ...
}

View File

@@ -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
@@ -349,12 +349,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(
@@ -385,7 +385,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::
@@ -471,14 +471,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
@@ -624,9 +624,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`
@@ -635,12 +635,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 }');

View File

@@ -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::
@@ -85,7 +85,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);
Migrating Between Save Handlers
@@ -202,7 +202,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::

View File

@@ -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 '<div class="flash-notice">'.$message.'</div>';
}
@@ -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 the 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.
Display one type of message::
// display warnings
foreach ($session->getFlashBag()->get('warning', array()) as $message) {
foreach ($session->getFlashBag()->get('warning', []) as $message) {
echo '<div class="flash-warning">'.$message.'</div>';
}
// display errors
foreach ($session->getFlashBag()->get('error', array()) as $message) {
foreach ($session->getFlashBag()->get('error', []) as $message) {
echo '<div class="flash-error">'.$message.'</div>';
}

View File

@@ -643,12 +643,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();

View File

@@ -85,13 +85,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');
@@ -112,13 +112,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
~~~~~~~~~~~~~~~~~~
@@ -190,7 +190,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`
@@ -204,7 +204,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
));
@@ -232,7 +232,7 @@ bundle::
\Locale::setDefault('en');
$languages = Intl::getLanguageBundle()->getLanguageNames();
// => array('ab' => 'Abkhazian', ...)
// => ['ab' => 'Abkhazian', ...]
$language = Intl::getLanguageBundle()->getLanguageName('de');
// => 'German'
@@ -241,7 +241,7 @@ bundle::
// => 'Austrian German'
$scripts = Intl::getLanguageBundle()->getScriptNames();
// => array('Arab' => 'Arabic', ...)
// => ['Arab' => 'Arabic', ...]
$script = Intl::getLanguageBundle()->getScriptName('Hans');
// => 'Simplified'
@@ -250,7 +250,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
~~~~~~~~~~~~~
@@ -262,7 +262,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'
@@ -271,7 +271,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
~~~~~~~
@@ -283,7 +283,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)'
@@ -292,7 +292,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
~~~~~~~~~~
@@ -305,7 +305,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'
@@ -327,7 +327,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!

View File

@@ -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);
// Adding or removing values to a multi-valued attribute is more efficient than using update()

View File

@@ -261,7 +261,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);

View File

@@ -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[]');
@@ -340,9 +340,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"
@@ -368,7 +368,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']);
}
}
@@ -376,9 +376,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"
@@ -501,10 +501,10 @@ the closure::
public function configureOptions(OptionsResolver $resolver)
{
// ...
$resolver->setDefaults(array(
$resolver->setDefaults([
'encryption' => null,
'host' => 'example.org',
));
]);
}
}
@@ -589,9 +589,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!
@@ -605,7 +605,7 @@ options in one go::
public function configureOptions(OptionsResolver $resolver)
{
// ...
$resolver->setDefined(array('port', 'encryption'));
$resolver->setDefined(['port', 'encryption']);
}
}
@@ -646,11 +646,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);
@@ -679,11 +679,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 = [];
}
// ...

View File

@@ -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
---------------

View File

@@ -30,7 +30,7 @@ escaping arguments to prevent security issues. It replaces PHP functions like
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
@@ -68,7 +68,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) {
@@ -85,7 +85,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) {
@@ -100,7 +100,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();
@@ -121,7 +121,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
@@ -141,7 +141,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
--------------------------------
@@ -153,7 +153,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;
@@ -172,7 +172,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()) {
@@ -184,7 +184,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
@@ -223,7 +223,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) {
@@ -255,7 +255,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();
@@ -281,7 +281,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();
@@ -307,7 +307,7 @@ is sent to the running process. The default signal sent to a process is ``SIGKIL
Please read the :ref:`signal documentation below<reference-process-signal>`
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
@@ -336,7 +336,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();
@@ -368,7 +368,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();
@@ -384,7 +384,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
@@ -398,7 +398,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();
@@ -413,7 +413,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();

View File

@@ -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<SingularOfThePropertyName>()``
and ``remove<SingularOfThePropertyName>()``. 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)
{

View File

@@ -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`:

View File

@@ -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();

View File

@@ -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.yaml');
@@ -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.yaml',
array('cache_dir' => __DIR__.'/cache'),
['cache_dir' => __DIR__.'/cache'],
$requestContext
);
$router->match('/foo/bar');
@@ -435,13 +435,13 @@ routes with UTF-8 characters:
$routes = new RouteCollection();
$routes->add('route1', new Route('/category/{name}',
array(
[
'_controller' => 'App\Controller\DefaultController::category',
),
array(),
array(
],
[],
[
'utf8' => true,
)
]
));
// ...
@@ -512,15 +512,15 @@ You can also include UTF-8 strings as routing requirements:
$routes = new RouteCollection();
$routes->add('route2', new Route('/default/{default}',
array(
[
'_controller' => 'App\Controller\DefaultController::default',
),
array(
],
[
'default' => '한국어',
),
array(
],
[
'utf8' => true,
)
]
));
// ...

View File

@@ -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`

View File

@@ -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,

View File

@@ -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

View File

@@ -54,8 +54,8 @@ 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);
@@ -189,10 +189,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
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -212,7 +212,7 @@ The serializer can also be used to update an existing object::
</person>
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.
@@ -337,16 +337,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')
@@ -384,10 +384,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.
@@ -412,10 +412,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:
@@ -472,7 +472,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.';
@@ -521,7 +521,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
@@ -553,9 +553,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');
@@ -813,7 +813,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);
@@ -834,7 +834,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"}]}
@@ -919,17 +919,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,
),
),
);
],
],
];
*/
Instead of throwing an exception, a custom callable can be executed when the
@@ -1004,7 +1004,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}]
@@ -1023,8 +1023,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
@@ -1036,7 +1036,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:
@@ -1051,7 +1051,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:
// <?xml version="1.0"?>
@@ -1061,7 +1061,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:
// <?xml version="1.0"?>
@@ -1189,10 +1189,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'
);

View File

@@ -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::
<?php $names = array('Fabien', ...) ?>
<?php $names = ['Fabien', ...] ?>
<?php foreach ($names as $name) : ?>
<?= $view->render('hello.php', array('firstname' => $name)) ?>
<?= $view->render('hello.php', ['firstname' => $name]) ?>
<?php endforeach ?>
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()) <Symfony\\Component\\Templating\\EngineInterface::render>`
* :method:`render($name, array $parameters = []) <Symfony\\Component\\Templating\\EngineInterface::render>`
- Renders a template
* :method:`exists($name) <Symfony\\Component\\Templating\\EngineInterface::exists>`
- 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
----------

View File

@@ -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.

View File

@@ -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.yaml' , 'fr_FR');
$dumper = new MyFormatDumper();
$dumper->dump($translations, array('path' => __DIR__.'/dumps'));
$dumper->dump($translations, ['path' => __DIR__.'/dumps']);

View File

@@ -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
@@ -366,7 +366,7 @@ use for translation::
$translator->trans(
'Symfony is great',
array(),
[],
'messages',
'fr_FR'
);
@@ -374,7 +374,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'
);
@@ -388,7 +388,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'
);
@@ -408,15 +408,15 @@ messages. 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
------------------------------------

View File

@@ -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

View File

@@ -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',
)));
]));
}
}

View File

@@ -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,
)));
]));
}
}

View File

@@ -253,7 +253,7 @@ Example::
public function testWithDumpEquals()
{
$testedVar = array(123, 'foo');
$testedVar = [123, 'foo'];
$expectedDump = <<<EOTXT
array:2 [
@@ -282,13 +282,13 @@ For simple variables, reading the output should be straightforward.
Here are some examples showing first a variable defined in PHP,
then its dump representation::
$var = array(
$var = [
'a simple string' => "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
@@ -369,11 +369,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);

View File

@@ -190,11 +190,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
));
]);
The output format of a dumper can be fine tuned by the two flags
``DUMP_STRING_LENGTH`` and ``DUMP_LIGHT_ARRAY`` which are passed as a bitmap
@@ -215,7 +215,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);
@@ -239,7 +239,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);
@@ -263,7 +263,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);
@@ -286,7 +286,7 @@ or its ``addCasters()`` method::
use Symfony\Component\VarDumper\Cloner\VarCloner;
$myCasters = array(...);
$myCasters = [...];
$cloner = new VarCloner($myCasters);
// or
@@ -296,10 +296,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.

View File

@@ -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
@@ -139,10 +139,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);
@@ -261,7 +261,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::
@@ -314,14 +314,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: |
@@ -338,7 +338,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
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -347,7 +347,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
@@ -366,16 +366,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 }'

View File

@@ -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

View File

@@ -61,7 +61,7 @@ instance, the framework bundle is configured in ``config/packages/framework.yaml
.. code-block:: php
# config/packages/framework.php
// config/packages/framework.php
$container->loadFromExtension('framework', [
'secret' => '%env(APP_SECRET)%',
//'default_locale' => 'en',
@@ -82,6 +82,31 @@ instance, the framework bundle is configured in ``config/packages/framework.yaml
The top-level key (here ``framework``) references configuration for a specific
bundle (:doc:`FrameworkBundle </reference/configuration/framework>` in this case).
=======
// app/config/config.php
$this->import('parameters.yml');
$this->import('security.yml');
$this->import('services.yml');
$container->loadFromExtension('framework', [
'secret' => '%secret%',
'router' => [
'resource' => '%kernel.project_dir%/app/config/routing.php',
],
// ...
]);
// Twig Configuration
$container->loadFromExtension('twig', [
'debug' => '%kernel.debug%',
'strict_variables' => '%kernel.debug%',
]);
// ...
Most top-level keys - like ``framework`` and ``twig`` - are configuration for a
specific bundle (i.e. ``FrameworkBundle`` and ``TwigBundle``).
>>>>>>> 3.4
.. sidebar:: Configuration Formats
@@ -194,12 +219,12 @@ This parameter is then referenced in the framework config in
.. code-block:: php
// config/packages/translation.php
$container->loadFromExtension('framework', array(
$container->loadFromExtension('framework', [
// any string surrounded by two % is replaced by that parameter value
'default_locale' => '%locale%',
// ...
));
]);
You can define whatever parameter names you want under the ``parameters`` key of
any configuration file. To reference a parameter, surround its name with two

View File

@@ -164,10 +164,10 @@ the environment variable is passed to the kernel::
.. code-block:: php
$container->loadFromExtension('twig', array(
$container->loadFromExtension('twig', [
'debug' => '%kernel.debug%',
// ...
));
]);
Selecting the Environment for Console Commands
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -235,9 +235,9 @@ configuration file:
.. code-block:: php
// config/packages/benchmark/web_profiler.php
$container->loadFromExtension('framework', array(
'profiler' => array('only_exceptions' => false),
));
$container->loadFromExtension('framework', [
'profiler' => ['only_exceptions' => false],
]);
And... you're finished! The application now supports a new environment called
``benchmark``.

View File

@@ -64,11 +64,11 @@ This variable is referenced in the service container configuration using
.. code-block:: php
// config/packages/doctrine.php
$container->loadFromExtension('doctrine', array(
'dbal' => array(
$container->loadFromExtension('doctrine', [
'dbal' => [
'url' => '%env(DATABASE_URL)%',
)
));
]
]);
You can also give the ``env()`` parameters a default value: the default value
will be used whenever the corresponding environment variable is *not* found:
@@ -176,11 +176,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:
@@ -220,9 +220,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:
@@ -260,9 +260,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.
@@ -307,14 +307,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.
@@ -356,9 +356,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
@@ -397,9 +397,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(csv:FOO)``
Decodes the content of ``FOO``, which is a CSV-encoded string:
@@ -450,9 +450,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:

View File

@@ -38,17 +38,17 @@ Next, create an ``index.php`` file that defines the 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/packages/framework.yaml
$c->loadFromExtension('framework', array(
$c->loadFromExtension('framework', [
'secret' => 'S0ME_SECRET'
));
]);
}
protected function configureRoutes(RouteCollectionBuilder $routes)
@@ -60,9 +60,9 @@ Next, create an ``index.php`` file that defines the kernel class and executes it
public function randomNumber($limit)
{
return new JsonResponse(array(
return new JsonResponse([
'number' => random_int(0, $limit),
));
]);
}
}
@@ -145,10 +145,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();
@@ -163,10 +163,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,
));
]);
}
}
@@ -231,12 +231,12 @@ because the configuration started to get bigger:
.. code-block:: php
// config/framework.php
$container->loadFromExtension('framework', array(
$container->loadFromExtension('framework', [
'secret' => 'S0ME_SECRET',
'profiler' => array(
'profiler' => [
'only_exceptions' => false,
),
));
],
]);
This also loads annotation routes from an ``src/Controller/`` directory, which
has one file in it::
@@ -256,9 +256,9 @@ has one file in it::
{
$number = random_int(0, $limit);
return $this->render('micro/random.html.twig', array(
return $this->render('micro/random.html.twig', [
'number' => $number,
));
]);
}
}
@@ -289,7 +289,7 @@ Finally, you need a front controller to boot and run the application. Create a
$loader = require __DIR__.'/../vendor/autoload.php';
// auto-load annotations
AnnotationRegistry::registerLoader(array($loader, 'loadClass'));
AnnotationRegistry::registerLoader([$loader, 'loadClass']);
$kernel = new Kernel('dev', true);
$request = Request::createFromGlobals();

View File

@@ -123,11 +123,11 @@ own templates directory (or directories):
.. code-block:: php
// config/packages/twig.php
$container->loadFromExtension('twig', array(
'paths' => array(
$container->loadFromExtension('twig', [
'paths' => [
'%kernel.project_dir%/resources/views',
),
));
],
]);
Override the Translations Directory
-----------------------------------
@@ -169,13 +169,13 @@ configuration option to define your own translations directory (or directories):
.. code-block:: php
// config/packages/translation.php
$container->loadFromExtension('framework', array(
'translator' => array(
'paths' => array(
$container->loadFromExtension('framework', [
'translator' => [
'paths' => [
'%kernel.project_dir%/i18n',
),
),
));
],
],
]);
.. _override-web-dir:
.. _override-the-web-directory:
@@ -211,7 +211,62 @@ You also need to change the ``extra.public-dir`` option in the
your Symfony project work on your shared host. Another way is to deploy
your application to a directory outside of your web root, delete your
``public_html`` directory, and then replace it with a symbolic link to
<<<<<<< HEAD
the ``public`` dir in your project.
=======
the ``web`` in your project.
.. note::
If you use the AsseticBundle, you need to configure the ``read_from`` option
to point to the correct ``web`` directory:
.. configuration-block::
.. code-block:: yaml
# app/config/config.yml
# ...
assetic:
# ...
read_from: '%kernel.project_dir%/../public_html'
.. code-block:: xml
<!-- app/config/config.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:assetic="http://symfony.com/schema/dic/assetic"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services
http://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/assetic
http://symfony.com/schema/dic/assetic/assetic-1.0.xsd">
<!-- ... -->
<assetic:config read-from="%kernel.project_dir%/../public_html" />
</container>
.. code-block:: php
// app/config/config.php
// ...
$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:
.. code-block:: terminal
$ php bin/console cache:clear --env=prod
$ php bin/console assetic:dump --env=prod --no-debug
>>>>>>> 3.4
Override the ``vendor`` Directory
---------------------------------

View File

@@ -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 Kernel),
// as expected, because %kernel.debug% inside configuration
// gets evaluated before being passed to the extension
)
);
];
$container->loadFromExtension('my_bundle');
// passes the string "%kernel.debug%".

View File

@@ -344,7 +344,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
@@ -352,7 +352,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();

View File

@@ -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);

View File

@@ -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('<fire>foo</>');

View File

@@ -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();

View File

@@ -116,7 +116,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::

View File

@@ -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

View File

@@ -17,9 +17,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);
@@ -47,10 +47,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`
@@ -72,9 +72,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)``.

View File

@@ -86,7 +86,7 @@ router service and override its settings::
public function __construct(RouterInterface $router)
{
parent::__construct();
$this->router = $router;
}
@@ -97,7 +97,7 @@ router service and override its settings::
$context->setScheme('https');
$context->setBaseUrl('my/path');
$url = $this->router->generate('route-name', array('param-name' => 'param-value'));
$url = $this->router->generate('route-name', ['param-name' => 'param-value']);
// ...
}
}

View File

@@ -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([
'<info>Lorem Ipsum Dolor Sit Amet</>',
'<info>==========================</>',
'',
));
]);
// ...
}
@@ -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 <Enter> 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
------------------------

View File

@@ -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()) {

View File

@@ -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)) {

View File

@@ -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)

View File

@@ -123,7 +123,7 @@ Generating URLs
The :method:`Symfony\\Bundle\\FrameworkBundle\\Controller\\AbstractController::generateUrl`
method is just a helper method that generates the URL for a given route::
$url = $this->generateUrl('app_lucky_number', array('max' => 10));
$url = $this->generateUrl('app_lucky_number', ['max' => 10]);
Redirecting
~~~~~~~~~~~
@@ -143,10 +143,10 @@ and ``redirect()`` methods::
// return new RedirectResponse($this->generateUrl('homepage'));
// does a permanent - 301 redirect
return $this->redirectToRoute('homepage', array(), 301);
return $this->redirectToRoute('homepage', [], 301);
// redirect to a route with parameters
return $this->redirectToRoute('app_lucky_number', array('max' => 10));
return $this->redirectToRoute('app_lucky_number', ['max' => 10]);
// redirects to a route and maintains the original query string parameters
return $this->redirectToRoute('blog_show', $request->query->all());
@@ -174,7 +174,7 @@ method renders a template **and** puts that content into a ``Response``
object for you::
// renders templates/lucky/number.html.twig
return $this->render('lucky/number.html.twig', array('number' => $number));
return $this->render('lucky/number.html.twig', ['number' => $number]);
Templating and Twig are explained more in the
:doc:`Creating and Using Templates article </templating>`.
@@ -267,10 +267,10 @@ the argument by its name:
$container->register(LuckyController::class)
->setPublic(true)
->setBindings(array(
->setBindings([
'$logger' => new Reference('monolog.logger.doctrine'),
'$projectDir' => '%kernel.project_dir%'
))
])
;
Like with all services, you can also use regular :ref:`constructor injection <services-constructor-injection>`
@@ -404,7 +404,7 @@ To get the session, add an argument and type-hint it with
$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.
@@ -505,7 +505,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');
@@ -559,10 +559,10 @@ special ``JsonResponse`` object that encodes the data automatically::
public function index()
{
// 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 </serializer>` is enabled in your

View File

@@ -95,12 +95,12 @@ type-hinted method arguments:
.. code-block:: php
// config/packages/sensio_framework_extra.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`
@@ -210,7 +210,7 @@ and adding a priority.
use App\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

View File

@@ -231,10 +231,10 @@ configuration option to point to it:
.. code-block:: php
// config/packages/twig.php
$container->loadFromExtension('twig', array(
$container->loadFromExtension('twig', [
'exception_controller' => 'App\Controller\ExceptionController::showException',
// ...
));
]);
The :class:`Symfony\\Component\\HttpKernel\\EventListener\\ExceptionListener`
class used by the TwigBundle as a listener of the ``kernel.exception`` event creates

View File

@@ -13,10 +13,10 @@ from *that* controller::
public function index($name)
{
$response = $this->forward('App\Controller\OtherController::fancy', array(
$response = $this->forward('App\Controller\OtherController::fancy', [
'name' => $name,
'color' => 'green',
));
]);
// ... further modify the response or return it directly

View File

@@ -65,9 +65,9 @@ a service like: ``App\Controller\HelloController::index``:
.. code-block:: php
// config/routes.php
$collection->add('hello', new Route('/hello', array(
$collection->add('hello', new Route('/hello', [
'_controller' => 'App\Controller\HelloController::index',
)));
]));
.. _controller-service-invoke:
@@ -112,7 +112,7 @@ service and use it directly::
{
$content = $this->twig->render(
'hello/index.html.twig',
array('name' => $name)
['name' => $name]
);
return new Response($content);

View File

@@ -101,7 +101,7 @@ the route ``/soap``::
$soapClient = new \SoapClient('http://example.com/index.php/soap?wsdl');
$result = $soapClient->call('hello', array('name' => 'Scott'));
$result = $soapClient->call('hello', ['name' => 'Scott']);
An example WSDL is below.

View File

@@ -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(),
));
]);
}
/**
@@ -436,12 +436,12 @@ Now, register this class as a Doctrine listener:
use App\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

View File

@@ -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::exception'))
->setArguments(['Calendar\Controller\ErrorController::exception'])
;
$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::

View File

@@ -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]];
}
}

View File

@@ -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])) {

View File

@@ -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

View File

@@ -22,9 +22,9 @@ 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(), 'index'),
'_controller' => [new LeapYearController(), 'index'],
)));
The move is pretty straightforward and makes a lot of sense as soon as you
@@ -62,10 +62,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::index',
)));
]));
To make this code work, modify the framework code to use the controller
resolver from HttpKernel::

View File

@@ -169,7 +169,7 @@ only if needed::
public static function getSubscribedEvents()
{
return array('kernel.view' => 'onView');
return ['kernel.view' => 'onView'];
}
}

Some files were not shown because too many files have changed in this diff Show More