Merge branch '3.4' into 4.1

* 3.4:
  fixed CS
  fixed short array CS in comments
  fixed CS in ExpressionLanguage fixtures
  fixed CS in generated files
  fixed CS on generated container files
  fixed CS on Form PHP templates
  fixed CS on YAML fixtures
  fixed fixtures
  switched array() to []
This commit is contained in:
Fabien Potencier 2019-01-16 19:21:11 +01:00
commit 572864b223
1863 changed files with 22367 additions and 22365 deletions

View File

@ -5,26 +5,26 @@ if (!file_exists(__DIR__.'/src')) {
}
return PhpCsFixer\Config::create()
->setRules(array(
->setRules([
'@Symfony' => true,
'@Symfony:risky' => true,
'@PHPUnit48Migration:risky' => true,
'php_unit_no_expectation_annotation' => false, // part of `PHPUnitXYMigration:risky` ruleset, to be enabled when PHPUnit 4.x support will be dropped, as we don't want to rewrite exceptions handling twice
'array_syntax' => array('syntax' => 'short'),
'array_syntax' => ['syntax' => 'short'],
'fopen_flags' => false,
'ordered_imports' => true,
'protected_to_private' => false,
// Part of @Symfony:risky in PHP-CS-Fixer 2.13.0. To be removed from the config file once upgrading
'native_function_invocation' => array('include' => array('@compiler_optimized'), 'scope' => 'namespaced'),
'native_function_invocation' => ['include' => ['@compiler_optimized'], 'scope' => 'namespaced'],
// Part of future @Symfony ruleset in PHP-CS-Fixer To be removed from the config file once upgrading
'phpdoc_types_order' => array('null_adjustment' => 'always_last', 'sort_algorithm' => 'none'),
))
'phpdoc_types_order' => ['null_adjustment' => 'always_last', 'sort_algorithm' => 'none'],
])
->setRiskyAllowed(true)
->setFinder(
PhpCsFixer\Finder::create()
->in(__DIR__.'/src')
->append(array(__FILE__))
->exclude(array(
->append([__FILE__])
->exclude([
// directories containing files with content that is autogenerated by `var_export`, which breaks CS in output code
'Symfony/Component/DependencyInjection/Tests/Fixtures',
'Symfony/Component/Routing/Tests/Fixtures/dumper',
@ -38,7 +38,7 @@ return PhpCsFixer\Config::create()
'Symfony/Bundle/FrameworkBundle/Resources/views/Form',
// explicit trigger_error tests
'Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/',
))
])
// Support for older PHPunit version
->notPath('Symfony/Bridge/PhpUnit/SymfonyTestsListener.php')
// file content autogenerated by `var_export`

View File

@ -27,8 +27,8 @@ class ContainerAwareEventManager extends EventManager
*
* <event> => <listeners>
*/
private $listeners = array();
private $initialized = array();
private $listeners = [];
private $initialized = [];
private $container;
public function __construct(ContainerInterface $container)

View File

@ -65,13 +65,13 @@ class RegisterEventListenersAndSubscribersPass implements CompilerPassInterface
foreach ($taggedSubscribers as $taggedSubscriber) {
list($id, $tag) = $taggedSubscriber;
$connections = isset($tag['connection']) ? array($tag['connection']) : array_keys($this->connections);
$connections = isset($tag['connection']) ? [$tag['connection']] : array_keys($this->connections);
foreach ($connections as $con) {
if (!isset($this->connections[$con])) {
throw new RuntimeException(sprintf('The Doctrine connection "%s" referenced in service "%s" does not exist. Available connections names: %s', $con, $id, implode(', ', array_keys($this->connections))));
}
$this->getEventManagerDef($container, $con)->addMethodCall('addEventSubscriber', array(new Reference($id)));
$this->getEventManagerDef($container, $con)->addMethodCall('addEventSubscriber', [new Reference($id)]);
}
}
}
@ -88,7 +88,7 @@ class RegisterEventListenersAndSubscribersPass implements CompilerPassInterface
throw new InvalidArgumentException(sprintf('Doctrine event listener "%s" must specify the "event" attribute.', $id));
}
$connections = isset($tag['connection']) ? array($tag['connection']) : array_keys($this->connections);
$connections = isset($tag['connection']) ? [$tag['connection']] : array_keys($this->connections);
foreach ($connections as $con) {
if (!isset($this->connections[$con])) {
throw new RuntimeException(sprintf('The Doctrine connection "%s" referenced in service "%s" does not exist. Available connections names: %s', $con, $id, implode(', ', array_keys($this->connections))));
@ -99,7 +99,7 @@ class RegisterEventListenersAndSubscribersPass implements CompilerPassInterface
}
// we add one call per event per service so we have the correct order
$this->getEventManagerDef($container, $con)->addMethodCall('addEventListener', array(array($tag['event']), $lazy ? $id : new Reference($id)));
$this->getEventManagerDef($container, $con)->addMethodCall('addEventListener', [[$tag['event']], $lazy ? $id : new Reference($id)]);
}
}
}
@ -130,12 +130,12 @@ class RegisterEventListenersAndSubscribersPass implements CompilerPassInterface
*/
private function findAndSortTags($tagName, ContainerBuilder $container)
{
$sortedTags = array();
$sortedTags = [];
foreach ($container->findTaggedServiceIds($tagName, true) as $serviceId => $tags) {
foreach ($tags as $attributes) {
$priority = isset($attributes['priority']) ? $attributes['priority'] : 0;
$sortedTags[$priority][] = array($serviceId, $attributes);
$sortedTags[$priority][] = [$serviceId, $attributes];
}
}

View File

@ -78,7 +78,7 @@ class DoctrineChoiceLoader implements ChoiceLoaderInterface
{
// Performance optimization
if (empty($choices)) {
return array();
return [];
}
// Optimize performance for single-field identifiers. We already
@ -87,7 +87,7 @@ class DoctrineChoiceLoader implements ChoiceLoaderInterface
// Attention: This optimization does not check choices for existence
if ($optimize && !$this->choiceList && $this->idReader->isSingleId()) {
$values = array();
$values = [];
// Maintain order and indices of the given objects
foreach ($choices as $i => $object) {
@ -115,7 +115,7 @@ class DoctrineChoiceLoader implements ChoiceLoaderInterface
// statements, consequently no test fails when this code is removed.
// https://github.com/symfony/symfony/pull/8981#issuecomment-24230557
if (empty($values)) {
return array();
return [];
}
// Optimize performance in case we have an object loader and
@ -124,8 +124,8 @@ class DoctrineChoiceLoader implements ChoiceLoaderInterface
if ($optimize && !$this->choiceList && $this->objectLoader && $this->idReader->isSingleId()) {
$unorderedObjects = $this->objectLoader->getEntitiesByIds($this->idReader->getIdField(), $values);
$objectsById = array();
$objects = array();
$objectsById = [];
$objects = [];
// Maintain order and indices from the given $values
// An alternative approach to the following loop is to add the

View File

@ -43,7 +43,7 @@ class IdReader
$this->om = $om;
$this->classMetadata = $classMetadata;
$this->singleId = 1 === \count($ids);
$this->intId = $this->singleId && \in_array($idType, array('integer', 'smallint', 'bigint'));
$this->intId = $this->singleId && \in_array($idType, ['integer', 'smallint', 'bigint']);
$this->idField = current($ids);
// single field association are resolved, since the schema column could be an int

View File

@ -64,7 +64,7 @@ class ORMQueryBuilderLoader implements EntityLoaderInterface
// Guess type
$entity = current($qb->getRootEntities());
$metadata = $qb->getEntityManager()->getClassMetadata($entity);
if (\in_array($metadata->getTypeOfField($identifier), array('integer', 'bigint', 'smallint'))) {
if (\in_array($metadata->getTypeOfField($identifier), ['integer', 'bigint', 'smallint'])) {
$parameterType = Connection::PARAM_INT_ARRAY;
// Filter out non-integer values (e.g. ""). If we don't, some
@ -72,7 +72,7 @@ class ORMQueryBuilderLoader implements EntityLoaderInterface
$values = array_values(array_filter($values, function ($v) {
return (string) $v === (string) (int) $v || ctype_digit($v);
}));
} elseif (\in_array($metadata->getTypeOfField($identifier), array('uuid', 'guid'))) {
} elseif (\in_array($metadata->getTypeOfField($identifier), ['uuid', 'guid'])) {
$parameterType = Connection::PARAM_STR_ARRAY;
// Like above, but we just filter out empty strings.
@ -83,7 +83,7 @@ class ORMQueryBuilderLoader implements EntityLoaderInterface
$parameterType = Connection::PARAM_STR_ARRAY;
}
if (!$values) {
return array();
return [];
}
return $qb->andWhere($where)

View File

@ -31,7 +31,7 @@ class CollectionToArrayTransformer implements DataTransformerInterface
public function transform($collection)
{
if (null === $collection) {
return array();
return [];
}
// For cases when the collection getter returns $collection->toArray()
@ -57,7 +57,7 @@ class CollectionToArrayTransformer implements DataTransformerInterface
public function reverseTransform($array)
{
if ('' === $array || null === $array) {
$array = array();
$array = [];
} else {
$array = (array) $array;
}

View File

@ -26,9 +26,9 @@ class DoctrineOrmExtension extends AbstractExtension
protected function loadTypes()
{
return array(
return [
new EntityType($this->registry),
);
];
}
protected function loadTypeGuesser()

View File

@ -35,12 +35,12 @@ abstract class DoctrineType extends AbstractType
/**
* @var IdReader[]
*/
private $idReaders = array();
private $idReaders = [];
/**
* @var DoctrineChoiceLoader[]
*/
private $choiceLoaders = array();
private $choiceLoaders = [];
/**
* Creates the label for a choice.
@ -126,11 +126,11 @@ abstract class DoctrineType extends AbstractType
// also if concrete Type can return important QueryBuilder parts to generate
// hash key we go for it as well
if (!$options['query_builder'] || false !== ($qbParts = $this->getQueryBuilderPartsForCachingHash($options['query_builder']))) {
$hash = CachingFactoryDecorator::generateHash(array(
$hash = CachingFactoryDecorator::generateHash([
$options['em'],
$options['class'],
$qbParts,
));
]);
if (isset($this->choiceLoaders[$hash])) {
return $this->choiceLoaders[$hash];
@ -167,7 +167,7 @@ abstract class DoctrineType extends AbstractType
// field name. We can only use numeric IDs as names, as we cannot
// guarantee that a non-numeric ID contains a valid form name
if ($idReader->isIntId()) {
return array(__CLASS__, 'createChoiceName');
return [__CLASS__, 'createChoiceName'];
}
// Otherwise, an incrementing integer is used as name automatically
@ -183,7 +183,7 @@ abstract class DoctrineType extends AbstractType
// If the entity has a single-column ID, use that ID as value
if ($idReader->isSingleId()) {
return array($idReader, 'getIdValue');
return [$idReader, 'getIdValue'];
}
// Otherwise, an incrementing integer is used as value automatically
@ -221,10 +221,10 @@ abstract class DoctrineType extends AbstractType
// Set the "id_reader" option via the normalizer. This option is not
// supposed to be set by the user.
$idReaderNormalizer = function (Options $options) {
$hash = CachingFactoryDecorator::generateHash(array(
$hash = CachingFactoryDecorator::generateHash([
$options['em'],
$options['class'],
));
]);
// The ID reader is a utility that is needed to read the object IDs
// when generating the field values. The callback generating the
@ -240,25 +240,25 @@ abstract class DoctrineType extends AbstractType
return $this->idReaders[$hash];
};
$resolver->setDefaults(array(
$resolver->setDefaults([
'em' => null,
'query_builder' => null,
'choices' => null,
'choice_loader' => $choiceLoader,
'choice_label' => array(__CLASS__, 'createChoiceLabel'),
'choice_label' => [__CLASS__, 'createChoiceLabel'],
'choice_name' => $choiceName,
'choice_value' => $choiceValue,
'id_reader' => null, // internal
'choice_translation_domain' => false,
));
]);
$resolver->setRequired(array('class'));
$resolver->setRequired(['class']);
$resolver->setNormalizer('em', $emNormalizer);
$resolver->setNormalizer('query_builder', $queryBuilderNormalizer);
$resolver->setNormalizer('id_reader', $idReaderNormalizer);
$resolver->setAllowedTypes('em', array('null', 'string', 'Doctrine\Common\Persistence\ObjectManager'));
$resolver->setAllowedTypes('em', ['null', 'string', 'Doctrine\Common\Persistence\ObjectManager']);
}
/**
@ -279,6 +279,6 @@ abstract class DoctrineType extends AbstractType
public function reset()
{
$this->choiceLoaders = array();
$this->choiceLoaders = [];
}
}

View File

@ -40,7 +40,7 @@ class EntityType extends DoctrineType
};
$resolver->setNormalizer('query_builder', $queryBuilderNormalizer);
$resolver->setAllowedTypes('query_builder', array('null', 'callable', 'Doctrine\ORM\QueryBuilder'));
$resolver->setAllowedTypes('query_builder', ['null', 'callable', 'Doctrine\ORM\QueryBuilder']);
}
/**
@ -78,10 +78,10 @@ class EntityType extends DoctrineType
*/
public function getQueryBuilderPartsForCachingHash($queryBuilder)
{
return array(
return [
$queryBuilder->getQuery()->getSQL(),
array_map(array($this, 'parameterToArray'), $queryBuilder->getParameters()->toArray()),
);
array_map([$this, 'parameterToArray'], $queryBuilder->getParameters()->toArray()),
];
}
/**
@ -91,6 +91,6 @@ class EntityType extends DoctrineType
*/
private function parameterToArray(Parameter $parameter)
{
return array($parameter->getName(), $parameter->getType(), $parameter->getValue());
return [$parameter->getName(), $parameter->getType(), $parameter->getValue()];
}
}

View File

@ -42,7 +42,7 @@ class DbalLogger implements SQLLogger
}
if (null !== $this->logger) {
$this->log($sql, null === $params ? array() : $this->normalizeParams($params));
$this->log($sql, null === $params ? [] : $this->normalizeParams($params));
}
}

View File

@ -37,7 +37,7 @@ class DoctrineExtractor implements PropertyListExtractorInterface, PropertyTypeE
/**
* {@inheritdoc}
*/
public function getProperties($class, array $context = array())
public function getProperties($class, array $context = [])
{
try {
$metadata = $this->classMetadataFactory->getMetadataFor($class);
@ -63,7 +63,7 @@ class DoctrineExtractor implements PropertyListExtractorInterface, PropertyTypeE
/**
* {@inheritdoc}
*/
public function getTypes($class, $property, array $context = array())
public function getTypes($class, $property, array $context = [])
{
try {
$metadata = $this->classMetadataFactory->getMetadataFor($class);
@ -85,7 +85,7 @@ class DoctrineExtractor implements PropertyListExtractorInterface, PropertyTypeE
$nullable = false;
}
return array(new Type(Type::BUILTIN_TYPE_OBJECT, $nullable, $class));
return [new Type(Type::BUILTIN_TYPE_OBJECT, $nullable, $class)];
}
$collectionKeyType = Type::BUILTIN_TYPE_INT;
@ -112,18 +112,18 @@ class DoctrineExtractor implements PropertyListExtractorInterface, PropertyTypeE
}
}
return array(new Type(
return [new Type(
Type::BUILTIN_TYPE_OBJECT,
false,
'Doctrine\Common\Collections\Collection',
true,
new Type($collectionKeyType),
new Type(Type::BUILTIN_TYPE_OBJECT, false, $class)
));
)];
}
if ($metadata instanceof ClassMetadataInfo && class_exists('Doctrine\ORM\Mapping\Embedded') && isset($metadata->embeddedClasses[$property])) {
return array(new Type(Type::BUILTIN_TYPE_OBJECT, false, $metadata->embeddedClasses[$property]['class']));
return [new Type(Type::BUILTIN_TYPE_OBJECT, false, $metadata->embeddedClasses[$property]['class'])];
}
if ($metadata->hasField($property)) {
@ -136,30 +136,30 @@ class DoctrineExtractor implements PropertyListExtractorInterface, PropertyTypeE
case DBALType::DATETIMETZ:
case 'vardatetime':
case DBALType::TIME:
return array(new Type(Type::BUILTIN_TYPE_OBJECT, $nullable, 'DateTime'));
return [new Type(Type::BUILTIN_TYPE_OBJECT, $nullable, 'DateTime')];
case 'date_immutable':
case 'datetime_immutable':
case 'datetimetz_immutable':
case 'time_immutable':
return array(new Type(Type::BUILTIN_TYPE_OBJECT, $nullable, 'DateTimeImmutable'));
return [new Type(Type::BUILTIN_TYPE_OBJECT, $nullable, 'DateTimeImmutable')];
case 'dateinterval':
return array(new Type(Type::BUILTIN_TYPE_OBJECT, $nullable, 'DateInterval'));
return [new Type(Type::BUILTIN_TYPE_OBJECT, $nullable, 'DateInterval')];
case DBALType::TARRAY:
return array(new Type(Type::BUILTIN_TYPE_ARRAY, $nullable, null, true));
return [new Type(Type::BUILTIN_TYPE_ARRAY, $nullable, null, true)];
case DBALType::SIMPLE_ARRAY:
return array(new Type(Type::BUILTIN_TYPE_ARRAY, $nullable, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_STRING)));
return [new Type(Type::BUILTIN_TYPE_ARRAY, $nullable, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_STRING))];
case DBALType::JSON_ARRAY:
return array(new Type(Type::BUILTIN_TYPE_ARRAY, $nullable, null, true));
return [new Type(Type::BUILTIN_TYPE_ARRAY, $nullable, null, true)];
default:
$builtinType = $this->getPhpType($typeOfField);
return $builtinType ? array(new Type($builtinType, $nullable)) : null;
return $builtinType ? [new Type($builtinType, $nullable)] : null;
}
}
}

View File

@ -53,8 +53,8 @@ class DoctrineTokenProvider implements TokenProviderInterface
// the alias for lastUsed works around case insensitivity in PostgreSQL
$sql = 'SELECT class, username, value, lastUsed AS last_used'
.' FROM rememberme_token WHERE series=:series';
$paramValues = array('series' => $series);
$paramTypes = array('series' => \PDO::PARAM_STR);
$paramValues = ['series' => $series];
$paramTypes = ['series' => \PDO::PARAM_STR];
$stmt = $this->conn->executeQuery($sql, $paramValues, $paramTypes);
$row = $stmt->fetch(\PDO::FETCH_ASSOC);
@ -71,8 +71,8 @@ class DoctrineTokenProvider implements TokenProviderInterface
public function deleteTokenBySeries($series)
{
$sql = 'DELETE FROM rememberme_token WHERE series=:series';
$paramValues = array('series' => $series);
$paramTypes = array('series' => \PDO::PARAM_STR);
$paramValues = ['series' => $series];
$paramTypes = ['series' => \PDO::PARAM_STR];
$this->conn->executeUpdate($sql, $paramValues, $paramTypes);
}
@ -83,16 +83,16 @@ class DoctrineTokenProvider implements TokenProviderInterface
{
$sql = 'UPDATE rememberme_token SET value=:value, lastUsed=:lastUsed'
.' WHERE series=:series';
$paramValues = array(
$paramValues = [
'value' => $tokenValue,
'lastUsed' => $lastUsed,
'series' => $series,
);
$paramTypes = array(
];
$paramTypes = [
'value' => \PDO::PARAM_STR,
'lastUsed' => DoctrineType::DATETIME,
'series' => \PDO::PARAM_STR,
);
];
$updated = $this->conn->executeUpdate($sql, $paramValues, $paramTypes);
if ($updated < 1) {
throw new TokenNotFoundException('No token found.');
@ -107,20 +107,20 @@ class DoctrineTokenProvider implements TokenProviderInterface
$sql = 'INSERT INTO rememberme_token'
.' (class, username, series, value, lastUsed)'
.' VALUES (:class, :username, :series, :value, :lastUsed)';
$paramValues = array(
$paramValues = [
'class' => $token->getClass(),
'username' => $token->getUsername(),
'series' => $token->getSeries(),
'value' => $token->getTokenValue(),
'lastUsed' => $token->getLastUsed(),
);
$paramTypes = array(
];
$paramTypes = [
'class' => \PDO::PARAM_STR,
'username' => \PDO::PARAM_STR,
'series' => \PDO::PARAM_STR,
'value' => \PDO::PARAM_STR,
'lastUsed' => DoctrineType::DATETIME,
);
];
$this->conn->executeUpdate($sql, $paramValues, $paramTypes);
}
}

View File

@ -48,7 +48,7 @@ class EntityUserProvider implements UserProviderInterface
{
$repository = $this->getRepository();
if (null !== $this->property) {
$user = $repository->findOneBy(array($this->property => $username));
$user = $repository->findOneBy([$this->property => $username]);
} else {
if (!$repository instanceof UserLoaderInterface) {
throw new \InvalidArgumentException(sprintf('You must either make the "%s" entity Doctrine Repository ("%s") implement "Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface" or set the "property" option in the corresponding entity provider configuration.', $this->classOrAlias, \get_class($repository)));

View File

@ -42,10 +42,10 @@ class DoctrineTestHelper
$config = self::createTestConfiguration();
}
$params = array(
$params = [
'driver' => 'pdo_sqlite',
'memory' => true,
);
];
return EntityManager::create($params, $config);
}
@ -56,7 +56,7 @@ class DoctrineTestHelper
public static function createTestConfiguration()
{
$config = new Configuration();
$config->setEntityNamespaces(array('SymfonyTestsDoctrine' => 'Symfony\Bridge\Doctrine\Tests\Fixtures'));
$config->setEntityNamespaces(['SymfonyTestsDoctrine' => 'Symfony\Bridge\Doctrine\Tests\Fixtures']);
$config->setAutoGenerateProxyClasses(true);
$config->setProxyDir(\sys_get_temp_dir());
$config->setProxyNamespace('SymfonyTests\Doctrine');

View File

@ -24,7 +24,7 @@ final class TestRepositoryFactory implements RepositoryFactory
/**
* @var ObjectRepository[]
*/
private $repositoryList = array();
private $repositoryList = [];
/**
* {@inheritdoc}

View File

@ -43,15 +43,15 @@ class ContainerAwareEventManagerTest extends TestCase
$this->evm->addEventListener('foo', 'bar');
$this->evm->addEventListener('foo', $listener = new MyListener());
$listeners = array('foo' => array('_service_bar' => 'bar', spl_object_hash($listener) => $listener));
$listeners = ['foo' => ['_service_bar' => 'bar', spl_object_hash($listener) => $listener]];
$this->assertSame($listeners, $this->evm->getListeners());
$this->assertSame($listeners['foo'], $this->evm->getListeners('foo'));
$this->evm->removeEventListener('foo', $listener);
$this->assertSame(array('_service_bar' => 'bar'), $this->evm->getListeners('foo'));
$this->assertSame(['_service_bar' => 'bar'], $this->evm->getListeners('foo'));
$this->evm->removeEventListener('foo', 'bar');
$this->assertSame(array(), $this->evm->getListeners('foo'));
$this->assertSame([], $this->evm->getListeners('foo'));
}
}

View File

@ -44,7 +44,7 @@ class RegisterEventListenersAndSubscribersPassTest extends TestCase
$abstractDefinition = new Definition('stdClass');
$abstractDefinition->setAbstract(true);
$abstractDefinition->addTag('doctrine.event_listener', array('event' => 'test'));
$abstractDefinition->addTag('doctrine.event_listener', ['event' => 'test']);
$container->setDefinition('a', $abstractDefinition);
@ -58,44 +58,44 @@ class RegisterEventListenersAndSubscribersPassTest extends TestCase
$container
->register('a', 'stdClass')
->setPublic(false)
->addTag('doctrine.event_listener', array(
->addTag('doctrine.event_listener', [
'event' => 'bar',
))
->addTag('doctrine.event_listener', array(
])
->addTag('doctrine.event_listener', [
'event' => 'foo',
'priority' => -5,
))
->addTag('doctrine.event_listener', array(
])
->addTag('doctrine.event_listener', [
'event' => 'foo_bar',
'priority' => 3,
'lazy' => true,
))
])
;
$container
->register('b', 'stdClass')
->addTag('doctrine.event_listener', array(
->addTag('doctrine.event_listener', [
'event' => 'foo',
))
])
;
$container
->register('c', 'stdClass')
->addTag('doctrine.event_listener', array(
->addTag('doctrine.event_listener', [
'event' => 'foo_bar',
'priority' => 4,
))
])
;
$this->process($container);
$methodCalls = $container->getDefinition('doctrine.dbal.default_connection.event_manager')->getMethodCalls();
$this->assertEquals(
array(
array('addEventListener', array(array('foo_bar'), new Reference('c'))),
array('addEventListener', array(array('foo_bar'), new Reference('a'))),
array('addEventListener', array(array('bar'), new Reference('a'))),
array('addEventListener', array(array('foo'), new Reference('b'))),
array('addEventListener', array(array('foo'), new Reference('a'))),
),
[
['addEventListener', [['foo_bar'], new Reference('c')]],
['addEventListener', [['foo_bar'], new Reference('a')]],
['addEventListener', [['bar'], new Reference('a')]],
['addEventListener', [['foo'], new Reference('b')]],
['addEventListener', [['foo'], new Reference('a')]],
],
$methodCalls
);
@ -113,42 +113,42 @@ class RegisterEventListenersAndSubscribersPassTest extends TestCase
$container
->register('a', 'stdClass')
->addTag('doctrine.event_listener', array(
->addTag('doctrine.event_listener', [
'event' => 'onFlush',
))
])
;
$container
->register('b', 'stdClass')
->addTag('doctrine.event_listener', array(
->addTag('doctrine.event_listener', [
'event' => 'onFlush',
'connection' => 'default',
))
])
;
$container
->register('c', 'stdClass')
->addTag('doctrine.event_listener', array(
->addTag('doctrine.event_listener', [
'event' => 'onFlush',
'connection' => 'second',
))
])
;
$this->process($container);
$this->assertEquals(
array(
array('addEventListener', array(array('onFlush'), new Reference('a'))),
array('addEventListener', array(array('onFlush'), new Reference('b'))),
),
[
['addEventListener', [['onFlush'], new Reference('a')]],
['addEventListener', [['onFlush'], new Reference('b')]],
],
$container->getDefinition('doctrine.dbal.default_connection.event_manager')->getMethodCalls()
);
$this->assertEquals(
array(
array('addEventListener', array(array('onFlush'), new Reference('a'))),
array('addEventListener', array(array('onFlush'), new Reference('c'))),
),
[
['addEventListener', [['onFlush'], new Reference('a')]],
['addEventListener', [['onFlush'], new Reference('c')]],
],
$container->getDefinition('doctrine.dbal.second_connection.event_manager')->getMethodCalls()
);
}
@ -159,42 +159,42 @@ class RegisterEventListenersAndSubscribersPassTest extends TestCase
$container
->register('a', 'stdClass')
->addTag('doctrine.event_subscriber', array(
->addTag('doctrine.event_subscriber', [
'event' => 'onFlush',
))
])
;
$container
->register('b', 'stdClass')
->addTag('doctrine.event_subscriber', array(
->addTag('doctrine.event_subscriber', [
'event' => 'onFlush',
'connection' => 'default',
))
])
;
$container
->register('c', 'stdClass')
->addTag('doctrine.event_subscriber', array(
->addTag('doctrine.event_subscriber', [
'event' => 'onFlush',
'connection' => 'second',
))
])
;
$this->process($container);
$this->assertEquals(
array(
array('addEventSubscriber', array(new Reference('a'))),
array('addEventSubscriber', array(new Reference('b'))),
),
[
['addEventSubscriber', [new Reference('a')]],
['addEventSubscriber', [new Reference('b')]],
],
$container->getDefinition('doctrine.dbal.default_connection.event_manager')->getMethodCalls()
);
$this->assertEquals(
array(
array('addEventSubscriber', array(new Reference('a'))),
array('addEventSubscriber', array(new Reference('c'))),
),
[
['addEventSubscriber', [new Reference('a')]],
['addEventSubscriber', [new Reference('c')]],
],
$container->getDefinition('doctrine.dbal.second_connection.event_manager')->getMethodCalls()
);
}
@ -209,39 +209,39 @@ class RegisterEventListenersAndSubscribersPassTest extends TestCase
;
$container
->register('b', 'stdClass')
->addTag('doctrine.event_subscriber', array(
->addTag('doctrine.event_subscriber', [
'priority' => 5,
))
])
;
$container
->register('c', 'stdClass')
->addTag('doctrine.event_subscriber', array(
->addTag('doctrine.event_subscriber', [
'priority' => 10,
))
])
;
$container
->register('d', 'stdClass')
->addTag('doctrine.event_subscriber', array(
->addTag('doctrine.event_subscriber', [
'priority' => 10,
))
])
;
$container
->register('e', 'stdClass')
->addTag('doctrine.event_subscriber', array(
->addTag('doctrine.event_subscriber', [
'priority' => 10,
))
])
;
$this->process($container);
$this->assertEquals(
array(
array('addEventSubscriber', array(new Reference('c'))),
array('addEventSubscriber', array(new Reference('d'))),
array('addEventSubscriber', array(new Reference('e'))),
array('addEventSubscriber', array(new Reference('b'))),
array('addEventSubscriber', array(new Reference('a'))),
),
[
['addEventSubscriber', [new Reference('c')]],
['addEventSubscriber', [new Reference('d')]],
['addEventSubscriber', [new Reference('e')]],
['addEventSubscriber', [new Reference('b')]],
['addEventSubscriber', [new Reference('a')]],
],
$container->getDefinition('doctrine.dbal.default_connection.event_manager')->getMethodCalls()
);
}
@ -252,9 +252,9 @@ class RegisterEventListenersAndSubscribersPassTest extends TestCase
$this->process($container);
$this->assertEquals(array(), $container->getDefinition('doctrine.dbal.default_connection.event_manager')->getMethodCalls());
$this->assertEquals([], $container->getDefinition('doctrine.dbal.default_connection.event_manager')->getMethodCalls());
$this->assertEquals(array(), $container->getDefinition('doctrine.dbal.second_connection.event_manager')->getMethodCalls());
$this->assertEquals([], $container->getDefinition('doctrine.dbal.second_connection.event_manager')->getMethodCalls());
}
private function process(ContainerBuilder $container)
@ -267,7 +267,7 @@ class RegisterEventListenersAndSubscribersPassTest extends TestCase
{
$container = new ContainerBuilder();
$connections = array('default' => 'doctrine.dbal.default_connection');
$connections = ['default' => 'doctrine.dbal.default_connection'];
$container->register('doctrine.dbal.default_connection.event_manager', 'stdClass');
$container->register('doctrine.dbal.default_connection', 'stdClass');

View File

@ -16,17 +16,17 @@ class RegisterMappingsPassTest extends TestCase
public function testNoDriverParmeterException()
{
$container = $this->createBuilder();
$this->process($container, array(
$this->process($container, [
'manager.param.one',
'manager.param.two',
));
]);
}
private function process(ContainerBuilder $container, array $managerParamNames)
{
$pass = new ConcreteMappingsPass(
new Definition('\stdClass'),
array(),
[],
$managerParamNames,
'some.%s.metadata_driver'
);

View File

@ -25,7 +25,7 @@ class SingleIntIdEntity
public $name;
/** @Column(type="array", nullable=true) */
public $phoneNumbers = array();
public $phoneNumbers = [];
public function __construct($id, $name)
{

View File

@ -34,17 +34,17 @@ class ORMQueryBuilderLoaderTest extends TestCase
$em = DoctrineTestHelper::createTestEntityManager();
$query = $this->getMockBuilder('QueryMock')
->setMethods(array('setParameter', 'getResult', 'getSql', '_doExecute'))
->setMethods(['setParameter', 'getResult', 'getSql', '_doExecute'])
->getMock();
$query->expects($this->once())
->method('setParameter')
->with('ORMQueryBuilderLoader_getEntitiesByIds_id', array(1, 2), $expectedType)
->with('ORMQueryBuilderLoader_getEntitiesByIds_id', [1, 2], $expectedType)
->willReturn($query);
$qb = $this->getMockBuilder('Doctrine\ORM\QueryBuilder')
->setConstructorArgs(array($em))
->setMethods(array('getQuery'))
->setConstructorArgs([$em])
->setMethods(['getQuery'])
->getMock();
$qb->expects($this->once())
@ -55,7 +55,7 @@ class ORMQueryBuilderLoaderTest extends TestCase
->from($classname, 'e');
$loader = new ORMQueryBuilderLoader($qb);
$loader->getEntitiesByIds('id', array(1, 2));
$loader->getEntitiesByIds('id', [1, 2]);
}
public function testFilterNonIntegerValues()
@ -63,17 +63,17 @@ class ORMQueryBuilderLoaderTest extends TestCase
$em = DoctrineTestHelper::createTestEntityManager();
$query = $this->getMockBuilder('QueryMock')
->setMethods(array('setParameter', 'getResult', 'getSql', '_doExecute'))
->setMethods(['setParameter', 'getResult', 'getSql', '_doExecute'])
->getMock();
$query->expects($this->once())
->method('setParameter')
->with('ORMQueryBuilderLoader_getEntitiesByIds_id', array(1, 2, 3, '9223372036854775808'), Connection::PARAM_INT_ARRAY)
->with('ORMQueryBuilderLoader_getEntitiesByIds_id', [1, 2, 3, '9223372036854775808'], Connection::PARAM_INT_ARRAY)
->willReturn($query);
$qb = $this->getMockBuilder('Doctrine\ORM\QueryBuilder')
->setConstructorArgs(array($em))
->setMethods(array('getQuery'))
->setConstructorArgs([$em])
->setMethods(['getQuery'])
->getMock();
$qb->expects($this->once())
@ -84,7 +84,7 @@ class ORMQueryBuilderLoaderTest extends TestCase
->from('Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity', 'e');
$loader = new ORMQueryBuilderLoader($qb);
$loader->getEntitiesByIds('id', array(1, '', 2, 3, 'foo', '9223372036854775808'));
$loader->getEntitiesByIds('id', [1, '', 2, 3, 'foo', '9223372036854775808']);
}
/**
@ -95,17 +95,17 @@ class ORMQueryBuilderLoaderTest extends TestCase
$em = DoctrineTestHelper::createTestEntityManager();
$query = $this->getMockBuilder('QueryMock')
->setMethods(array('setParameter', 'getResult', 'getSql', '_doExecute'))
->setMethods(['setParameter', 'getResult', 'getSql', '_doExecute'])
->getMock();
$query->expects($this->once())
->method('setParameter')
->with('ORMQueryBuilderLoader_getEntitiesByIds_id', array('71c5fd46-3f16-4abb-bad7-90ac1e654a2d', 'b98e8e11-2897-44df-ad24-d2627eb7f499'), Connection::PARAM_STR_ARRAY)
->with('ORMQueryBuilderLoader_getEntitiesByIds_id', ['71c5fd46-3f16-4abb-bad7-90ac1e654a2d', 'b98e8e11-2897-44df-ad24-d2627eb7f499'], Connection::PARAM_STR_ARRAY)
->willReturn($query);
$qb = $this->getMockBuilder('Doctrine\ORM\QueryBuilder')
->setConstructorArgs(array($em))
->setMethods(array('getQuery'))
->setConstructorArgs([$em])
->setMethods(['getQuery'])
->getMock();
$qb->expects($this->once())
@ -116,7 +116,7 @@ class ORMQueryBuilderLoaderTest extends TestCase
->from($entityClass, 'e');
$loader = new ORMQueryBuilderLoader($qb);
$loader->getEntitiesByIds('id', array('71c5fd46-3f16-4abb-bad7-90ac1e654a2d', '', 'b98e8e11-2897-44df-ad24-d2627eb7f499'));
$loader->getEntitiesByIds('id', ['71c5fd46-3f16-4abb-bad7-90ac1e654a2d', '', 'b98e8e11-2897-44df-ad24-d2627eb7f499']);
}
public function testEmbeddedIdentifierName()
@ -130,17 +130,17 @@ class ORMQueryBuilderLoaderTest extends TestCase
$em = DoctrineTestHelper::createTestEntityManager();
$query = $this->getMockBuilder('QueryMock')
->setMethods(array('setParameter', 'getResult', 'getSql', '_doExecute'))
->setMethods(['setParameter', 'getResult', 'getSql', '_doExecute'])
->getMock();
$query->expects($this->once())
->method('setParameter')
->with('ORMQueryBuilderLoader_getEntitiesByIds_id_value', array(1, 2, 3), Connection::PARAM_INT_ARRAY)
->with('ORMQueryBuilderLoader_getEntitiesByIds_id_value', [1, 2, 3], Connection::PARAM_INT_ARRAY)
->willReturn($query);
$qb = $this->getMockBuilder('Doctrine\ORM\QueryBuilder')
->setConstructorArgs(array($em))
->setMethods(array('getQuery'))
->setConstructorArgs([$em])
->setMethods(['getQuery'])
->getMock();
$qb->expects($this->once())
->method('getQuery')
@ -150,14 +150,14 @@ class ORMQueryBuilderLoaderTest extends TestCase
->from('Symfony\Bridge\Doctrine\Tests\Fixtures\EmbeddedIdentifierEntity', 'e');
$loader = new ORMQueryBuilderLoader($qb);
$loader->getEntitiesByIds('id.value', array(1, '', 2, 3, 'foo'));
$loader->getEntitiesByIds('id.value', [1, '', 2, 3, 'foo']);
}
public function provideGuidEntityClasses()
{
return array(
array('Symfony\Bridge\Doctrine\Tests\Fixtures\GuidIdEntity'),
array('Symfony\Bridge\Doctrine\Tests\Fixtures\UuidIdEntity'),
);
return [
['Symfony\Bridge\Doctrine\Tests\Fixtures\GuidIdEntity'],
['Symfony\Bridge\Doctrine\Tests\Fixtures\UuidIdEntity'],
];
}
}

View File

@ -32,10 +32,10 @@ class CollectionToArrayTransformerTest extends TestCase
public function testTransform()
{
$array = array(
$array = [
2 => 'foo',
3 => 'bar',
);
];
$this->assertSame($array, $this->transformer->transform(new ArrayCollection($array)));
}
@ -49,17 +49,17 @@ class CollectionToArrayTransformerTest extends TestCase
*/
public function testTransformArray()
{
$array = array(
$array = [
2 => 'foo',
3 => 'bar',
);
];
$this->assertSame($array, $this->transformer->transform($array));
}
public function testTransformNull()
{
$this->assertSame(array(), $this->transformer->transform(null));
$this->assertSame([], $this->transformer->transform(null));
}
/**
@ -72,10 +72,10 @@ class CollectionToArrayTransformerTest extends TestCase
public function testReverseTransform()
{
$array = array(
$array = [
2 => 'foo',
3 => 'bar',
);
];
$this->assertEquals(new ArrayCollection($array), $this->transformer->reverseTransform($array));
}

View File

@ -29,54 +29,54 @@ class DoctrineOrmTypeGuesserTest extends TestCase
public function requiredProvider()
{
$return = array();
$return = [];
// Simple field, not nullable
$classMetadata = $this->getMockBuilder('Doctrine\ORM\Mapping\ClassMetadata')->disableOriginalConstructor()->getMock();
$classMetadata->fieldMappings['field'] = true;
$classMetadata->expects($this->once())->method('isNullable')->with('field')->will($this->returnValue(false));
$return[] = array($classMetadata, new ValueGuess(true, Guess::HIGH_CONFIDENCE));
$return[] = [$classMetadata, new ValueGuess(true, Guess::HIGH_CONFIDENCE)];
// Simple field, nullable
$classMetadata = $this->getMockBuilder('Doctrine\ORM\Mapping\ClassMetadata')->disableOriginalConstructor()->getMock();
$classMetadata->fieldMappings['field'] = true;
$classMetadata->expects($this->once())->method('isNullable')->with('field')->will($this->returnValue(true));
$return[] = array($classMetadata, new ValueGuess(false, Guess::MEDIUM_CONFIDENCE));
$return[] = [$classMetadata, new ValueGuess(false, Guess::MEDIUM_CONFIDENCE)];
// One-to-one, nullable (by default)
$classMetadata = $this->getMockBuilder('Doctrine\ORM\Mapping\ClassMetadata')->disableOriginalConstructor()->getMock();
$classMetadata->expects($this->once())->method('isAssociationWithSingleJoinColumn')->with('field')->will($this->returnValue(true));
$mapping = array('joinColumns' => array(array()));
$mapping = ['joinColumns' => [[]]];
$classMetadata->expects($this->once())->method('getAssociationMapping')->with('field')->will($this->returnValue($mapping));
$return[] = array($classMetadata, new ValueGuess(false, Guess::HIGH_CONFIDENCE));
$return[] = [$classMetadata, new ValueGuess(false, Guess::HIGH_CONFIDENCE)];
// One-to-one, nullable (explicit)
$classMetadata = $this->getMockBuilder('Doctrine\ORM\Mapping\ClassMetadata')->disableOriginalConstructor()->getMock();
$classMetadata->expects($this->once())->method('isAssociationWithSingleJoinColumn')->with('field')->will($this->returnValue(true));
$mapping = array('joinColumns' => array(array('nullable' => true)));
$mapping = ['joinColumns' => [['nullable' => true]]];
$classMetadata->expects($this->once())->method('getAssociationMapping')->with('field')->will($this->returnValue($mapping));
$return[] = array($classMetadata, new ValueGuess(false, Guess::HIGH_CONFIDENCE));
$return[] = [$classMetadata, new ValueGuess(false, Guess::HIGH_CONFIDENCE)];
// One-to-one, not nullable
$classMetadata = $this->getMockBuilder('Doctrine\ORM\Mapping\ClassMetadata')->disableOriginalConstructor()->getMock();
$classMetadata->expects($this->once())->method('isAssociationWithSingleJoinColumn')->with('field')->will($this->returnValue(true));
$mapping = array('joinColumns' => array(array('nullable' => false)));
$mapping = ['joinColumns' => [['nullable' => false]]];
$classMetadata->expects($this->once())->method('getAssociationMapping')->with('field')->will($this->returnValue($mapping));
$return[] = array($classMetadata, new ValueGuess(true, Guess::HIGH_CONFIDENCE));
$return[] = [$classMetadata, new ValueGuess(true, Guess::HIGH_CONFIDENCE)];
// One-to-many, no clue
$classMetadata = $this->getMockBuilder('Doctrine\ORM\Mapping\ClassMetadata')->disableOriginalConstructor()->getMock();
$classMetadata->expects($this->once())->method('isAssociationWithSingleJoinColumn')->with('field')->will($this->returnValue(false));
$return[] = array($classMetadata, null);
$return[] = [$classMetadata, null];
return $return;
}
@ -87,7 +87,7 @@ class DoctrineOrmTypeGuesserTest extends TestCase
$em->expects($this->once())->method('getClassMetaData')->with('TestEntity')->will($this->returnValue($classMetadata));
$registry = $this->getMockBuilder('Doctrine\Common\Persistence\ManagerRegistry')->getMock();
$registry->expects($this->once())->method('getManagers')->will($this->returnValue(array($em)));
$registry->expects($this->once())->method('getManagers')->will($this->returnValue([$em]));
return new DoctrineOrmTypeGuesser($registry);
}

View File

@ -42,10 +42,10 @@ class EntityTypePerformanceTest extends FormPerformanceTestCase
->method('getManagerForClass')
->will($this->returnValue($this->em));
return array(
return [
new CoreExtension(),
new DoctrineOrmExtension($manager),
);
];
}
protected function setUp()
@ -55,9 +55,9 @@ class EntityTypePerformanceTest extends FormPerformanceTestCase
parent::setUp();
$schemaTool = new SchemaTool($this->em);
$classes = array(
$classes = [
$this->em->getClassMetadata(self::ENTITY_CLASS),
);
];
try {
$schemaTool->dropSchema($classes);
@ -90,9 +90,9 @@ class EntityTypePerformanceTest extends FormPerformanceTestCase
$this->setMaxRunningTime(1);
for ($i = 0; $i < 40; ++$i) {
$form = $this->factory->create('Symfony\Bridge\Doctrine\Form\Type\EntityType', null, array(
$form = $this->factory->create('Symfony\Bridge\Doctrine\Form\Type\EntityType', null, [
'class' => self::ENTITY_CLASS,
));
]);
// force loading of the choice list
$form->createView();
@ -108,10 +108,10 @@ class EntityTypePerformanceTest extends FormPerformanceTestCase
$this->setMaxRunningTime(1);
for ($i = 0; $i < 40; ++$i) {
$form = $this->factory->create('Symfony\Bridge\Doctrine\Form\Type\EntityType', null, array(
$form = $this->factory->create('Symfony\Bridge\Doctrine\Form\Type\EntityType', null, [
'class' => self::ENTITY_CLASS,
'choices' => $choices,
));
]);
// force loading of the choice list
$form->createView();
@ -127,10 +127,10 @@ class EntityTypePerformanceTest extends FormPerformanceTestCase
$this->setMaxRunningTime(1);
for ($i = 0; $i < 40; ++$i) {
$form = $this->factory->create('Symfony\Bridge\Doctrine\Form\Type\EntityType', null, array(
$form = $this->factory->create('Symfony\Bridge\Doctrine\Form\Type\EntityType', null, [
'class' => self::ENTITY_CLASS,
'preferred_choices' => $choices,
));
]);
// force loading of the choice list
$form->createView();

View File

@ -25,8 +25,8 @@ class DbalLoggerTest extends TestCase
$dbalLogger = $this
->getMockBuilder('Symfony\\Bridge\\Doctrine\\Logger\\DbalLogger')
->setConstructorArgs(array($logger, null))
->setMethods(array('log'))
->setConstructorArgs([$logger, null])
->setMethods(['log'])
->getMock()
;
@ -41,14 +41,14 @@ class DbalLoggerTest extends TestCase
public function getLogFixtures()
{
return array(
array('SQL', null, array()),
array('SQL', array(), array()),
array('SQL', array('foo' => 'bar'), array('foo' => 'bar')),
array('SQL', array('foo' => "\x7F\xFF"), array('foo' => DbalLogger::BINARY_DATA_VALUE)),
array('SQL', array('foo' => "bar\x7F\xFF"), array('foo' => DbalLogger::BINARY_DATA_VALUE)),
array('SQL', array('foo' => ''), array('foo' => '')),
);
return [
['SQL', null, []],
['SQL', [], []],
['SQL', ['foo' => 'bar'], ['foo' => 'bar']],
['SQL', ['foo' => "\x7F\xFF"], ['foo' => DbalLogger::BINARY_DATA_VALUE]],
['SQL', ['foo' => "bar\x7F\xFF"], ['foo' => DbalLogger::BINARY_DATA_VALUE]],
['SQL', ['foo' => ''], ['foo' => '']],
];
}
public function testLogNonUtf8()
@ -57,21 +57,21 @@ class DbalLoggerTest extends TestCase
$dbalLogger = $this
->getMockBuilder('Symfony\\Bridge\\Doctrine\\Logger\\DbalLogger')
->setConstructorArgs(array($logger, null))
->setMethods(array('log'))
->setConstructorArgs([$logger, null])
->setMethods(['log'])
->getMock()
;
$dbalLogger
->expects($this->once())
->method('log')
->with('SQL', array('utf8' => 'foo', 'nonutf8' => DbalLogger::BINARY_DATA_VALUE))
->with('SQL', ['utf8' => 'foo', 'nonutf8' => DbalLogger::BINARY_DATA_VALUE])
;
$dbalLogger->startQuery('SQL', array(
$dbalLogger->startQuery('SQL', [
'utf8' => 'foo',
'nonutf8' => "\x7F\xFF",
));
]);
}
public function testLogNonUtf8Array()
@ -80,29 +80,29 @@ class DbalLoggerTest extends TestCase
$dbalLogger = $this
->getMockBuilder('Symfony\\Bridge\\Doctrine\\Logger\\DbalLogger')
->setConstructorArgs(array($logger, null))
->setMethods(array('log'))
->setConstructorArgs([$logger, null])
->setMethods(['log'])
->getMock()
;
$dbalLogger
->expects($this->once())
->method('log')
->with('SQL', array(
->with('SQL', [
'utf8' => 'foo',
array(
[
'nonutf8' => DbalLogger::BINARY_DATA_VALUE,
),
)
],
]
)
;
$dbalLogger->startQuery('SQL', array(
$dbalLogger->startQuery('SQL', [
'utf8' => 'foo',
array(
[
'nonutf8' => "\x7F\xFF",
),
));
],
]);
}
public function testLogLongString()
@ -111,8 +111,8 @@ class DbalLoggerTest extends TestCase
$dbalLogger = $this
->getMockBuilder('Symfony\\Bridge\\Doctrine\\Logger\\DbalLogger')
->setConstructorArgs(array($logger, null))
->setMethods(array('log'))
->setConstructorArgs([$logger, null])
->setMethods(['log'])
->getMock()
;
@ -124,13 +124,13 @@ class DbalLoggerTest extends TestCase
$dbalLogger
->expects($this->once())
->method('log')
->with('SQL', array('short' => $shortString, 'long' => substr($longString, 0, DbalLogger::MAX_STRING_LENGTH - 6).' [...]'))
->with('SQL', ['short' => $shortString, 'long' => substr($longString, 0, DbalLogger::MAX_STRING_LENGTH - 6).' [...]'])
;
$dbalLogger->startQuery('SQL', array(
$dbalLogger->startQuery('SQL', [
'short' => $shortString,
'long' => $longString,
));
]);
}
public function testLogUTF8LongString()
@ -139,12 +139,12 @@ class DbalLoggerTest extends TestCase
$dbalLogger = $this
->getMockBuilder('Symfony\\Bridge\\Doctrine\\Logger\\DbalLogger')
->setConstructorArgs(array($logger, null))
->setMethods(array('log'))
->setConstructorArgs([$logger, null])
->setMethods(['log'])
->getMock()
;
$testStringArray = array('é', 'á', 'ű', 'ő', 'ú', 'ö', 'ü', 'ó', 'í');
$testStringArray = ['é', 'á', 'ű', 'ő', 'ú', 'ö', 'ü', 'ó', 'í'];
$testStringCount = \count($testStringArray);
$shortString = '';
@ -158,12 +158,12 @@ class DbalLoggerTest extends TestCase
$dbalLogger
->expects($this->once())
->method('log')
->with('SQL', array('short' => $shortString, 'long' => mb_substr($longString, 0, DbalLogger::MAX_STRING_LENGTH - 6, 'UTF-8').' [...]'))
->with('SQL', ['short' => $shortString, 'long' => mb_substr($longString, 0, DbalLogger::MAX_STRING_LENGTH - 6, 'UTF-8').' [...]'])
;
$dbalLogger->startQuery('SQL', array(
$dbalLogger->startQuery('SQL', [
'short' => $shortString,
'long' => $longString,
));
]);
}
}

View File

@ -30,7 +30,7 @@ class ManagerRegistryTest extends TestCase
{
$container = new \LazyServiceProjectServiceContainer();
$registry = new TestManagerRegistry('name', array(), array('defaultManager' => 'foo'), 'defaultConnection', 'defaultManager', 'proxyInterfaceName');
$registry = new TestManagerRegistry('name', [], ['defaultManager' => 'foo'], 'defaultConnection', 'defaultManager', 'proxyInterfaceName');
$registry->setTestContainer($container);
$foo = $container->get('foo');

View File

@ -30,8 +30,8 @@ class DoctrineExtractorTest extends TestCase
protected function setUp()
{
$config = Setup::createAnnotationMetadataConfiguration(array(__DIR__.\DIRECTORY_SEPARATOR.'Fixtures'), true);
$entityManager = EntityManager::create(array('driver' => 'pdo_sqlite'), $config);
$config = Setup::createAnnotationMetadataConfiguration([__DIR__.\DIRECTORY_SEPARATOR.'Fixtures'], true);
$entityManager = EntityManager::create(['driver' => 'pdo_sqlite'], $config);
if (!DBALType::hasType('foo')) {
DBALType::addType('foo', 'Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineFooType');
@ -44,7 +44,7 @@ class DoctrineExtractorTest extends TestCase
public function testGetProperties()
{
$this->assertEquals(
array(
[
'id',
'guid',
'time',
@ -62,7 +62,7 @@ class DoctrineExtractorTest extends TestCase
'bar',
'indexedBar',
'indexedFoo',
),
],
$this->extractor->getProperties('Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineDummy')
);
}
@ -74,10 +74,10 @@ class DoctrineExtractorTest extends TestCase
}
$this->assertEquals(
array(
[
'id',
'embedded',
),
],
$this->extractor->getProperties('Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineWithEmbedded')
);
}
@ -87,7 +87,7 @@ class DoctrineExtractorTest extends TestCase
*/
public function testExtract($property, array $type = null)
{
$this->assertEquals($type, $this->extractor->getTypes('Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineDummy', $property, array()));
$this->assertEquals($type, $this->extractor->getTypes('Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineDummy', $property, []));
}
public function testExtractWithEmbedded()
@ -96,16 +96,16 @@ class DoctrineExtractorTest extends TestCase
$this->markTestSkipped('@Embedded is not available in Doctrine ORM lower than 2.5.');
}
$expectedTypes = array(new Type(
$expectedTypes = [new Type(
Type::BUILTIN_TYPE_OBJECT,
false,
'Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineEmbeddable'
));
)];
$actualTypes = $this->extractor->getTypes(
'Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineWithEmbedded',
'embedded',
array()
[]
);
$this->assertEquals($expectedTypes, $actualTypes);
@ -113,47 +113,47 @@ class DoctrineExtractorTest extends TestCase
public function typesProvider()
{
return array(
array('id', array(new Type(Type::BUILTIN_TYPE_INT))),
array('guid', array(new Type(Type::BUILTIN_TYPE_STRING))),
array('bigint', array(new Type(Type::BUILTIN_TYPE_STRING))),
array('time', array(new Type(Type::BUILTIN_TYPE_OBJECT, false, 'DateTime'))),
array('timeImmutable', array(new Type(Type::BUILTIN_TYPE_OBJECT, false, 'DateTimeImmutable'))),
array('dateInterval', array(new Type(Type::BUILTIN_TYPE_OBJECT, false, 'DateInterval'))),
array('float', array(new Type(Type::BUILTIN_TYPE_FLOAT))),
array('decimal', array(new Type(Type::BUILTIN_TYPE_STRING))),
array('bool', array(new Type(Type::BUILTIN_TYPE_BOOL))),
array('binary', array(new Type(Type::BUILTIN_TYPE_RESOURCE))),
array('json', array(new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true))),
array('foo', array(new Type(Type::BUILTIN_TYPE_OBJECT, true, 'Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineRelation'))),
array('bar', array(new Type(
return [
['id', [new Type(Type::BUILTIN_TYPE_INT)]],
['guid', [new Type(Type::BUILTIN_TYPE_STRING)]],
['bigint', [new Type(Type::BUILTIN_TYPE_STRING)]],
['time', [new Type(Type::BUILTIN_TYPE_OBJECT, false, 'DateTime')]],
['timeImmutable', [new Type(Type::BUILTIN_TYPE_OBJECT, false, 'DateTimeImmutable')]],
['dateInterval', [new Type(Type::BUILTIN_TYPE_OBJECT, false, 'DateInterval')]],
['float', [new Type(Type::BUILTIN_TYPE_FLOAT)]],
['decimal', [new Type(Type::BUILTIN_TYPE_STRING)]],
['bool', [new Type(Type::BUILTIN_TYPE_BOOL)]],
['binary', [new Type(Type::BUILTIN_TYPE_RESOURCE)]],
['json', [new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true)]],
['foo', [new Type(Type::BUILTIN_TYPE_OBJECT, true, 'Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineRelation')]],
['bar', [new Type(
Type::BUILTIN_TYPE_OBJECT,
false,
'Doctrine\Common\Collections\Collection',
true,
new Type(Type::BUILTIN_TYPE_INT),
new Type(Type::BUILTIN_TYPE_OBJECT, false, 'Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineRelation')
))),
array('indexedBar', array(new Type(
)]],
['indexedBar', [new Type(
Type::BUILTIN_TYPE_OBJECT,
false,
'Doctrine\Common\Collections\Collection',
true,
new Type(Type::BUILTIN_TYPE_STRING),
new Type(Type::BUILTIN_TYPE_OBJECT, false, 'Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineRelation')
))),
array('indexedFoo', array(new Type(
)]],
['indexedFoo', [new Type(
Type::BUILTIN_TYPE_OBJECT,
false,
'Doctrine\Common\Collections\Collection',
true,
new Type(Type::BUILTIN_TYPE_STRING),
new Type(Type::BUILTIN_TYPE_OBJECT, false, 'Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineRelation')
))),
array('simpleArray', array(new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_STRING)))),
array('customFoo', null),
array('notMapped', null),
);
)]],
['simpleArray', [new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_STRING))]],
['customFoo', null],
['notMapped', null],
];
}
public function testGetPropertiesCatchException()

View File

@ -38,7 +38,7 @@ class DoctrineFooType extends Type
*/
public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
{
return $platform->getClobTypeDeclarationSQL(array());
return $platform->getClobTypeDeclarationSQL([]);
}
/**

View File

@ -145,7 +145,7 @@ class EntityUserProviderTest extends TestCase
$provider = new EntityUserProvider($this->getManager($em), 'Symfony\Bridge\Doctrine\Tests\Fixtures\User', 'name');
$user2 = $em->getReference('Symfony\Bridge\Doctrine\Tests\Fixtures\User', array('id1' => 1, 'id2' => 1));
$user2 = $em->getReference('Symfony\Bridge\Doctrine\Tests\Fixtures\User', ['id1' => 1, 'id2' => 1]);
$this->assertTrue($provider->supportsClass(\get_class($user2)));
}
@ -196,7 +196,7 @@ class EntityUserProviderTest extends TestCase
private function getObjectManager($repository)
{
$em = $this->getMockBuilder('\Doctrine\Common\Persistence\ObjectManager')
->setMethods(array('getClassMetadata', 'getRepository'))
->setMethods(['getClassMetadata', 'getRepository'])
->getMockForAbstractClass();
$em->expects($this->any())
->method('getRepository')
@ -208,8 +208,8 @@ class EntityUserProviderTest extends TestCase
private function createSchema($em)
{
$schemaTool = new SchemaTool($em);
$schemaTool->createSchema(array(
$schemaTool->createSchema([
$em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\User'),
));
]);
}
}

View File

@ -90,7 +90,7 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
protected function createRepositoryMock()
{
$repository = $this->getMockBuilder('Doctrine\Common\Persistence\ObjectRepository')
->setMethods(array('findByCustom', 'find', 'findAll', 'findOneBy', 'findBy', 'getClassName'))
->setMethods(['findByCustom', 'find', 'findAll', 'findOneBy', 'findBy', 'getClassName'])
->getMock()
;
@ -118,8 +118,8 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
->getMock()
;
$refl = $this->getMockBuilder('Doctrine\Common\Reflection\StaticReflectionProperty')
->setConstructorArgs(array($reflParser, 'property-name'))
->setMethods(array('getValue'))
->setConstructorArgs([$reflParser, 'property-name'])
->setMethods(['getValue'])
->getMock()
;
$refl
@ -127,7 +127,7 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
->method('getValue')
->will($this->returnValue(true))
;
$classMetadata->reflFields = array('name' => $refl);
$classMetadata->reflFields = ['name' => $refl];
$em->expects($this->any())
->method('getClassMetadata')
->will($this->returnValue($classMetadata))
@ -144,7 +144,7 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
private function createSchema(ObjectManager $em)
{
$schemaTool = new SchemaTool($em);
$schemaTool->createSchema(array(
$schemaTool->createSchema([
$em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity'),
$em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdNoToStringEntity'),
$em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\DoubleNameEntity'),
@ -156,7 +156,7 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
$em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\Employee'),
$em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\CompositeObjectNoToStringIdEntity'),
$em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdStringWrapperNameEntity'),
));
]);
}
/**
@ -164,11 +164,11 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
*/
public function testValidateUniqueness()
{
$constraint = new UniqueEntity(array(
$constraint = new UniqueEntity([
'message' => 'myMessage',
'fields' => array('name'),
'fields' => ['name'],
'em' => self::EM_NAME,
));
]);
$entity1 = new SingleIntIdEntity(1, 'Foo');
$entity2 = new SingleIntIdEntity(2, 'Foo');
@ -190,19 +190,19 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
->atPath('property.path.name')
->setParameter('{{ value }}', '"Foo"')
->setInvalidValue($entity2)
->setCause(array($entity1))
->setCause([$entity1])
->setCode(UniqueEntity::NOT_UNIQUE_ERROR)
->assertRaised();
}
public function testValidateCustomErrorPath()
{
$constraint = new UniqueEntity(array(
$constraint = new UniqueEntity([
'message' => 'myMessage',
'fields' => array('name'),
'fields' => ['name'],
'em' => self::EM_NAME,
'errorPath' => 'bar',
));
]);
$entity1 = new SingleIntIdEntity(1, 'Foo');
$entity2 = new SingleIntIdEntity(2, 'Foo');
@ -216,18 +216,18 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
->atPath('property.path.bar')
->setParameter('{{ value }}', '"Foo"')
->setInvalidValue($entity2)
->setCause(array($entity1))
->setCause([$entity1])
->setCode(UniqueEntity::NOT_UNIQUE_ERROR)
->assertRaised();
}
public function testValidateUniquenessWithNull()
{
$constraint = new UniqueEntity(array(
$constraint = new UniqueEntity([
'message' => 'myMessage',
'fields' => array('name'),
'fields' => ['name'],
'em' => self::EM_NAME,
));
]);
$entity1 = new SingleIntIdEntity(1, null);
$entity2 = new SingleIntIdEntity(2, null);
@ -243,12 +243,12 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
public function testValidateUniquenessWithIgnoreNullDisabled()
{
$constraint = new UniqueEntity(array(
$constraint = new UniqueEntity([
'message' => 'myMessage',
'fields' => array('name', 'name2'),
'fields' => ['name', 'name2'],
'em' => self::EM_NAME,
'ignoreNull' => false,
));
]);
$entity1 = new DoubleNameEntity(1, 'Foo', null);
$entity2 = new DoubleNameEntity(2, 'Foo', null);
@ -270,7 +270,7 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
->atPath('property.path.name')
->setParameter('{{ value }}', '"Foo"')
->setInvalidValue('Foo')
->setCause(array($entity1))
->setCause([$entity1])
->setCode(UniqueEntity::NOT_UNIQUE_ERROR)
->assertRaised();
}
@ -280,12 +280,12 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
*/
public function testAllConfiguredFieldsAreCheckedOfBeingMappedByDoctrineWithIgnoreNullEnabled()
{
$constraint = new UniqueEntity(array(
$constraint = new UniqueEntity([
'message' => 'myMessage',
'fields' => array('name', 'name2'),
'fields' => ['name', 'name2'],
'em' => self::EM_NAME,
'ignoreNull' => true,
));
]);
$entity1 = new SingleIntIdEntity(1, null);
@ -294,12 +294,12 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
public function testNoValidationIfFirstFieldIsNullAndNullValuesAreIgnored()
{
$constraint = new UniqueEntity(array(
$constraint = new UniqueEntity([
'message' => 'myMessage',
'fields' => array('name', 'name2'),
'fields' => ['name', 'name2'],
'em' => self::EM_NAME,
'ignoreNull' => true,
));
]);
$entity1 = new DoubleNullableNameEntity(1, null, 'Foo');
$entity2 = new DoubleNullableNameEntity(2, null, 'Foo');
@ -322,12 +322,12 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
public function testValidateUniquenessWithValidCustomErrorPath()
{
$constraint = new UniqueEntity(array(
$constraint = new UniqueEntity([
'message' => 'myMessage',
'fields' => array('name', 'name2'),
'fields' => ['name', 'name2'],
'em' => self::EM_NAME,
'errorPath' => 'name2',
));
]);
$entity1 = new DoubleNameEntity(1, 'Foo', 'Bar');
$entity2 = new DoubleNameEntity(2, 'Foo', 'Bar');
@ -349,24 +349,24 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
->atPath('property.path.name2')
->setParameter('{{ value }}', '"Bar"')
->setInvalidValue('Bar')
->setCause(array($entity1))
->setCause([$entity1])
->setCode(UniqueEntity::NOT_UNIQUE_ERROR)
->assertRaised();
}
public function testValidateUniquenessUsingCustomRepositoryMethod()
{
$constraint = new UniqueEntity(array(
$constraint = new UniqueEntity([
'message' => 'myMessage',
'fields' => array('name'),
'fields' => ['name'],
'em' => self::EM_NAME,
'repositoryMethod' => 'findByCustom',
));
]);
$repository = $this->createRepositoryMock();
$repository->expects($this->once())
->method('findByCustom')
->will($this->returnValue(array()))
->will($this->returnValue([]))
;
$this->em = $this->createEntityManagerMock($repository);
$this->registry = $this->createRegistryMock($this->em);
@ -382,12 +382,12 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
public function testValidateUniquenessWithUnrewoundArray()
{
$constraint = new UniqueEntity(array(
$constraint = new UniqueEntity([
'message' => 'myMessage',
'fields' => array('name'),
'fields' => ['name'],
'em' => self::EM_NAME,
'repositoryMethod' => 'findByCustom',
));
]);
$entity = new SingleIntIdEntity(1, 'foo');
@ -396,9 +396,9 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
->method('findByCustom')
->will(
$this->returnCallback(function () use ($entity) {
$returnValue = array(
$returnValue = [
$entity,
);
];
next($returnValue);
return $returnValue;
@ -420,12 +420,12 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
*/
public function testValidateResultTypes($entity1, $result)
{
$constraint = new UniqueEntity(array(
$constraint = new UniqueEntity([
'message' => 'myMessage',
'fields' => array('name'),
'fields' => ['name'],
'em' => self::EM_NAME,
'repositoryMethod' => 'findByCustom',
));
]);
$repository = $this->createRepositoryMock();
$repository->expects($this->once())
@ -446,20 +446,20 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
{
$entity = new SingleIntIdEntity(1, 'foo');
return array(
array($entity, array($entity)),
array($entity, new \ArrayIterator(array($entity))),
array($entity, new ArrayCollection(array($entity))),
);
return [
[$entity, [$entity]],
[$entity, new \ArrayIterator([$entity])],
[$entity, new ArrayCollection([$entity])],
];
}
public function testAssociatedEntity()
{
$constraint = new UniqueEntity(array(
$constraint = new UniqueEntity([
'message' => 'myMessage',
'fields' => array('single'),
'fields' => ['single'],
'em' => self::EM_NAME,
));
]);
$entity1 = new SingleIntIdEntity(1, 'foo');
$associated = new AssociationEntity();
@ -485,17 +485,17 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
->setParameter('{{ value }}', 'foo')
->setInvalidValue($entity1)
->setCode(UniqueEntity::NOT_UNIQUE_ERROR)
->setCause(array($associated, $associated2))
->setCause([$associated, $associated2])
->assertRaised();
}
public function testValidateUniquenessNotToStringEntityWithAssociatedEntity()
{
$constraint = new UniqueEntity(array(
$constraint = new UniqueEntity([
'message' => 'myMessage',
'fields' => array('single'),
'fields' => ['single'],
'em' => self::EM_NAME,
));
]);
$entity1 = new SingleIntIdNoToStringEntity(1, 'foo');
$associated = new AssociationEntity2();
@ -522,19 +522,19 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
->atPath('property.path.single')
->setParameter('{{ value }}', $expectedValue)
->setInvalidValue($entity1)
->setCause(array($associated, $associated2))
->setCause([$associated, $associated2])
->setCode(UniqueEntity::NOT_UNIQUE_ERROR)
->assertRaised();
}
public function testAssociatedEntityWithNull()
{
$constraint = new UniqueEntity(array(
$constraint = new UniqueEntity([
'message' => 'myMessage',
'fields' => array('single'),
'fields' => ['single'],
'em' => self::EM_NAME,
'ignoreNull' => false,
));
]);
$associated = new AssociationEntity();
$associated->single = null;
@ -552,19 +552,19 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
$repository = $this->createRepositoryMock();
$this->repositoryFactory->setRepository($this->em, 'Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity', $repository);
$constraint = new UniqueEntity(array(
$constraint = new UniqueEntity([
'message' => 'myMessage',
'fields' => array('phoneNumbers'),
'fields' => ['phoneNumbers'],
'em' => self::EM_NAME,
'repositoryMethod' => 'findByCustom',
));
]);
$entity1 = new SingleIntIdEntity(1, 'foo');
$entity1->phoneNumbers[] = 123;
$repository->expects($this->once())
->method('findByCustom')
->will($this->returnValue(array($entity1)))
->will($this->returnValue([$entity1]))
;
$this->em->persist($entity1);
@ -580,8 +580,8 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
$this->buildViolation('myMessage')
->atPath('property.path.phoneNumbers')
->setParameter('{{ value }}', 'array')
->setInvalidValue(array(123))
->setCause(array($entity1))
->setInvalidValue([123])
->setCause([$entity1])
->setCode(UniqueEntity::NOT_UNIQUE_ERROR)
->assertRaised();
}
@ -592,11 +592,11 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
*/
public function testDedicatedEntityManagerNullObject()
{
$constraint = new UniqueEntity(array(
$constraint = new UniqueEntity([
'message' => 'myMessage',
'fields' => array('name'),
'fields' => ['name'],
'em' => self::EM_NAME,
));
]);
$this->em = null;
$this->registry = $this->createRegistryMock($this->em);
@ -614,11 +614,11 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
*/
public function testEntityManagerNullObject()
{
$constraint = new UniqueEntity(array(
$constraint = new UniqueEntity([
'message' => 'myMessage',
'fields' => array('name'),
'fields' => ['name'],
// no "em" option set
));
]);
$this->em = null;
$this->registry = $this->createRegistryMock($this->em);
@ -643,11 +643,11 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
$this->validator = $this->createValidator();
$this->validator->initialize($this->context);
$constraint = new UniqueEntity(array(
$constraint = new UniqueEntity([
'message' => 'myMessage',
'fields' => array('name'),
'fields' => ['name'],
'em' => self::EM_NAME,
));
]);
$entity = new SingleIntIdEntity(1, null);
@ -660,12 +660,12 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
public function testValidateInheritanceUniqueness()
{
$constraint = new UniqueEntity(array(
$constraint = new UniqueEntity([
'message' => 'myMessage',
'fields' => array('name'),
'fields' => ['name'],
'em' => self::EM_NAME,
'entityClass' => 'Symfony\Bridge\Doctrine\Tests\Fixtures\Person',
));
]);
$entity1 = new Person(1, 'Foo');
$entity2 = new Employee(2, 'Foo');
@ -687,8 +687,8 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
->atPath('property.path.name')
->setInvalidValue('Foo')
->setCode('23bd9dbf-6b9b-41cd-a99e-4844bcf3077f')
->setCause(array($entity1))
->setParameters(array('{{ value }}' => '"Foo"'))
->setCause([$entity1])
->setParameters(['{{ value }}' => '"Foo"'])
->assertRaised();
}
@ -698,12 +698,12 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
*/
public function testInvalidateRepositoryForInheritance()
{
$constraint = new UniqueEntity(array(
$constraint = new UniqueEntity([
'message' => 'myMessage',
'fields' => array('name'),
'fields' => ['name'],
'em' => self::EM_NAME,
'entityClass' => 'Symfony\Bridge\Doctrine\Tests\Fixtures\SingleStringIdEntity',
));
]);
$entity = new Person(1, 'Foo');
$this->validator->validate($entity, $constraint);
@ -711,11 +711,11 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
public function testValidateUniquenessWithCompositeObjectNoToStringIdEntity()
{
$constraint = new UniqueEntity(array(
$constraint = new UniqueEntity([
'message' => 'myMessage',
'fields' => array('objectOne', 'objectTwo'),
'fields' => ['objectOne', 'objectTwo'],
'em' => self::EM_NAME,
));
]);
$objectOne = new SingleIntIdNoToStringEntity(1, 'foo');
$objectTwo = new SingleIntIdNoToStringEntity(2, 'bar');
@ -739,18 +739,18 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
->atPath('property.path.objectOne')
->setParameter('{{ value }}', $expectedValue)
->setInvalidValue($objectOne)
->setCause(array($entity))
->setCause([$entity])
->setCode(UniqueEntity::NOT_UNIQUE_ERROR)
->assertRaised();
}
public function testValidateUniquenessWithCustomDoctrineTypeValue()
{
$constraint = new UniqueEntity(array(
$constraint = new UniqueEntity([
'message' => 'myMessage',
'fields' => array('name'),
'fields' => ['name'],
'em' => self::EM_NAME,
));
]);
$existingEntity = new SingleIntIdStringWrapperNameEntity(1, new StringWrapper('foo'));
@ -767,7 +767,7 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
->atPath('property.path.name')
->setParameter('{{ value }}', $expectedValue)
->setInvalidValue($existingEntity->name)
->setCause(array($existingEntity))
->setCause([$existingEntity])
->setCode(UniqueEntity::NOT_UNIQUE_ERROR)
->assertRaised();
}
@ -777,11 +777,11 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
*/
public function testValidateUniquenessCause()
{
$constraint = new UniqueEntity(array(
$constraint = new UniqueEntity([
'message' => 'myMessage',
'fields' => array('name'),
'fields' => ['name'],
'em' => self::EM_NAME,
));
]);
$entity1 = new SingleIntIdEntity(1, 'Foo');
$entity2 = new SingleIntIdEntity(2, 'Foo');
@ -803,7 +803,7 @@ class UniqueEntityValidatorTest extends ConstraintValidatorTestCase
->atPath('property.path.name')
->setParameter('{{ value }}', '"Foo"')
->setInvalidValue($entity2)
->setCause(array($entity1))
->setCause([$entity1])
->setCode(UniqueEntity::NOT_UNIQUE_ERROR)
->assertRaised();
}

View File

@ -30,17 +30,17 @@ class UniqueEntity extends Constraint
public $em = null;
public $entityClass = null;
public $repositoryMethod = 'findBy';
public $fields = array();
public $fields = [];
public $errorPath = null;
public $ignoreNull = true;
protected static $errorNames = array(
protected static $errorNames = [
self::NOT_UNIQUE_ERROR => 'NOT_UNIQUE_ERROR',
);
];
public function getRequiredOptions()
{
return array('fields');
return ['fields'];
}
/**

View File

@ -81,7 +81,7 @@ class UniqueEntityValidator extends ConstraintValidator
$class = $em->getClassMetadata(\get_class($entity));
/* @var $class \Doctrine\Common\Persistence\Mapping\ClassMetadata */
$criteria = array();
$criteria = [];
$hasNullValue = false;
foreach ($fields as $fieldName) {
@ -149,15 +149,15 @@ class UniqueEntityValidator extends ConstraintValidator
if ($result instanceof \Iterator) {
$result->rewind();
if ($result instanceof \Countable && 1 < \count($result)) {
$result = array($result->current(), $result->current());
$result = [$result->current(), $result->current()];
} else {
$result = $result->current();
$result = null === $result ? array() : array($result);
$result = null === $result ? [] : [$result];
}
} elseif (\is_array($result)) {
reset($result);
} else {
$result = null === $result ? array() : array($result);
$result = null === $result ? [] : [$result];
}
/* If no entity matched the query criteria or a single entity matched,
@ -197,7 +197,7 @@ class UniqueEntityValidator extends ConstraintValidator
} else {
// this case might happen if the non unique column has a custom doctrine type and its value is an object
// in which case we cannot get any identifiers for it
$identifiers = array();
$identifiers = [];
}
} else {
$identifiers = $class->getIdentifierValues($value);

View File

@ -22,7 +22,7 @@ use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
*/
class ChromePhpHandler extends BaseChromePhpHandler
{
private $headers = array();
private $headers = [];
/**
* @var Response
@ -40,7 +40,7 @@ class ChromePhpHandler extends BaseChromePhpHandler
if (!preg_match(static::USER_AGENT_REGEX, $event->getRequest()->headers->get('User-Agent'))) {
$this->sendHeaders = false;
$this->headers = array();
$this->headers = [];
return;
}
@ -49,7 +49,7 @@ class ChromePhpHandler extends BaseChromePhpHandler
foreach ($this->headers as $header => $content) {
$this->response->headers->set($header, $content);
}
$this->headers = array();
$this->headers = [];
}
/**

View File

@ -22,7 +22,7 @@ use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
*/
class FirePHPHandler extends BaseFirePHPHandler
{
private $headers = array();
private $headers = [];
/**
* @var Response
@ -42,7 +42,7 @@ class FirePHPHandler extends BaseFirePHPHandler
if (!preg_match('{\bFirePHP/\d+\.\d+\b}', $request->headers->get('User-Agent'))
&& !$request->headers->has('X-FirePHP-Version')) {
self::$sendHeaders = false;
$this->headers = array();
$this->headers = [];
return;
}
@ -51,7 +51,7 @@ class FirePHPHandler extends BaseFirePHPHandler
foreach ($this->headers as $header => $content) {
$this->response->headers->set($header, $content);
}
$this->headers = array();
$this->headers = [];
}
/**

View File

@ -31,7 +31,7 @@ class Logger extends BaseLogger implements DebugLoggerInterface
return \call_user_func_array(array($logger, 'getLogs'), \func_get_args());
}
return array();
return [];
}
/**

View File

@ -31,11 +31,11 @@ class TokenProcessor
{
$records['extra']['token'] = null;
if (null !== $token = $this->tokenStorage->getToken()) {
$records['extra']['token'] = array(
$records['extra']['token'] = [
'username' => $token->getUsername(),
'authenticated' => $token->isAuthenticated(),
'roles' => array_map(function ($role) { return $role->getRole(); }, $token->getRoles()),
);
];
}
return $records;

View File

@ -26,7 +26,7 @@ class WebProcessor extends BaseWebProcessor implements EventSubscriberInterface
public function __construct(array $extraFields = null)
{
// Pass an empty array as the default null value would access $_SERVER
parent::__construct(array(), $extraFields);
parent::__construct([], $extraFields);
}
public function onKernelRequest(GetResponseEvent $event)

View File

@ -38,13 +38,13 @@ class ConsoleHandlerTest extends TestCase
public function testIsHandling()
{
$handler = new ConsoleHandler();
$this->assertFalse($handler->isHandling(array()), '->isHandling returns false when no output is set');
$this->assertFalse($handler->isHandling([]), '->isHandling returns false when no output is set');
}
/**
* @dataProvider provideVerbosityMappingTests
*/
public function testVerbosityMapping($verbosity, $level, $isHandling, array $map = array())
public function testVerbosityMapping($verbosity, $level, $isHandling, array $map = [])
{
$output = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface')->getMock();
$output
@ -53,7 +53,7 @@ class ConsoleHandlerTest extends TestCase
->will($this->returnValue($verbosity))
;
$handler = new ConsoleHandler($output, true, $map);
$this->assertSame($isHandling, $handler->isHandling(array('level' => $level)),
$this->assertSame($isHandling, $handler->isHandling(['level' => $level]),
'->isHandling returns correct value depending on console verbosity and log level'
);
@ -61,7 +61,7 @@ class ConsoleHandlerTest extends TestCase
$levelName = Logger::getLevelName($level);
$levelName = sprintf('%-9s', $levelName);
$realOutput = $this->getMockBuilder('Symfony\Component\Console\Output\Output')->setMethods(array('doWrite'))->getMock();
$realOutput = $this->getMockBuilder('Symfony\Component\Console\Output\Output')->setMethods(['doWrite'])->getMock();
$realOutput->setVerbosity($verbosity);
if ($realOutput->isDebug()) {
$log = "16:21:54 $levelName [app] My info message\n";
@ -74,38 +74,38 @@ class ConsoleHandlerTest extends TestCase
->with($log, false);
$handler = new ConsoleHandler($realOutput, true, $map);
$infoRecord = array(
$infoRecord = [
'message' => 'My info message',
'context' => array(),
'context' => [],
'level' => $level,
'level_name' => Logger::getLevelName($level),
'channel' => 'app',
'datetime' => new \DateTime('2013-05-29 16:21:54'),
'extra' => array(),
);
'extra' => [],
];
$this->assertFalse($handler->handle($infoRecord), 'The handler finished handling the log.');
}
public function provideVerbosityMappingTests()
{
return array(
array(OutputInterface::VERBOSITY_QUIET, Logger::ERROR, true),
array(OutputInterface::VERBOSITY_QUIET, Logger::WARNING, false),
array(OutputInterface::VERBOSITY_NORMAL, Logger::WARNING, true),
array(OutputInterface::VERBOSITY_NORMAL, Logger::NOTICE, false),
array(OutputInterface::VERBOSITY_VERBOSE, Logger::NOTICE, true),
array(OutputInterface::VERBOSITY_VERBOSE, Logger::INFO, false),
array(OutputInterface::VERBOSITY_VERY_VERBOSE, Logger::INFO, true),
array(OutputInterface::VERBOSITY_VERY_VERBOSE, Logger::DEBUG, false),
array(OutputInterface::VERBOSITY_DEBUG, Logger::DEBUG, true),
array(OutputInterface::VERBOSITY_DEBUG, Logger::EMERGENCY, true),
array(OutputInterface::VERBOSITY_NORMAL, Logger::NOTICE, true, array(
return [
[OutputInterface::VERBOSITY_QUIET, Logger::ERROR, true],
[OutputInterface::VERBOSITY_QUIET, Logger::WARNING, false],
[OutputInterface::VERBOSITY_NORMAL, Logger::WARNING, true],
[OutputInterface::VERBOSITY_NORMAL, Logger::NOTICE, false],
[OutputInterface::VERBOSITY_VERBOSE, Logger::NOTICE, true],
[OutputInterface::VERBOSITY_VERBOSE, Logger::INFO, false],
[OutputInterface::VERBOSITY_VERY_VERBOSE, Logger::INFO, true],
[OutputInterface::VERBOSITY_VERY_VERBOSE, Logger::DEBUG, false],
[OutputInterface::VERBOSITY_DEBUG, Logger::DEBUG, true],
[OutputInterface::VERBOSITY_DEBUG, Logger::EMERGENCY, true],
[OutputInterface::VERBOSITY_NORMAL, Logger::NOTICE, true, [
OutputInterface::VERBOSITY_NORMAL => Logger::NOTICE,
)),
array(OutputInterface::VERBOSITY_DEBUG, Logger::NOTICE, true, array(
]],
[OutputInterface::VERBOSITY_DEBUG, Logger::NOTICE, true, [
OutputInterface::VERBOSITY_NORMAL => Logger::NOTICE,
)),
);
]],
];
}
public function testVerbosityChanged()
@ -122,10 +122,10 @@ class ConsoleHandlerTest extends TestCase
->will($this->returnValue(OutputInterface::VERBOSITY_DEBUG))
;
$handler = new ConsoleHandler($output);
$this->assertFalse($handler->isHandling(array('level' => Logger::NOTICE)),
$this->assertFalse($handler->isHandling(['level' => Logger::NOTICE]),
'when verbosity is set to quiet, the handler does not handle the log'
);
$this->assertTrue($handler->isHandling(array('level' => Logger::NOTICE)),
$this->assertTrue($handler->isHandling(['level' => Logger::NOTICE]),
'since the verbosity of the output increased externally, the handler is now handling the log'
);
}
@ -155,15 +155,15 @@ class ConsoleHandlerTest extends TestCase
$handler = new ConsoleHandler(null, false);
$handler->setOutput($output);
$infoRecord = array(
$infoRecord = [
'message' => 'My info message',
'context' => array(),
'context' => [],
'level' => Logger::INFO,
'level_name' => Logger::getLevelName(Logger::INFO),
'channel' => 'app',
'datetime' => new \DateTime('2013-05-29 16:21:54'),
'extra' => array(),
);
'extra' => [],
];
$this->assertTrue($handler->handle($infoRecord), 'The handler finished handling the log as bubble is false.');
}

View File

@ -28,28 +28,28 @@ class NotFoundActivationStrategyTest extends TestCase
$requestStack = new RequestStack();
$requestStack->push(Request::create($url));
$strategy = new NotFoundActivationStrategy($requestStack, array('^/foo', 'bar'), Logger::WARNING);
$strategy = new NotFoundActivationStrategy($requestStack, ['^/foo', 'bar'], Logger::WARNING);
$this->assertEquals($expected, $strategy->isHandlerActivated($record));
}
public function isActivatedProvider()
{
return array(
array('/test', array('level' => Logger::DEBUG), false),
array('/foo', array('level' => Logger::DEBUG, 'context' => $this->getContextException(404)), false),
array('/baz/bar', array('level' => Logger::ERROR, 'context' => $this->getContextException(404)), false),
array('/foo', array('level' => Logger::ERROR, 'context' => $this->getContextException(404)), false),
array('/foo', array('level' => Logger::ERROR, 'context' => $this->getContextException(500)), true),
return [
['/test', ['level' => Logger::DEBUG], false],
['/foo', ['level' => Logger::DEBUG, 'context' => $this->getContextException(404)], false],
['/baz/bar', ['level' => Logger::ERROR, 'context' => $this->getContextException(404)], false],
['/foo', ['level' => Logger::ERROR, 'context' => $this->getContextException(404)], false],
['/foo', ['level' => Logger::ERROR, 'context' => $this->getContextException(500)], true],
array('/test', array('level' => Logger::ERROR), true),
array('/baz', array('level' => Logger::ERROR, 'context' => $this->getContextException(404)), true),
array('/baz', array('level' => Logger::ERROR, 'context' => $this->getContextException(500)), true),
);
['/test', ['level' => Logger::ERROR], true],
['/baz', ['level' => Logger::ERROR, 'context' => $this->getContextException(404)], true],
['/baz', ['level' => Logger::ERROR, 'context' => $this->getContextException(500)], true],
];
}
protected function getContextException($code)
{
return array('exception' => new HttpException($code));
return ['exception' => new HttpException($code)];
}
}

View File

@ -25,12 +25,12 @@ class TokenProcessorTest extends TestCase
{
public function testProcessor()
{
$token = new UsernamePasswordToken('user', 'password', 'provider', array('ROLE_USER'));
$token = new UsernamePasswordToken('user', 'password', 'provider', ['ROLE_USER']);
$tokenStorage = $this->getMockBuilder(TokenStorageInterface::class)->getMock();
$tokenStorage->method('getToken')->willReturn($token);
$processor = new TokenProcessor($tokenStorage);
$record = array('extra' => array());
$record = ['extra' => []];
$record = $processor($record);
$this->assertArrayHasKey('token', $record['extra']);

View File

@ -73,7 +73,7 @@ class ClockMock
{
$self = \get_called_class();
$mockedNs = array(substr($class, 0, strrpos($class, '\\')));
$mockedNs = [substr($class, 0, strrpos($class, '\\'))];
if (0 < strpos($class, '\\Tests\\')) {
$ns = str_replace('\\Tests\\', '\\', $class);
$mockedNs[] = substr($ns, 0, strrpos($ns, '\\'));

View File

@ -54,9 +54,9 @@ class DeprecationErrorHandler
if (false === $mode) {
$mode = getenv('SYMFONY_DEPRECATIONS_HELPER');
}
if (DeprecationErrorHandler::MODE_DISABLED !== $mode
&& DeprecationErrorHandler::MODE_WEAK !== $mode
&& DeprecationErrorHandler::MODE_WEAK_VENDORS !== $mode
if (self::MODE_DISABLED !== $mode
&& self::MODE_WEAK !== $mode
&& self::MODE_WEAK_VENDORS !== $mode
&& (!isset($mode[0]) || '/' !== $mode[0])
) {
$mode = preg_match('/^[1-9][0-9]*$/', $mode) ? (int) $mode : 0;
@ -92,21 +92,21 @@ class DeprecationErrorHandler
return false;
};
$deprecations = array(
$deprecations = [
'unsilencedCount' => 0,
'remainingCount' => 0,
'legacyCount' => 0,
'otherCount' => 0,
'remaining vendorCount' => 0,
'unsilenced' => array(),
'remaining' => array(),
'legacy' => array(),
'other' => array(),
'remaining vendor' => array(),
);
$deprecationHandler = function ($type, $msg, $file, $line, $context = array()) use (&$deprecations, $getMode, $UtilPrefix, $inVendors) {
'unsilenced' => [],
'remaining' => [],
'legacy' => [],
'other' => [],
'remaining vendor' => [],
];
$deprecationHandler = function ($type, $msg, $file, $line, $context = []) use (&$deprecations, $getMode, $UtilPrefix, $inVendors) {
$mode = $getMode();
if ((E_USER_DEPRECATED !== $type && E_DEPRECATED !== $type) || DeprecationErrorHandler::MODE_DISABLED === $mode) {
if ((E_USER_DEPRECATED !== $type && E_DEPRECATED !== $type) || self::MODE_DISABLED === $mode) {
$ErrorHandler = $UtilPrefix.'ErrorHandler';
return $ErrorHandler::handleError($type, $msg, $file, $line, $context);
@ -114,7 +114,7 @@ class DeprecationErrorHandler
$trace = debug_backtrace();
$group = 'other';
$isVendor = DeprecationErrorHandler::MODE_WEAK_VENDORS === $mode && $inVendors($file);
$isVendor = self::MODE_WEAK_VENDORS === $mode && $inVendors($file);
$i = \count($trace);
while (1 < $i && (!isset($trace[--$i]['class']) || ('ReflectionMethod' === $trace[$i]['class'] || 0 === strpos($trace[$i]['class'], 'PHPUnit_') || 0 === strpos($trace[$i]['class'], 'PHPUnit\\')))) {
@ -131,7 +131,7 @@ class DeprecationErrorHandler
// \Symfony\Bridge\PhpUnit\Legacy\SymfonyTestsListenerTrait::endTest()
// then we need to use the serialized information to determine
// if the error has been triggered from vendor code.
$isVendor = DeprecationErrorHandler::MODE_WEAK_VENDORS === $mode && isset($parsedMsg['triggering_file']) && $inVendors($parsedMsg['triggering_file']);
$isVendor = self::MODE_WEAK_VENDORS === $mode && isset($parsedMsg['triggering_file']) && $inVendors($parsedMsg['triggering_file']);
} else {
$class = isset($trace[$i]['object']) ? \get_class($trace[$i]['object']) : $trace[$i]['class'];
$method = $trace[$i]['function'];
@ -168,13 +168,13 @@ class DeprecationErrorHandler
exit(1);
}
if ('legacy' !== $group && DeprecationErrorHandler::MODE_WEAK !== $mode) {
if ('legacy' !== $group && self::MODE_WEAK !== $mode) {
$ref = &$deprecations[$group][$msg]['count'];
++$ref;
$ref = &$deprecations[$group][$msg][$class.'::'.$method];
++$ref;
}
} elseif (DeprecationErrorHandler::MODE_WEAK !== $mode) {
} elseif (self::MODE_WEAK !== $mode) {
$ref = &$deprecations[$group][$msg]['count'];
++$ref;
}
@ -184,7 +184,7 @@ class DeprecationErrorHandler
if (null !== $oldErrorHandler) {
restore_error_handler();
if (array($UtilPrefix.'ErrorHandler', 'handleError') === $oldErrorHandler) {
if ([$UtilPrefix.'ErrorHandler', 'handleError'] === $oldErrorHandler) {
restore_error_handler();
self::register($mode);
}
@ -207,7 +207,7 @@ class DeprecationErrorHandler
$currErrorHandler = set_error_handler('var_dump');
restore_error_handler();
if (DeprecationErrorHandler::MODE_WEAK === $mode) {
if (self::MODE_WEAK === $mode) {
$colorize = function ($str) { return $str; };
}
if ($currErrorHandler !== $deprecationHandler) {
@ -218,8 +218,8 @@ class DeprecationErrorHandler
return $b['count'] - $a['count'];
};
$groups = array('unsilenced', 'remaining');
if (DeprecationErrorHandler::MODE_WEAK_VENDORS === $mode) {
$groups = ['unsilenced', 'remaining'];
if (self::MODE_WEAK_VENDORS === $mode) {
$groups[] = 'remaining vendor';
}
array_push($groups, 'legacy', 'other');
@ -255,11 +255,11 @@ class DeprecationErrorHandler
$displayDeprecations($deprecations);
// store failing status
$isFailing = DeprecationErrorHandler::MODE_WEAK !== $mode && $mode < $deprecations['unsilencedCount'] + $deprecations['remainingCount'] + $deprecations['otherCount'];
$isFailing = self::MODE_WEAK !== $mode && $mode < $deprecations['unsilencedCount'] + $deprecations['remainingCount'] + $deprecations['otherCount'];
// reset deprecations array
foreach ($deprecations as $group => $arrayOrInt) {
$deprecations[$group] = \is_int($arrayOrInt) ? 0 : array();
$deprecations[$group] = \is_int($arrayOrInt) ? 0 : [];
}
register_shutdown_function(function () use (&$deprecations, $isFailing, $displayDeprecations, $mode) {
@ -270,7 +270,7 @@ class DeprecationErrorHandler
}
}
$displayDeprecations($deprecations);
if ($isFailing || DeprecationErrorHandler::MODE_WEAK !== $mode && $mode < $deprecations['unsilencedCount'] + $deprecations['remainingCount'] + $deprecations['otherCount']) {
if ($isFailing || self::MODE_WEAK !== $mode && $mode < $deprecations['unsilencedCount'] + $deprecations['remainingCount'] + $deprecations['otherCount']) {
exit(1);
}
});
@ -280,8 +280,8 @@ class DeprecationErrorHandler
public static function collectDeprecations($outputFile)
{
$deprecations = array();
$previousErrorHandler = set_error_handler(function ($type, $msg, $file, $line, $context = array()) use (&$deprecations, &$previousErrorHandler) {
$deprecations = [];
$previousErrorHandler = set_error_handler(function ($type, $msg, $file, $line, $context = []) use (&$deprecations, &$previousErrorHandler) {
if (E_USER_DEPRECATED !== $type && E_DEPRECATED !== $type) {
if ($previousErrorHandler) {
return $previousErrorHandler($type, $msg, $file, $line, $context);
@ -293,7 +293,7 @@ class DeprecationErrorHandler
return $ErrorHandler::handleError($type, $msg, $file, $line, $context);
}
$deprecations[] = array(error_reporting(), $msg, $file);
$deprecations[] = [error_reporting(), $msg, $file];
});
register_shutdown_function(function () use ($outputFile, &$deprecations) {

View File

@ -16,8 +16,8 @@ namespace Symfony\Bridge\PhpUnit;
*/
class DnsMock
{
private static $hosts = array();
private static $dnsTypes = array(
private static $hosts = [];
private static $dnsTypes = [
'A' => DNS_A,
'MX' => DNS_MX,
'NS' => DNS_NS,
@ -30,7 +30,7 @@ class DnsMock
'NAPTR' => DNS_NAPTR,
'TXT' => DNS_TXT,
'HINFO' => DNS_HINFO,
);
];
/**
* Configures the mock values for DNS queries.
@ -68,7 +68,7 @@ class DnsMock
if (!self::$hosts) {
return \getmxrr($hostname, $mxhosts, $weight);
}
$mxhosts = $weight = array();
$mxhosts = $weight = [];
if (isset(self::$hosts[$hostname])) {
foreach (self::$hosts[$hostname] as $record) {
@ -125,7 +125,7 @@ class DnsMock
$ips = false;
if (isset(self::$hosts[$hostname])) {
$ips = array();
$ips = [];
foreach (self::$hosts[$hostname] as $record) {
if ('A' === $record['type']) {
@ -149,11 +149,11 @@ class DnsMock
if (DNS_ANY === $type) {
$type = DNS_ALL;
}
$records = array();
$records = [];
foreach (self::$hosts[$hostname] as $record) {
if (isset(self::$dnsTypes[$record['type']]) && (self::$dnsTypes[$record['type']] & $type)) {
$records[] = array_merge(array('host' => $hostname, 'class' => 'IN', 'ttl' => 1, 'type' => $record['type']), $record);
$records[] = array_merge(['host' => $hostname, 'class' => 'IN', 'ttl' => 1, 'type' => $record['type']], $record);
}
}
}
@ -165,7 +165,7 @@ class DnsMock
{
$self = \get_called_class();
$mockedNs = array(substr($class, 0, strrpos($class, '\\')));
$mockedNs = [substr($class, 0, strrpos($class, '\\'))];
if (0 < strpos($class, '\\Tests\\')) {
$ns = str_replace('\\Tests\\', '\\', $class);
$mockedNs[] = substr($ns, 0, strrpos($ns, '\\'));

View File

@ -31,7 +31,7 @@ class CoverageListenerTrait
{
$this->sutFqcnResolver = $sutFqcnResolver;
$this->warningOnSutNotFound = $warningOnSutNotFound;
$this->warnings = array();
$this->warnings = [];
}
public function startTest($test)
@ -42,7 +42,7 @@ class CoverageListenerTrait
$annotations = $test->getAnnotations();
$ignoredAnnotations = array('covers', 'coversDefaultClass', 'coversNothing');
$ignoredAnnotations = ['covers', 'coversDefaultClass', 'coversNothing'];
foreach ($ignoredAnnotations as $annotation) {
if (isset($annotations['class'][$annotation]) || isset($annotations['method'][$annotation])) {
@ -74,11 +74,11 @@ class CoverageListenerTrait
$r->setAccessible(true);
$cache = $r->getValue();
$cache = array_replace_recursive($cache, array(
\get_class($test) => array(
'covers' => array($sutFqcn),
),
));
$cache = array_replace_recursive($cache, [
\get_class($test) => [
'covers' => [$sutFqcn],
],
]);
$r->setValue($testClass, $cache);
}

View File

@ -22,7 +22,7 @@ class SymfonyTestsListenerForV5 extends \PHPUnit_Framework_BaseTestListener
{
private $trait;
public function __construct(array $mockedNamespaces = array())
public function __construct(array $mockedNamespaces = [])
{
$this->trait = new SymfonyTestsListenerTrait($mockedNamespaces);
}

View File

@ -27,7 +27,7 @@ class SymfonyTestsListenerForV6 extends BaseTestListener
{
private $trait;
public function __construct(array $mockedNamespaces = array())
public function __construct(array $mockedNamespaces = [])
{
$this->trait = new SymfonyTestsListenerTrait($mockedNamespaces);
}

View File

@ -30,7 +30,7 @@ class SymfonyTestsListenerForV7 implements TestListener
private $trait;
public function __construct(array $mockedNamespaces = array())
public function __construct(array $mockedNamespaces = [])
{
$this->trait = new SymfonyTestsListenerTrait($mockedNamespaces);
}

View File

@ -31,10 +31,10 @@ class SymfonyTestsListenerTrait
private static $globallyEnabled = false;
private $state = -1;
private $skippedFile = false;
private $wasSkipped = array();
private $isSkipped = array();
private $expectedDeprecations = array();
private $gatheredDeprecations = array();
private $wasSkipped = [];
private $isSkipped = [];
private $expectedDeprecations = [];
private $gatheredDeprecations = [];
private $previousErrorHandler;
private $testsWithWarnings;
private $reportUselessTests;
@ -44,7 +44,7 @@ class SymfonyTestsListenerTrait
/**
* @param array $mockedNamespaces List of namespaces, indexed by mocked features (time-sensitive or dns-sensitive)
*/
public function __construct(array $mockedNamespaces = array())
public function __construct(array $mockedNamespaces = [])
{
if (class_exists('PHPUnit_Util_Blacklist')) {
\PHPUnit_Util_Blacklist::$blacklistedClassNames['\Symfony\Bridge\PhpUnit\Legacy\SymfonyTestsListenerTrait'] = 2;
@ -54,7 +54,7 @@ class SymfonyTestsListenerTrait
foreach ($mockedNamespaces as $type => $namespaces) {
if (!\is_array($namespaces)) {
$namespaces = array($namespaces);
$namespaces = [$namespaces];
}
if ('time-sensitive' === $type) {
foreach ($namespaces as $ns) {
@ -95,7 +95,7 @@ class SymfonyTestsListenerTrait
$Test = 'PHPUnit\Util\Test';
}
$suiteName = $suite->getName();
$this->testsWithWarnings = array();
$this->testsWithWarnings = [];
foreach ($suite->tests() as $test) {
if (!($test instanceof \PHPUnit\Framework\TestCase || $test instanceof TestCase)) {
@ -126,11 +126,11 @@ class SymfonyTestsListenerTrait
if (!$this->wasSkipped = require $this->skippedFile) {
echo "All tests already ran successfully.\n";
$suite->setTests(array());
$suite->setTests([]);
}
}
}
$testSuites = array($suite);
$testSuites = [$suite];
for ($i = 0; isset($testSuites[$i]); ++$i) {
foreach ($testSuites[$i]->tests() as $test) {
if ($test instanceof \PHPUnit_Framework_TestSuite || $test instanceof TestSuite) {
@ -149,7 +149,7 @@ class SymfonyTestsListenerTrait
}
}
} elseif (2 === $this->state) {
$skipped = array();
$skipped = [];
foreach ($suite->tests() as $test) {
if (!($test instanceof \PHPUnit\Framework\TestCase || $test instanceof TestCase)
|| isset($this->wasSkipped[$suiteName]['*'])
@ -221,7 +221,7 @@ class SymfonyTestsListenerTrait
$test->getTestResultObject()->beStrictAboutTestsThatDoNotTestAnything(false);
$this->expectedDeprecations = $annotations['method']['expectedDeprecation'];
$this->previousErrorHandler = set_error_handler(array($this, 'handleError'));
$this->previousErrorHandler = set_error_handler([$this, 'handleError']);
}
}
}
@ -262,8 +262,8 @@ class SymfonyTestsListenerTrait
$deprecations = file_get_contents($this->runsInSeparateProcess);
unlink($this->runsInSeparateProcess);
putenv('SYMFONY_DEPRECATIONS_SERIALIZE');
foreach ($deprecations ? unserialize($deprecations) : array() as $deprecation) {
$error = serialize(array('deprecation' => $deprecation[1], 'class' => $className, 'method' => $test->getName(false), 'triggering_file' => isset($deprecation[2]) ? $deprecation[2] : null));
foreach ($deprecations ? unserialize($deprecations) : [] as $deprecation) {
$error = serialize(['deprecation' => $deprecation[1], 'class' => $className, 'method' => $test->getName(false), 'triggering_file' => isset($deprecation[2]) ? $deprecation[2] : null]);
if ($deprecation[0]) {
@trigger_error($error, E_USER_DEPRECATED);
} else {
@ -274,13 +274,13 @@ class SymfonyTestsListenerTrait
}
if ($this->expectedDeprecations) {
if (!\in_array($test->getStatus(), array($BaseTestRunner::STATUS_SKIPPED, $BaseTestRunner::STATUS_INCOMPLETE), true)) {
if (!\in_array($test->getStatus(), [$BaseTestRunner::STATUS_SKIPPED, $BaseTestRunner::STATUS_INCOMPLETE], true)) {
$test->addToAssertionCount(\count($this->expectedDeprecations));
}
restore_error_handler();
if (!$errored && !\in_array($test->getStatus(), array($BaseTestRunner::STATUS_SKIPPED, $BaseTestRunner::STATUS_INCOMPLETE, $BaseTestRunner::STATUS_FAILURE, $BaseTestRunner::STATUS_ERROR), true)) {
if (!$errored && !\in_array($test->getStatus(), [$BaseTestRunner::STATUS_SKIPPED, $BaseTestRunner::STATUS_INCOMPLETE, $BaseTestRunner::STATUS_FAILURE, $BaseTestRunner::STATUS_ERROR], true)) {
try {
$prefix = "@expectedDeprecation:\n";
$test->assertStringMatchesFormat($prefix.'%A '.implode("\n%A ", $this->expectedDeprecations)."\n%A", $prefix.' '.implode("\n ", $this->gatheredDeprecations)."\n");
@ -291,7 +291,7 @@ class SymfonyTestsListenerTrait
}
}
$this->expectedDeprecations = $this->gatheredDeprecations = array();
$this->expectedDeprecations = $this->gatheredDeprecations = [];
$this->previousErrorHandler = null;
}
if (!$this->runsInSeparateProcess && -2 < $this->state && ($test instanceof \PHPUnit\Framework\TestCase || $test instanceof TestCase)) {
@ -299,12 +299,12 @@ class SymfonyTestsListenerTrait
ClockMock::withClockMock(false);
}
if (\in_array('dns-sensitive', $groups, true)) {
DnsMock::withMockedHosts(array());
DnsMock::withMockedHosts([]);
}
}
}
public function handleError($type, $msg, $file, $line, $context = array())
public function handleError($type, $msg, $file, $line, $context = [])
{
if (E_USER_DEPRECATED !== $type && E_DEPRECATED !== $type) {
$h = $this->previousErrorHandler;

View File

@ -27,7 +27,7 @@ class TestRunnerForV5 extends \PHPUnit_TextUI_TestRunner
$result = parent::handleConfiguration($arguments);
$arguments['listeners'] = isset($arguments['listeners']) ? $arguments['listeners'] : array();
$arguments['listeners'] = isset($arguments['listeners']) ? $arguments['listeners'] : [];
$registeredLocally = false;

View File

@ -30,7 +30,7 @@ class TestRunnerForV6 extends BaseRunner
parent::handleConfiguration($arguments);
$arguments['listeners'] = isset($arguments['listeners']) ? $arguments['listeners'] : array();
$arguments['listeners'] = isset($arguments['listeners']) ? $arguments['listeners'] : [];
$registeredLocally = false;

View File

@ -30,7 +30,7 @@ class TestRunnerForV7 extends BaseRunner
parent::handleConfiguration($arguments);
$arguments['listeners'] = isset($arguments['listeners']) ? $arguments['listeners'] : array();
$arguments['listeners'] = isset($arguments['listeners']) ? $arguments['listeners'] : [];
$registeredLocally = false;

View File

@ -25,7 +25,7 @@ class Test
{
public static function getGroups()
{
return array();
return [];
}
}
EOPHP
@ -35,7 +35,7 @@ class PHPUnit_Util_Test
{
public static function getGroups()
{
return array();
return [];
}
}

View File

@ -7,7 +7,7 @@ class Test
{
public static function getGroups()
{
return array();
return [];
}
}
EOPHP

View File

@ -25,7 +25,7 @@ class Test
{
public static function getGroups()
{
return array();
return [];
}
}
EOPHP
@ -35,7 +35,7 @@ class PHPUnit_Util_Test
{
public static function getGroups()
{
return array();
return [];
}
}

View File

@ -25,7 +25,7 @@ class Test
{
public static function getGroups()
{
return array();
return [];
}
}
EOPHP

View File

@ -18,15 +18,15 @@ class DnsMockTest extends TestCase
{
protected function tearDown()
{
DnsMock::withMockedHosts(array());
DnsMock::withMockedHosts([]);
}
public function testCheckdnsrr()
{
DnsMock::withMockedHosts(array('example.com' => array(array('type' => 'MX'))));
DnsMock::withMockedHosts(['example.com' => [['type' => 'MX']]]);
$this->assertTrue(DnsMock::checkdnsrr('example.com'));
DnsMock::withMockedHosts(array('example.com' => array(array('type' => 'A'))));
DnsMock::withMockedHosts(['example.com' => [['type' => 'A']]]);
$this->assertFalse(DnsMock::checkdnsrr('example.com'));
$this->assertTrue(DnsMock::checkdnsrr('example.com', 'a'));
$this->assertTrue(DnsMock::checkdnsrr('example.com', 'any'));
@ -35,34 +35,34 @@ class DnsMockTest extends TestCase
public function testGetmxrr()
{
DnsMock::withMockedHosts(array(
'example.com' => array(array(
DnsMock::withMockedHosts([
'example.com' => [[
'type' => 'MX',
'host' => 'mx.example.com',
'pri' => 10,
)),
));
]],
]);
$this->assertFalse(DnsMock::getmxrr('foobar.com', $mxhosts, $weight));
$this->assertTrue(DnsMock::getmxrr('example.com', $mxhosts, $weight));
$this->assertSame(array('mx.example.com'), $mxhosts);
$this->assertSame(array(10), $weight);
$this->assertSame(['mx.example.com'], $mxhosts);
$this->assertSame([10], $weight);
}
public function testGethostbyaddr()
{
DnsMock::withMockedHosts(array(
'example.com' => array(
array(
DnsMock::withMockedHosts([
'example.com' => [
[
'type' => 'A',
'ip' => '1.2.3.4',
),
array(
],
[
'type' => 'AAAA',
'ipv6' => '::12',
),
),
));
],
],
]);
$this->assertSame('::21', DnsMock::gethostbyaddr('::21'));
$this->assertSame('example.com', DnsMock::gethostbyaddr('::12'));
@ -71,18 +71,18 @@ class DnsMockTest extends TestCase
public function testGethostbyname()
{
DnsMock::withMockedHosts(array(
'example.com' => array(
array(
DnsMock::withMockedHosts([
'example.com' => [
[
'type' => 'AAAA',
'ipv6' => '::12',
),
array(
],
[
'type' => 'A',
'ip' => '1.2.3.4',
),
),
));
],
],
]);
$this->assertSame('foobar.com', DnsMock::gethostbyname('foobar.com'));
$this->assertSame('1.2.3.4', DnsMock::gethostbyname('example.com'));
@ -90,59 +90,59 @@ class DnsMockTest extends TestCase
public function testGethostbynamel()
{
DnsMock::withMockedHosts(array(
'example.com' => array(
array(
DnsMock::withMockedHosts([
'example.com' => [
[
'type' => 'A',
'ip' => '1.2.3.4',
),
array(
],
[
'type' => 'A',
'ip' => '2.3.4.5',
),
),
));
],
],
]);
$this->assertFalse(DnsMock::gethostbynamel('foobar.com'));
$this->assertSame(array('1.2.3.4', '2.3.4.5'), DnsMock::gethostbynamel('example.com'));
$this->assertSame(['1.2.3.4', '2.3.4.5'], DnsMock::gethostbynamel('example.com'));
}
public function testDnsGetRecord()
{
DnsMock::withMockedHosts(array(
'example.com' => array(
array(
DnsMock::withMockedHosts([
'example.com' => [
[
'type' => 'A',
'ip' => '1.2.3.4',
),
array(
],
[
'type' => 'PTR',
'ip' => '2.3.4.5',
),
),
));
],
],
]);
$records = array(
array(
$records = [
[
'host' => 'example.com',
'class' => 'IN',
'ttl' => 1,
'type' => 'A',
'ip' => '1.2.3.4',
),
$ptr = array(
],
$ptr = [
'host' => 'example.com',
'class' => 'IN',
'ttl' => 1,
'type' => 'PTR',
'ip' => '2.3.4.5',
),
);
],
];
$this->assertFalse(DnsMock::dns_get_record('foobar.com'));
$this->assertSame($records, DnsMock::dns_get_record('example.com'));
$this->assertSame($records, DnsMock::dns_get_record('example.com', DNS_ALL));
$this->assertSame($records, DnsMock::dns_get_record('example.com', DNS_A | DNS_PTR));
$this->assertSame(array($ptr), DnsMock::dns_get_record('example.com', DNS_PTR));
$this->assertSame([$ptr], DnsMock::dns_get_record('example.com', DNS_PTR));
}
}

View File

@ -112,7 +112,7 @@ if (!file_exists("$PHPUNIT_DIR/phpunit-$PHPUNIT_VERSION/phpunit") || md5_file(__
$prevRoot = getenv('COMPOSER_ROOT_VERSION');
putenv("COMPOSER_ROOT_VERSION=$PHPUNIT_VERSION.99");
// --no-suggest is not in the list to keep compat with composer 1.0, which is shipped with Ubuntu 16.04LTS
$exit = proc_close(proc_open("$COMPOSER install --no-dev --prefer-dist --no-progress --ansi", array(), $p, getcwd(), null, array('bypass_shell' => true)));
$exit = proc_close(proc_open("$COMPOSER install --no-dev --prefer-dist --no-progress --ansi", [], $p, getcwd(), null, ['bypass_shell' => true]));
putenv('COMPOSER_ROOT_VERSION'.(false !== $prevRoot ? '='.$prevRoot : ''));
if ($exit) {
exit($exit);
@ -145,9 +145,9 @@ EOPHP
}
global $argv, $argc;
$argv = isset($_SERVER['argv']) ? $_SERVER['argv'] : array();
$argv = isset($_SERVER['argv']) ? $_SERVER['argv'] : [];
$argc = isset($_SERVER['argc']) ? $_SERVER['argc'] : 0;
$components = array();
$components = [];
$cmd = array_map('escapeshellarg', $argv);
$exit = 0;
@ -182,7 +182,7 @@ if ('\\' === DIRECTORY_SEPARATOR) {
if ($components) {
$skippedTests = isset($_SERVER['SYMFONY_PHPUNIT_SKIPPED_TESTS']) ? $_SERVER['SYMFONY_PHPUNIT_SKIPPED_TESTS'] : false;
$runningProcs = array();
$runningProcs = [];
foreach ($components as $component) {
// Run phpunit tests in parallel
@ -193,7 +193,7 @@ if ($components) {
$c = escapeshellarg($component);
if ($proc = proc_open(sprintf($cmd, $c, " > $c/phpunit.stdout 2> $c/phpunit.stderr"), array(), $pipes)) {
if ($proc = proc_open(sprintf($cmd, $c, " > $c/phpunit.stdout 2> $c/phpunit.stderr"), [], $pipes)) {
$runningProcs[$component] = $proc;
} else {
$exit = 1;
@ -203,7 +203,7 @@ if ($components) {
while ($runningProcs) {
usleep(300000);
$terminatedProcs = array();
$terminatedProcs = [];
foreach ($runningProcs as $component => $proc) {
$procStatus = proc_get_status($proc);
if (!$procStatus['running']) {
@ -214,7 +214,7 @@ if ($components) {
}
foreach ($terminatedProcs as $component => $procStatus) {
foreach (array('out', 'err') as $file) {
foreach (['out', 'err'] as $file) {
$file = "$component/phpunit.std$file";
readfile($file);
unlink($file);
@ -224,7 +224,7 @@ if ($components) {
// STATUS_STACK_BUFFER_OVERRUN (-1073740791/0xC0000409)
// STATUS_ACCESS_VIOLATION (-1073741819/0xC0000005)
// STATUS_HEAP_CORRUPTION (-1073740940/0xC0000374)
if ($procStatus && ('\\' !== DIRECTORY_SEPARATOR || !extension_loaded('apcu') || !filter_var(ini_get('apc.enable_cli'), FILTER_VALIDATE_BOOLEAN) || !in_array($procStatus, array(-1073740791, -1073741819, -1073740940)))) {
if ($procStatus && ('\\' !== DIRECTORY_SEPARATOR || !extension_loaded('apcu') || !filter_var(ini_get('apc.enable_cli'), FILTER_VALIDATE_BOOLEAN) || !in_array($procStatus, [-1073740791, -1073741819, -1073740940]))) {
$exit = $procStatus;
echo "\033[41mKO\033[0m $component\n\n";
} else {
@ -236,7 +236,7 @@ if ($components) {
if (!class_exists('SymfonyBlacklistSimplePhpunit', false)) {
class SymfonyBlacklistSimplePhpunit {}
}
array_splice($argv, 1, 0, array('--colors=always'));
array_splice($argv, 1, 0, ['--colors=always']);
$_SERVER['argv'] = $argv;
$_SERVER['argc'] = ++$argc;
include "$PHPUNIT_DIR/phpunit-$PHPUNIT_VERSION/phpunit";

View File

@ -69,6 +69,6 @@ class PhpDumperTest extends TestCase
$dumper->setProxyDumper(new ProxyDumper());
return $dumper->dump(array('class' => 'LazyServiceProjectServiceContainer'));
return $dumper->dump(['class' => 'LazyServiceProjectServiceContainer']);
}
}

View File

@ -11,14 +11,14 @@ class ProxyManagerBridgeFooClass
public $initialized = false;
public $configured = false;
public $called = false;
public $arguments = array();
public $arguments = [];
public function __construct($arguments = array())
public function __construct($arguments = [])
{
$this->arguments = $arguments;
}
public static function getInstance($arguments = array())
public static function getInstance($arguments = [])
{
$obj = new self($arguments);
$obj->called = true;

View File

@ -95,18 +95,18 @@ class ProxyDumperTest extends TestCase
public function getPrivatePublicDefinitions()
{
return array(
array(
return [
[
(new Definition(__CLASS__))
->setPublic(false),
\method_exists(ContainerBuilder::class, 'addClassResource') ? 'services' : 'privates',
),
array(
],
[
(new Definition(__CLASS__))
->setPublic(true),
'services',
),
);
],
];
}
/**
@ -125,12 +125,12 @@ class ProxyDumperTest extends TestCase
*/
public function getProxyCandidates()
{
$definitions = array(
array(new Definition(__CLASS__), true),
array(new Definition('stdClass'), true),
array(new Definition(uniqid('foo', true)), false),
array(new Definition(), false),
);
$definitions = [
[new Definition(__CLASS__), true],
[new Definition('stdClass'), true],
[new Definition(uniqid('foo', true)), false],
[new Definition(), false],
];
array_map(
function ($definition) {

View File

@ -150,7 +150,7 @@ class AppVariable
* Returns some or all the existing flash messages:
* * getFlashes() returns all the flash messages
* * getFlashes('notice') returns a simple array with flash messages of that type
* * getFlashes(array('notice', 'error')) returns a nested array of type => messages.
* * getFlashes(['notice', 'error']) returns a nested array of type => messages.
*
* @return array
*/
@ -159,13 +159,13 @@ class AppVariable
try {
$session = $this->getSession();
if (null === $session) {
return array();
return [];
}
} catch (\RuntimeException $e) {
return array();
return [];
}
if (null === $types || '' === $types || array() === $types) {
if (null === $types || '' === $types || [] === $types) {
return $session->getFlashBag()->all();
}
@ -173,7 +173,7 @@ class AppVariable
return $session->getFlashBag()->get($types);
}
$result = array();
$result = [];
foreach ($types as $type) {
$result[$type] = $session->getFlashBag()->get($type);
}

View File

@ -38,7 +38,7 @@ CHANGELOG
use Symfony\Bridge\Twig\Form\TwigRendererEngine;
// ...
$rendererEngine = new TwigRendererEngine(array('form_div_layout.html.twig'));
$rendererEngine = new TwigRendererEngine(['form_div_layout.html.twig']);
$rendererEngine->setEnvironment($twig);
$twig->addExtension(new FormExtension(new TwigRenderer($rendererEngine, $csrfTokenManager)));
```
@ -47,13 +47,13 @@ CHANGELOG
```php
// ...
$rendererEngine = new TwigRendererEngine(array('form_div_layout.html.twig'), $twig);
$rendererEngine = new TwigRendererEngine(['form_div_layout.html.twig'], $twig);
// require Twig 1.30+
$twig->addRuntimeLoader(new \Twig\RuntimeLoader\FactoryRuntimeLoader(array(
$twig->addRuntimeLoader(new \Twig\RuntimeLoader\FactoryRuntimeLoader([
TwigRenderer::class => function () use ($rendererEngine, $csrfTokenManager) {
return new TwigRenderer($rendererEngine, $csrfTokenManager);
},
)));
]));
$twig->addExtension(new FormExtension());
```
* Deprecated the `TwigRendererEngineInterface` interface.

View File

@ -87,7 +87,7 @@ EOF
$template .= fread(STDIN, 1024);
}
return $this->display($input, $output, $io, array($this->validate($template, uniqid('sf_', true))));
return $this->display($input, $output, $io, [$this->validate($template, uniqid('sf_', true))]);
}
$filesInfo = $this->getFilesInfo($filenames);
@ -97,7 +97,7 @@ EOF
private function getFilesInfo(array $filenames)
{
$filesInfo = array();
$filesInfo = [];
foreach ($filenames as $filename) {
foreach ($this->findFiles($filename) as $file) {
$filesInfo[] = $this->validate(file_get_contents($file), $file);
@ -110,7 +110,7 @@ EOF
protected function findFiles($filename)
{
if (is_file($filename)) {
return array($filename);
return [$filename];
} elseif (is_dir($filename)) {
return Finder::create()->files()->in($filename)->name('*.twig');
}
@ -122,7 +122,7 @@ EOF
{
$realLoader = $this->twig->getLoader();
try {
$temporaryLoader = new ArrayLoader(array((string) $file => $template));
$temporaryLoader = new ArrayLoader([(string) $file => $template]);
$this->twig->setLoader($temporaryLoader);
$nodeTree = $this->twig->parse($this->twig->tokenize(new Source($template, (string) $file)));
$this->twig->compile($nodeTree);
@ -130,10 +130,10 @@ EOF
} catch (Error $e) {
$this->twig->setLoader($realLoader);
return array('template' => $template, 'file' => $file, 'line' => $e->getTemplateLine(), 'valid' => false, 'exception' => $e);
return ['template' => $template, 'file' => $file, 'line' => $e->getTemplateLine(), 'valid' => false, 'exception' => $e];
}
return array('template' => $template, 'file' => $file, 'valid' => true);
return ['template' => $template, 'file' => $file, 'valid' => true];
}
private function display(InputInterface $input, OutputInterface $output, SymfonyStyle $io, $files)
@ -219,7 +219,7 @@ EOF
$position = max(0, $line - $context);
$max = min(\count($lines), $line - 1 + $context);
$result = array();
$result = [];
while ($position < $max) {
$result[$position + 1] = $lines[$position];
++$position;

View File

@ -34,10 +34,10 @@ class AssetExtension extends AbstractExtension
*/
public function getFunctions()
{
return array(
new TwigFunction('asset', array($this, 'getAssetUrl')),
new TwigFunction('asset_version', array($this, 'getAssetVersion')),
);
return [
new TwigFunction('asset', [$this, 'getAssetUrl']),
new TwigFunction('asset_version', [$this, 'getAssetVersion']),
];
}
/**

View File

@ -43,17 +43,17 @@ class CodeExtension extends AbstractExtension
*/
public function getFilters()
{
return array(
new TwigFilter('abbr_class', array($this, 'abbrClass'), array('is_safe' => array('html'))),
new TwigFilter('abbr_method', array($this, 'abbrMethod'), array('is_safe' => array('html'))),
new TwigFilter('format_args', array($this, 'formatArgs'), array('is_safe' => array('html'))),
new TwigFilter('format_args_as_text', array($this, 'formatArgsAsText')),
new TwigFilter('file_excerpt', array($this, 'fileExcerpt'), array('is_safe' => array('html'))),
new TwigFilter('format_file', array($this, 'formatFile'), array('is_safe' => array('html'))),
new TwigFilter('format_file_from_text', array($this, 'formatFileFromText'), array('is_safe' => array('html'))),
new TwigFilter('format_log_message', array($this, 'formatLogMessage'), array('is_safe' => array('html'))),
new TwigFilter('file_link', array($this, 'getFileLink')),
);
return [
new TwigFilter('abbr_class', [$this, 'abbrClass'], ['is_safe' => ['html']]),
new TwigFilter('abbr_method', [$this, 'abbrMethod'], ['is_safe' => ['html']]),
new TwigFilter('format_args', [$this, 'formatArgs'], ['is_safe' => ['html']]),
new TwigFilter('format_args_as_text', [$this, 'formatArgsAsText']),
new TwigFilter('file_excerpt', [$this, 'fileExcerpt'], ['is_safe' => ['html']]),
new TwigFilter('format_file', [$this, 'formatFile'], ['is_safe' => ['html']]),
new TwigFilter('format_file_from_text', [$this, 'formatFileFromText'], ['is_safe' => ['html']]),
new TwigFilter('format_log_message', [$this, 'formatLogMessage'], ['is_safe' => ['html']]),
new TwigFilter('file_link', [$this, 'getFileLink']),
];
}
public function abbrClass($class)
@ -87,7 +87,7 @@ class CodeExtension extends AbstractExtension
*/
public function formatArgs($args)
{
$result = array();
$result = [];
foreach ($args as $key => $item) {
if ('object' === $item[0]) {
$parts = explode('\\', $item[1]);
@ -146,7 +146,7 @@ class CodeExtension extends AbstractExtension
}, $code);
$content = explode('<br />', $code);
$lines = array();
$lines = [];
if (0 > $srcContext) {
$srcContext = \count($content);
}
@ -205,7 +205,7 @@ class CodeExtension extends AbstractExtension
public function getFileLink($file, $line)
{
if ($fmt = $this->fileLinkFormat) {
return \is_string($fmt) ? strtr($fmt, array('%f' => $file, '%l' => $line)) : $fmt->format($file, $line);
return \is_string($fmt) ? strtr($fmt, ['%f' => $file, '%l' => $line]) : $fmt->format($file, $line);
}
return false;
@ -224,7 +224,7 @@ class CodeExtension extends AbstractExtension
public function formatLogMessage($message, array $context)
{
if ($context && false !== strpos($message, '{')) {
$replacements = array();
$replacements = [];
foreach ($context as $key => $val) {
if (is_scalar($val)) {
$replacements['{'.$key.'}'] = $val;

View File

@ -37,14 +37,14 @@ class DumpExtension extends AbstractExtension
public function getFunctions()
{
return array(
new TwigFunction('dump', array($this, 'dump'), array('is_safe' => array('html'), 'needs_context' => true, 'needs_environment' => true)),
);
return [
new TwigFunction('dump', [$this, 'dump'], ['is_safe' => ['html'], 'needs_context' => true, 'needs_environment' => true]),
];
}
public function getTokenParsers()
{
return array(new DumpTokenParser());
return [new DumpTokenParser()];
}
public function getName()
@ -59,14 +59,14 @@ class DumpExtension extends AbstractExtension
}
if (2 === \func_num_args()) {
$vars = array();
$vars = [];
foreach ($context as $key => $value) {
if (!$value instanceof Template) {
$vars[$key] = $value;
}
}
$vars = array($vars);
$vars = [$vars];
} else {
$vars = \func_get_args();
unset($vars[0], $vars[1]);

View File

@ -27,9 +27,9 @@ class ExpressionExtension extends AbstractExtension
*/
public function getFunctions()
{
return array(
new TwigFunction('expression', array($this, 'createExpression')),
);
return [
new TwigFunction('expression', [$this, 'createExpression']),
];
}
public function createExpression($expression)

View File

@ -38,10 +38,10 @@ class HttpFoundationExtension extends AbstractExtension
*/
public function getFunctions()
{
return array(
new TwigFunction('absolute_url', array($this, 'generateAbsoluteUrl')),
new TwigFunction('relative_path', array($this, 'generateRelativePath')),
);
return [
new TwigFunction('absolute_url', [$this, 'generateAbsoluteUrl']),
new TwigFunction('relative_path', [$this, 'generateRelativePath']),
];
}
/**

View File

@ -24,14 +24,14 @@ class HttpKernelExtension extends AbstractExtension
{
public function getFunctions()
{
return array(
new TwigFunction('render', array(HttpKernelRuntime::class, 'renderFragment'), array('is_safe' => array('html'))),
new TwigFunction('render_*', array(HttpKernelRuntime::class, 'renderFragmentStrategy'), array('is_safe' => array('html'))),
return [
new TwigFunction('render', [HttpKernelRuntime::class, 'renderFragment'], ['is_safe' => ['html']]),
new TwigFunction('render_*', [HttpKernelRuntime::class, 'renderFragmentStrategy'], ['is_safe' => ['html']]),
new TwigFunction('controller', static::class.'::controller'),
);
];
}
public static function controller($controller, $attributes = array(), $query = array())
public static function controller($controller, $attributes = [], $query = [])
{
return new ControllerReference($controller, $attributes, $query);
}

View File

@ -38,7 +38,7 @@ class HttpKernelRuntime
*
* @see FragmentHandler::render()
*/
public function renderFragment($uri, $options = array())
public function renderFragment($uri, $options = [])
{
$strategy = isset($options['strategy']) ? $options['strategy'] : 'inline';
unset($options['strategy']);
@ -57,7 +57,7 @@ class HttpKernelRuntime
*
* @see FragmentHandler::render()
*/
public function renderFragmentStrategy($strategy, $uri, $options = array())
public function renderFragmentStrategy($strategy, $uri, $options = [])
{
return $this->handler->render($uri, $strategy, $options);
}

View File

@ -34,10 +34,10 @@ class LogoutUrlExtension extends AbstractExtension
*/
public function getFunctions()
{
return array(
new TwigFunction('logout_url', array($this, 'getLogoutUrl')),
new TwigFunction('logout_path', array($this, 'getLogoutPath')),
);
return [
new TwigFunction('logout_url', [$this, 'getLogoutUrl']),
new TwigFunction('logout_path', [$this, 'getLogoutPath']),
];
}
/**

View File

@ -39,10 +39,10 @@ class RoutingExtension extends AbstractExtension
*/
public function getFunctions()
{
return array(
new TwigFunction('url', array($this, 'getUrl'), array('is_safe_callback' => array($this, 'isUrlGenerationSafe'))),
new TwigFunction('path', array($this, 'getPath'), array('is_safe_callback' => array($this, 'isUrlGenerationSafe'))),
);
return [
new TwigFunction('url', [$this, 'getUrl'], ['is_safe_callback' => [$this, 'isUrlGenerationSafe']]),
new TwigFunction('path', [$this, 'getPath'], ['is_safe_callback' => [$this, 'isUrlGenerationSafe']]),
];
}
/**
@ -52,7 +52,7 @@ class RoutingExtension extends AbstractExtension
*
* @return string
*/
public function getPath($name, $parameters = array(), $relative = false)
public function getPath($name, $parameters = [], $relative = false)
{
return $this->generator->generate($name, $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH);
}
@ -64,7 +64,7 @@ class RoutingExtension extends AbstractExtension
*
* @return string
*/
public function getUrl($name, $parameters = array(), $schemeRelative = false)
public function getUrl($name, $parameters = [], $schemeRelative = false)
{
return $this->generator->generate($name, $parameters, $schemeRelative ? UrlGeneratorInterface::NETWORK_PATH : UrlGeneratorInterface::ABSOLUTE_URL);
}
@ -103,10 +103,10 @@ class RoutingExtension extends AbstractExtension
if (null === $paramsNode || $paramsNode instanceof ArrayExpression && \count($paramsNode) <= 2 &&
(!$paramsNode->hasNode(1) || $paramsNode->getNode(1) instanceof ConstantExpression)
) {
return array('html');
return ['html'];
}
return array();
return [];
}
/**

View File

@ -53,9 +53,9 @@ class SecurityExtension extends AbstractExtension
*/
public function getFunctions()
{
return array(
new TwigFunction('is_granted', array($this, 'isGranted')),
);
return [
new TwigFunction('is_granted', [$this, 'isGranted']),
];
}
/**

View File

@ -38,14 +38,14 @@ class StopwatchExtension extends AbstractExtension
public function getTokenParsers()
{
return array(
return [
/*
* {% stopwatch foo %}
* Some stuff which will be recorded on the timeline
* {% endstopwatch %}
*/
new StopwatchTokenParser(null !== $this->stopwatch && $this->enabled),
);
];
}
public function getName()

View File

@ -48,10 +48,10 @@ class TranslationExtension extends AbstractExtension
*/
public function getFilters()
{
return array(
new TwigFilter('trans', array($this, 'trans')),
new TwigFilter('transchoice', array($this, 'transchoice')),
);
return [
new TwigFilter('trans', [$this, 'trans']),
new TwigFilter('transchoice', [$this, 'transchoice']),
];
}
/**
@ -61,7 +61,7 @@ class TranslationExtension extends AbstractExtension
*/
public function getTokenParsers()
{
return array(
return [
// {% trans %}Symfony is great!{% endtrans %}
new TransTokenParser(),
@ -72,7 +72,7 @@ class TranslationExtension extends AbstractExtension
// {% trans_default_domain "foobar" %}
new TransDefaultDomainTokenParser(),
);
];
}
/**
@ -80,7 +80,7 @@ class TranslationExtension extends AbstractExtension
*/
public function getNodeVisitors()
{
return array($this->getTranslationNodeVisitor(), new TranslationDefaultDomainNodeVisitor());
return [$this->getTranslationNodeVisitor(), new TranslationDefaultDomainNodeVisitor()];
}
public function getTranslationNodeVisitor()
@ -88,7 +88,7 @@ class TranslationExtension extends AbstractExtension
return $this->translationNodeVisitor ?: $this->translationNodeVisitor = new TranslationNodeVisitor();
}
public function trans($message, array $arguments = array(), $domain = null, $locale = null)
public function trans($message, array $arguments = [], $domain = null, $locale = null)
{
if (null === $this->translator) {
return strtr($message, $arguments);
@ -97,13 +97,13 @@ class TranslationExtension extends AbstractExtension
return $this->translator->trans($message, $arguments, $domain, $locale);
}
public function transchoice($message, $count, array $arguments = array(), $domain = null, $locale = null)
public function transchoice($message, $count, array $arguments = [], $domain = null, $locale = null)
{
if (null === $this->translator) {
return strtr($message, $arguments);
}
return $this->translator->transChoice($message, $count, array_merge(array('%count%' => $count), $arguments), $domain, $locale);
return $this->translator->transChoice($message, $count, array_merge(['%count%' => $count], $arguments), $domain, $locale);
}
/**

View File

@ -36,14 +36,14 @@ class WebLinkExtension extends AbstractExtension
*/
public function getFunctions()
{
return array(
new TwigFunction('link', array($this, 'link')),
new TwigFunction('preload', array($this, 'preload')),
new TwigFunction('dns_prefetch', array($this, 'dnsPrefetch')),
new TwigFunction('preconnect', array($this, 'preconnect')),
new TwigFunction('prefetch', array($this, 'prefetch')),
new TwigFunction('prerender', array($this, 'prerender')),
);
return [
new TwigFunction('link', [$this, 'link']),
new TwigFunction('preload', [$this, 'preload']),
new TwigFunction('dns_prefetch', [$this, 'dnsPrefetch']),
new TwigFunction('preconnect', [$this, 'preconnect']),
new TwigFunction('prefetch', [$this, 'prefetch']),
new TwigFunction('prerender', [$this, 'prerender']),
];
}
/**
@ -51,11 +51,11 @@ class WebLinkExtension extends AbstractExtension
*
* @param string $uri The relation URI
* @param string $rel The relation type (e.g. "preload", "prefetch", "prerender" or "dns-prefetch")
* @param array $attributes The attributes of this link (e.g. "array('as' => true)", "array('pr' => 0.5)")
* @param array $attributes The attributes of this link (e.g. "['as' => true]", "['pr' => 0.5]")
*
* @return string The relation URI
*/
public function link($uri, $rel, array $attributes = array())
public function link($uri, $rel, array $attributes = [])
{
if (!$request = $this->requestStack->getMasterRequest()) {
return $uri;
@ -76,11 +76,11 @@ class WebLinkExtension extends AbstractExtension
* Preloads a resource.
*
* @param string $uri A public path
* @param array $attributes The attributes of this link (e.g. "array('as' => true)", "array('crossorigin' => 'use-credentials')")
* @param array $attributes The attributes of this link (e.g. "['as' => true]", "['crossorigin' => 'use-credentials']")
*
* @return string The path of the asset
*/
public function preload($uri, array $attributes = array())
public function preload($uri, array $attributes = [])
{
return $this->link($uri, 'preload', $attributes);
}
@ -89,11 +89,11 @@ class WebLinkExtension extends AbstractExtension
* Resolves a resource origin as early as possible.
*
* @param string $uri A public path
* @param array $attributes The attributes of this link (e.g. "array('as' => true)", "array('pr' => 0.5)")
* @param array $attributes The attributes of this link (e.g. "['as' => true]", "['pr' => 0.5]")
*
* @return string The path of the asset
*/
public function dnsPrefetch($uri, array $attributes = array())
public function dnsPrefetch($uri, array $attributes = [])
{
return $this->link($uri, 'dns-prefetch', $attributes);
}
@ -102,11 +102,11 @@ class WebLinkExtension extends AbstractExtension
* Initiates a early connection to a resource (DNS resolution, TCP handshake, TLS negotiation).
*
* @param string $uri A public path
* @param array $attributes The attributes of this link (e.g. "array('as' => true)", "array('pr' => 0.5)")
* @param array $attributes The attributes of this link (e.g. "['as' => true]", "['pr' => 0.5]")
*
* @return string The path of the asset
*/
public function preconnect($uri, array $attributes = array())
public function preconnect($uri, array $attributes = [])
{
return $this->link($uri, 'preconnect', $attributes);
}
@ -115,11 +115,11 @@ class WebLinkExtension extends AbstractExtension
* Indicates to the client that it should prefetch this resource.
*
* @param string $uri A public path
* @param array $attributes The attributes of this link (e.g. "array('as' => true)", "array('pr' => 0.5)")
* @param array $attributes The attributes of this link (e.g. "['as' => true]", "['pr' => 0.5]")
*
* @return string The path of the asset
*/
public function prefetch($uri, array $attributes = array())
public function prefetch($uri, array $attributes = [])
{
return $this->link($uri, 'prefetch', $attributes);
}
@ -128,11 +128,11 @@ class WebLinkExtension extends AbstractExtension
* Indicates to the client that it should prerender this resource .
*
* @param string $uri A public path
* @param array $attributes The attributes of this link (e.g. "array('as' => true)", "array('pr' => 0.5)")
* @param array $attributes The attributes of this link (e.g. "['as' => true]", "['pr' => 0.5]")
*
* @return string The path of the asset
*/
public function prerender($uri, array $attributes = array())
public function prerender($uri, array $attributes = [])
{
return $this->link($uri, 'prerender', $attributes);
}

View File

@ -28,10 +28,10 @@ class YamlExtension extends AbstractExtension
*/
public function getFilters()
{
return array(
new TwigFilter('yaml_encode', array($this, 'encode')),
new TwigFilter('yaml_dump', array($this, 'dump')),
);
return [
new TwigFilter('yaml_encode', [$this, 'encode']),
new TwigFilter('yaml_dump', [$this, 'dump']),
];
}
public function encode($input, $inline = 0, $dumpObjects = 0)

View File

@ -23,12 +23,12 @@ class DumpNode extends Node
public function __construct($varPrefix, Node $values = null, int $lineno, string $tag = null)
{
$nodes = array();
$nodes = [];
if (null !== $values) {
$nodes['values'] = $values;
}
parent::__construct($nodes, array(), $lineno, $tag);
parent::__construct($nodes, [], $lineno, $tag);
$this->varPrefix = $varPrefix;
}

View File

@ -53,7 +53,7 @@ class SearchAndRenderBlockNode extends FunctionExpression
// Only insert the label into the array if it is not empty
if (!twig_test_empty($label->getAttribute('value'))) {
$originalVariables = $variables;
$variables = new ArrayExpression(array(), $lineno);
$variables = new ArrayExpression([], $lineno);
$labelKey = new ConstantExpression('label', $lineno);
if (null !== $originalVariables) {

View File

@ -24,7 +24,7 @@ class StopwatchNode extends Node
{
public function __construct(Node $name, Node $body, AssignNameExpression $var, int $lineno = 0, string $tag = null)
{
parent::__construct(array('body' => $body, 'name' => $name, 'var' => $var), array(), $lineno, $tag);
parent::__construct(['body' => $body, 'name' => $name, 'var' => $var], [], $lineno, $tag);
}
public function compile(Compiler $compiler)

View File

@ -22,7 +22,7 @@ class TransDefaultDomainNode extends Node
{
public function __construct(AbstractExpression $expr, int $lineno = 0, string $tag = null)
{
parent::__construct(array('expr' => $expr), array(), $lineno, $tag);
parent::__construct(['expr' => $expr], [], $lineno, $tag);
}
public function compile(Compiler $compiler)

View File

@ -29,7 +29,7 @@ class TransNode extends Node
{
public function __construct(Node $body, Node $domain = null, AbstractExpression $count = null, AbstractExpression $vars = null, AbstractExpression $locale = null, int $lineno = 0, string $tag = null)
{
$nodes = array('body' => $body);
$nodes = ['body' => $body];
if (null !== $domain) {
$nodes['domain'] = $domain;
}
@ -43,14 +43,14 @@ class TransNode extends Node
$nodes['locale'] = $locale;
}
parent::__construct($nodes, array(), $lineno, $tag);
parent::__construct($nodes, [], $lineno, $tag);
}
public function compile(Compiler $compiler)
{
$compiler->addDebugInfo($this);
$defaults = new ArrayExpression(array(), -1);
$defaults = new ArrayExpression([], -1);
if ($this->hasNode('vars') && ($vars = $this->getNode('vars')) instanceof ArrayExpression) {
$defaults = $this->getNode('vars');
$vars = null;
@ -109,7 +109,7 @@ class TransNode extends Node
} elseif ($body instanceof TextNode) {
$msg = $body->getAttribute('data');
} else {
return array($body, $vars);
return [$body, $vars];
}
preg_match_all('/(?<!%)%([^%]+)%/', $msg, $matches);
@ -127,6 +127,6 @@ class TransNode extends Node
}
}
return array(new ConstantExpression(str_replace('%%', '%', trim($msg)), $body->getTemplateLine()), $vars);
return [new ConstantExpression(str_replace('%%', '%', trim($msg)), $body->getTemplateLine()), $vars];
}
}

View File

@ -17,7 +17,7 @@ namespace Symfony\Bridge\Twig\NodeVisitor;
class Scope
{
private $parent;
private $data = array();
private $data = [];
private $left = false;
public function __construct(self $parent = null)

View File

@ -56,7 +56,7 @@ class TranslationDefaultDomainNodeVisitor extends AbstractNodeVisitor
$name = new AssignNameExpression($var, $node->getTemplateLine());
$this->scope->set('domain', new NameExpression($var, $node->getTemplateLine()));
return new SetNode(false, new Node(array($name)), new Node(array($node->getNode('expr'))), $node->getTemplateLine());
return new SetNode(false, new Node([$name]), new Node([$node->getNode('expr')]), $node->getTemplateLine());
}
}
@ -64,7 +64,7 @@ class TranslationDefaultDomainNodeVisitor extends AbstractNodeVisitor
return $node;
}
if ($node instanceof FilterExpression && \in_array($node->getNode('filter')->getAttribute('value'), array('trans', 'transchoice'))) {
if ($node instanceof FilterExpression && \in_array($node->getNode('filter')->getAttribute('value'), ['trans', 'transchoice'])) {
$arguments = $node->getNode('arguments');
$ind = 'trans' === $node->getNode('filter')->getAttribute('value') ? 1 : 2;
if ($this->isNamedArguments($arguments)) {
@ -74,7 +74,7 @@ class TranslationDefaultDomainNodeVisitor extends AbstractNodeVisitor
} else {
if (!$arguments->hasNode($ind)) {
if (!$arguments->hasNode($ind - 1)) {
$arguments->setNode($ind - 1, new ArrayExpression(array(), $node->getTemplateLine()));
$arguments->setNode($ind - 1, new ArrayExpression([], $node->getTemplateLine()));
}
$arguments->setNode($ind, $this->scope->get('domain'));

View File

@ -28,18 +28,18 @@ class TranslationNodeVisitor extends AbstractNodeVisitor
const UNDEFINED_DOMAIN = '_undefined';
private $enabled = false;
private $messages = array();
private $messages = [];
public function enable()
{
$this->enabled = true;
$this->messages = array();
$this->messages = [];
}
public function disable()
{
$this->enabled = false;
$this->messages = array();
$this->messages = [];
}
public function getMessages()
@ -62,26 +62,26 @@ class TranslationNodeVisitor extends AbstractNodeVisitor
$node->getNode('node') instanceof ConstantExpression
) {
// extract constant nodes with a trans filter
$this->messages[] = array(
$this->messages[] = [
$node->getNode('node')->getAttribute('value'),
$this->getReadDomainFromArguments($node->getNode('arguments'), 1),
);
];
} elseif (
$node instanceof FilterExpression &&
'transchoice' === $node->getNode('filter')->getAttribute('value') &&
$node->getNode('node') instanceof ConstantExpression
) {
// extract constant nodes with a trans filter
$this->messages[] = array(
$this->messages[] = [
$node->getNode('node')->getAttribute('value'),
$this->getReadDomainFromArguments($node->getNode('arguments'), 2),
);
];
} elseif ($node instanceof TransNode) {
// extract trans nodes
$this->messages[] = array(
$this->messages[] = [
$node->getNode('body')->getAttribute('data'),
$node->hasNode('domain') ? $this->getReadDomainFromNode($node->getNode('domain')) : null,
);
];
}
return $node;

View File

@ -32,10 +32,10 @@ class AppVariableTest extends TestCase
public function debugDataProvider()
{
return array(
'debug on' => array(true),
'debug off' => array(false),
);
return [
'debug on' => [true],
'debug off' => [false],
];
}
public function testEnvironment()
@ -165,7 +165,7 @@ class AppVariableTest extends TestCase
{
$this->setRequestStack(null);
$this->assertEquals(array(), $this->appVariable->getFlashes());
$this->assertEquals([], $this->appVariable->getFlashes());
}
/**
@ -189,15 +189,15 @@ class AppVariableTest extends TestCase
$this->assertEquals($flashMessages, $this->appVariable->getFlashes(''));
$flashMessages = $this->setFlashMessages();
$this->assertEquals($flashMessages, $this->appVariable->getFlashes(array()));
$this->assertEquals($flashMessages, $this->appVariable->getFlashes([]));
$flashMessages = $this->setFlashMessages();
$this->assertEquals(array(), $this->appVariable->getFlashes('this-does-not-exist'));
$this->assertEquals([], $this->appVariable->getFlashes('this-does-not-exist'));
$flashMessages = $this->setFlashMessages();
$this->assertEquals(
array('this-does-not-exist' => array()),
$this->appVariable->getFlashes(array('this-does-not-exist'))
['this-does-not-exist' => []],
$this->appVariable->getFlashes(['this-does-not-exist'])
);
$flashMessages = $this->setFlashMessages();
@ -205,31 +205,31 @@ class AppVariableTest extends TestCase
$flashMessages = $this->setFlashMessages();
$this->assertEquals(
array('notice' => $flashMessages['notice']),
$this->appVariable->getFlashes(array('notice'))
['notice' => $flashMessages['notice']],
$this->appVariable->getFlashes(['notice'])
);
$flashMessages = $this->setFlashMessages();
$this->assertEquals(
array('notice' => $flashMessages['notice'], 'this-does-not-exist' => array()),
$this->appVariable->getFlashes(array('notice', 'this-does-not-exist'))
['notice' => $flashMessages['notice'], 'this-does-not-exist' => []],
$this->appVariable->getFlashes(['notice', 'this-does-not-exist'])
);
$flashMessages = $this->setFlashMessages();
$this->assertEquals(
array('notice' => $flashMessages['notice'], 'error' => $flashMessages['error']),
$this->appVariable->getFlashes(array('notice', 'error'))
['notice' => $flashMessages['notice'], 'error' => $flashMessages['error']],
$this->appVariable->getFlashes(['notice', 'error'])
);
$this->assertEquals(
array('warning' => $flashMessages['warning']),
$this->appVariable->getFlashes(array('warning')),
['warning' => $flashMessages['warning']],
$this->appVariable->getFlashes(['warning']),
'After getting some flash types (e.g. "notice" and "error"), the rest of flash messages must remain (e.g. "warning").'
);
$this->assertEquals(
array('this-does-not-exist' => array()),
$this->appVariable->getFlashes(array('this-does-not-exist'))
['this-does-not-exist' => []],
$this->appVariable->getFlashes(['this-does-not-exist'])
);
}
@ -254,11 +254,11 @@ class AppVariableTest extends TestCase
private function setFlashMessages($sessionHasStarted = true)
{
$flashMessages = array(
'notice' => array('Notice #1 message'),
'warning' => array('Warning #1 message'),
'error' => array('Error #1 message', 'Error #2 message'),
);
$flashMessages = [
'notice' => ['Notice #1 message'],
'warning' => ['Warning #1 message'],
'error' => ['Error #1 message', 'Error #2 message'],
];
$flashBag = new FlashBag();
$flashBag->initialize($flashMessages);

View File

@ -23,7 +23,7 @@ class DebugCommandTest extends TestCase
public function testDebugCommand()
{
$tester = $this->createCommandTester();
$ret = $tester->execute(array(), array('decorated' => false));
$ret = $tester->execute([], ['decorated' => false]);
$this->assertEquals(0, $ret, 'Returns 0 in case of success');
$this->assertContains('Functions', trim($tester->getDisplay()));
@ -33,12 +33,12 @@ class DebugCommandTest extends TestCase
{
// these paths aren't realistic,
// they're configured to force the line separator
$tester = $this->createCommandTester(array(
'Acme' => array('extractor', 'extractor'),
'!Acme' => array('extractor', 'extractor'),
FilesystemLoader::MAIN_NAMESPACE => array('extractor', 'extractor'),
));
$ret = $tester->execute(array(), array('decorated' => false));
$tester = $this->createCommandTester([
'Acme' => ['extractor', 'extractor'],
'!Acme' => ['extractor', 'extractor'],
FilesystemLoader::MAIN_NAMESPACE => ['extractor', 'extractor'],
]);
$ret = $tester->execute([], ['decorated' => false]);
$ds = \DIRECTORY_SEPARATOR;
$loaderPaths = <<<TXT
Loader Paths
@ -62,9 +62,9 @@ TXT;
$this->assertContains($loaderPaths, trim($tester->getDisplay(true)));
}
private function createCommandTester(array $paths = array())
private function createCommandTester(array $paths = [])
{
$filesystemLoader = new FilesystemLoader(array(), \dirname(__DIR__).'/Fixtures');
$filesystemLoader = new FilesystemLoader([], \dirname(__DIR__).'/Fixtures');
foreach ($paths as $namespace => $relDirs) {
foreach ($relDirs as $relDir) {
$filesystemLoader->addPath($relDir, $namespace);

View File

@ -17,7 +17,7 @@ abstract class AbstractBootstrap3HorizontalLayoutTest extends AbstractBootstrap3
{
$form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\DateType');
$view = $form->createView();
$this->renderWidget($view, array('label' => 'foo'));
$this->renderWidget($view, ['label' => 'foo']);
$html = $this->renderLabel($view);
$this->assertMatchesXpath($html,
@ -31,11 +31,11 @@ abstract class AbstractBootstrap3HorizontalLayoutTest extends AbstractBootstrap3
public function testLabelDoesNotRenderFieldAttributes()
{
$form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType');
$html = $this->renderLabel($form->createView(), null, array(
'attr' => array(
$html = $this->renderLabel($form->createView(), null, [
'attr' => [
'class' => 'my&class',
),
));
],
]);
$this->assertMatchesXpath($html,
'/label
@ -48,11 +48,11 @@ abstract class AbstractBootstrap3HorizontalLayoutTest extends AbstractBootstrap3
public function testLabelWithCustomAttributesPassedDirectly()
{
$form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType');
$html = $this->renderLabel($form->createView(), null, array(
'label_attr' => array(
$html = $this->renderLabel($form->createView(), null, [
'label_attr' => [
'class' => 'my&class',
),
));
],
]);
$this->assertMatchesXpath($html,
'/label
@ -65,11 +65,11 @@ abstract class AbstractBootstrap3HorizontalLayoutTest extends AbstractBootstrap3
public function testLabelWithCustomTextAndCustomAttributesPassedDirectly()
{
$form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType');
$html = $this->renderLabel($form->createView(), 'Custom label', array(
'label_attr' => array(
$html = $this->renderLabel($form->createView(), 'Custom label', [
'label_attr' => [
'class' => 'my&class',
),
));
],
]);
$this->assertMatchesXpath($html,
'/label
@ -82,14 +82,14 @@ abstract class AbstractBootstrap3HorizontalLayoutTest extends AbstractBootstrap3
public function testLabelWithCustomTextAsOptionAndCustomAttributesPassedDirectly()
{
$form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, array(
$form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, [
'label' => 'Custom label',
));
$html = $this->renderLabel($form->createView(), null, array(
'label_attr' => array(
]);
$html = $this->renderLabel($form->createView(), null, [
'label_attr' => [
'class' => 'my&class',
),
));
],
]);
$this->assertMatchesXpath($html,
'/label
@ -102,10 +102,10 @@ abstract class AbstractBootstrap3HorizontalLayoutTest extends AbstractBootstrap3
public function testStartTag()
{
$form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, array(
$form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, [
'method' => 'get',
'action' => 'http://example.com/directory',
));
]);
$html = $this->renderStart($form->createView());
@ -114,25 +114,25 @@ abstract class AbstractBootstrap3HorizontalLayoutTest extends AbstractBootstrap3
public function testStartTagWithOverriddenVars()
{
$form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, array(
$form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, [
'method' => 'put',
'action' => 'http://example.com/directory',
));
]);
$html = $this->renderStart($form->createView(), array(
$html = $this->renderStart($form->createView(), [
'method' => 'post',
'action' => 'http://foo.com/directory',
));
]);
$this->assertSame('<form name="form" method="post" action="http://foo.com/directory" class="form-horizontal">', $html);
}
public function testStartTagForMultipartForm()
{
$form = $this->factory->createBuilder('Symfony\Component\Form\Extension\Core\Type\FormType', null, array(
$form = $this->factory->createBuilder('Symfony\Component\Form\Extension\Core\Type\FormType', null, [
'method' => 'get',
'action' => 'http://example.com/directory',
))
])
->add('file', 'Symfony\Component\Form\Extension\Core\Type\FileType')
->getForm();
@ -143,14 +143,14 @@ abstract class AbstractBootstrap3HorizontalLayoutTest extends AbstractBootstrap3
public function testStartTagWithExtraAttributes()
{
$form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, array(
$form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, [
'method' => 'get',
'action' => 'http://example.com/directory',
));
]);
$html = $this->renderStart($form->createView(), array(
'attr' => array('class' => 'foobar'),
));
$html = $this->renderStart($form->createView(), [
'attr' => ['class' => 'foobar'],
]);
$this->assertSame('<form name="form" method="get" action="http://example.com/directory" class="foobar form-horizontal">', $html);
}
@ -159,7 +159,7 @@ abstract class AbstractBootstrap3HorizontalLayoutTest extends AbstractBootstrap3
{
$form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\CheckboxType');
$view = $form->createView();
$html = $this->renderRow($view, array('label' => 'foo'));
$html = $this->renderRow($view, ['label' => 'foo']);
$this->assertMatchesXpath($html, '/div[@class="form-group"]/div[@class="col-sm-2" or @class="col-sm-10"]', 2);
}

View File

@ -49,7 +49,7 @@ abstract class AbstractBootstrap4HorizontalLayoutTest extends AbstractBootstrap4
{
$form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\DateType');
$view = $form->createView();
$this->renderWidget($view, array('label' => 'foo'));
$this->renderWidget($view, ['label' => 'foo']);
$html = $this->renderLabel($view);
$this->assertMatchesXpath($html,
@ -63,11 +63,11 @@ abstract class AbstractBootstrap4HorizontalLayoutTest extends AbstractBootstrap4
public function testLabelDoesNotRenderFieldAttributes()
{
$form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType');
$html = $this->renderLabel($form->createView(), null, array(
'attr' => array(
$html = $this->renderLabel($form->createView(), null, [
'attr' => [
'class' => 'my&class',
),
));
],
]);
$this->assertMatchesXpath($html,
'/label
@ -80,11 +80,11 @@ abstract class AbstractBootstrap4HorizontalLayoutTest extends AbstractBootstrap4
public function testLabelWithCustomAttributesPassedDirectly()
{
$form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType');
$html = $this->renderLabel($form->createView(), null, array(
'label_attr' => array(
$html = $this->renderLabel($form->createView(), null, [
'label_attr' => [
'class' => 'my&class',
),
));
],
]);
$this->assertMatchesXpath($html,
'/label
@ -97,11 +97,11 @@ abstract class AbstractBootstrap4HorizontalLayoutTest extends AbstractBootstrap4
public function testLabelWithCustomTextAndCustomAttributesPassedDirectly()
{
$form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType');
$html = $this->renderLabel($form->createView(), 'Custom label', array(
'label_attr' => array(
$html = $this->renderLabel($form->createView(), 'Custom label', [
'label_attr' => [
'class' => 'my&class',
),
));
],
]);
$this->assertMatchesXpath($html,
'/label
@ -114,14 +114,14 @@ abstract class AbstractBootstrap4HorizontalLayoutTest extends AbstractBootstrap4
public function testLabelWithCustomTextAsOptionAndCustomAttributesPassedDirectly()
{
$form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, array(
$form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, [
'label' => 'Custom label',
));
$html = $this->renderLabel($form->createView(), null, array(
'label_attr' => array(
]);
$html = $this->renderLabel($form->createView(), null, [
'label_attr' => [
'class' => 'my&class',
),
));
],
]);
$this->assertMatchesXpath($html,
'/label
@ -134,11 +134,11 @@ abstract class AbstractBootstrap4HorizontalLayoutTest extends AbstractBootstrap4
public function testLegendOnExpandedType()
{
$form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', null, array(
$form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', null, [
'label' => 'Custom label',
'expanded' => true,
'choices' => array('Choice&A' => '&a', 'Choice&B' => '&b'),
));
'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'],
]);
$view = $form->createView();
$this->renderWidget($view);
$html = $this->renderLabel($view);
@ -153,10 +153,10 @@ abstract class AbstractBootstrap4HorizontalLayoutTest extends AbstractBootstrap4
public function testStartTag()
{
$form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, array(
$form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, [
'method' => 'get',
'action' => 'http://example.com/directory',
));
]);
$html = $this->renderStart($form->createView());
@ -165,25 +165,25 @@ abstract class AbstractBootstrap4HorizontalLayoutTest extends AbstractBootstrap4
public function testStartTagWithOverriddenVars()
{
$form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, array(
$form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, [
'method' => 'put',
'action' => 'http://example.com/directory',
));
]);
$html = $this->renderStart($form->createView(), array(
$html = $this->renderStart($form->createView(), [
'method' => 'post',
'action' => 'http://foo.com/directory',
));
]);
$this->assertSame('<form name="form" method="post" action="http://foo.com/directory">', $html);
}
public function testStartTagForMultipartForm()
{
$form = $this->factory->createBuilder('Symfony\Component\Form\Extension\Core\Type\FormType', null, array(
$form = $this->factory->createBuilder('Symfony\Component\Form\Extension\Core\Type\FormType', null, [
'method' => 'get',
'action' => 'http://example.com/directory',
))
])
->add('file', 'Symfony\Component\Form\Extension\Core\Type\FileType')
->getForm();
@ -194,14 +194,14 @@ abstract class AbstractBootstrap4HorizontalLayoutTest extends AbstractBootstrap4
public function testStartTagWithExtraAttributes()
{
$form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, array(
$form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, [
'method' => 'get',
'action' => 'http://example.com/directory',
));
]);
$html = $this->renderStart($form->createView(), array(
'attr' => array('class' => 'foobar'),
));
$html = $this->renderStart($form->createView(), [
'attr' => ['class' => 'foobar'],
]);
$this->assertSame('<form name="form" method="get" action="http://example.com/directory" class="foobar">', $html);
}
@ -210,7 +210,7 @@ abstract class AbstractBootstrap4HorizontalLayoutTest extends AbstractBootstrap4
{
$form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\CheckboxType');
$view = $form->createView();
$html = $this->renderRow($view, array('label' => 'foo'));
$html = $this->renderRow($view, ['label' => 'foo']);
$this->assertMatchesXpath($html, '/div[@class="form-group row"]/div[@class="col-sm-2" or @class="col-sm-10"]', 2);
}

View File

@ -41,20 +41,20 @@ class CodeExtensionTest extends TestCase
public function getClassNameProvider()
{
return array(
array('F\Q\N\Foo', '<abbr title="F\Q\N\Foo">Foo</abbr>'),
array('Bare', '<abbr title="Bare">Bare</abbr>'),
);
return [
['F\Q\N\Foo', '<abbr title="F\Q\N\Foo">Foo</abbr>'],
['Bare', '<abbr title="Bare">Bare</abbr>'],
];
}
public function getMethodNameProvider()
{
return array(
array('F\Q\N\Foo::Method', '<abbr title="F\Q\N\Foo">Foo</abbr>::Method()'),
array('Bare::Method', '<abbr title="Bare">Bare</abbr>::Method()'),
array('Closure', '<abbr title="Closure">Closure</abbr>'),
array('Method', '<abbr title="Method">Method</abbr>()'),
);
return [
['F\Q\N\Foo::Method', '<abbr title="F\Q\N\Foo">Foo</abbr>::Method()'],
['Bare::Method', '<abbr title="Bare">Bare</abbr>::Method()'],
['Closure', '<abbr title="Closure">Closure</abbr>'],
['Method', '<abbr title="Method">Method</abbr>()'],
];
}
public function testGetName()

View File

@ -27,11 +27,11 @@ class DumpExtensionTest extends TestCase
public function testDumpTag($template, $debug, $expectedOutput, $expectedDumped)
{
$extension = new DumpExtension(new VarCloner());
$twig = new Environment(new ArrayLoader(array('template' => $template)), array(
$twig = new Environment(new ArrayLoader(['template' => $template]), [
'debug' => $debug,
'cache' => false,
'optimizations' => 0,
));
]);
$twig->addExtension($extension);
$dumped = null;
@ -54,11 +54,11 @@ class DumpExtensionTest extends TestCase
public function getDumpTags()
{
return array(
array('A{% dump %}B', true, 'AB', array()),
array('A{% set foo="bar"%}B{% dump %}C', true, 'ABC', array('foo' => 'bar')),
array('A{% dump %}B', false, 'AB', null),
);
return [
['A{% dump %}B', true, 'AB', []],
['A{% set foo="bar"%}B{% dump %}C', true, 'ABC', ['foo' => 'bar']],
['A{% dump %}B', false, 'AB', null],
];
}
/**
@ -67,16 +67,16 @@ class DumpExtensionTest extends TestCase
public function testDump($context, $args, $expectedOutput, $debug = true)
{
$extension = new DumpExtension(new VarCloner());
$twig = new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock(), array(
$twig = new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock(), [
'debug' => $debug,
'cache' => false,
'optimizations' => 0,
));
]);
array_unshift($args, $context);
array_unshift($args, $twig);
$dump = \call_user_func_array(array($extension, 'dump'), $args);
$dump = \call_user_func_array([$extension, 'dump'], $args);
if ($debug) {
$this->assertStringStartsWith('<script>', $dump);
@ -88,24 +88,24 @@ class DumpExtensionTest extends TestCase
public function getDumpArgs()
{
return array(
array(array(), array(), '', false),
array(array(), array(), "<pre class=sf-dump id=sf-dump data-indent-pad=\" \">[]\n</pre><script>Sfdump(\"sf-dump\")</script>\n"),
array(
array(),
array(123, 456),
return [
[[], [], '', false],
[[], [], "<pre class=sf-dump id=sf-dump data-indent-pad=\" \">[]\n</pre><script>Sfdump(\"sf-dump\")</script>\n"],
[
[],
[123, 456],
"<pre class=sf-dump id=sf-dump data-indent-pad=\" \"><span class=sf-dump-num>123</span>\n</pre><script>Sfdump(\"sf-dump\")</script>\n"
."<pre class=sf-dump id=sf-dump data-indent-pad=\" \"><span class=sf-dump-num>456</span>\n</pre><script>Sfdump(\"sf-dump\")</script>\n",
),
array(
array('foo' => 'bar'),
array(),
],
[
['foo' => 'bar'],
[],
"<pre class=sf-dump id=sf-dump data-indent-pad=\" \"><span class=sf-dump-note>array:1</span> [<samp>\n"
." \"<span class=sf-dump-key>foo</span>\" => \"<span class=sf-dump-str title=\"3 characters\">bar</span>\"\n"
."</samp>]\n"
."</pre><script>Sfdump(\"sf-dump\")</script>\n",
),
);
],
];
}
public function testCustomDumper()
@ -123,13 +123,13 @@ class DumpExtensionTest extends TestCase
'</pre><script>Sfdump("%s")</script>'
);
$extension = new DumpExtension(new VarCloner(), $dumper);
$twig = new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock(), array(
$twig = new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock(), [
'debug' => true,
'cache' => false,
'optimizations' => 0,
));
]);
$dump = $extension->dump($twig, array(), 'foo');
$dump = $extension->dump($twig, [], 'foo');
$dump = preg_replace('/sf-dump-\d+/', 'sf-dump', $dump);
$this->assertEquals(

View File

@ -21,7 +21,7 @@ class ExpressionExtensionTest extends TestCase
public function testExpressionCreation()
{
$template = "{{ expression('1 == 1') }}";
$twig = new Environment(new ArrayLoader(array('template' => $template)), array('debug' => true, 'cache' => false, 'autoescape' => 'html', 'optimizations' => 0));
$twig = new Environment(new ArrayLoader(['template' => $template]), ['debug' => true, 'cache' => false, 'autoescape' => 'html', 'optimizations' => 0]);
$twig->addExtension(new ExpressionExtension());
$output = $twig->render('template');

View File

@ -15,12 +15,12 @@ use Symfony\Component\Translation\TranslatorInterface;
class StubTranslator implements TranslatorInterface
{
public function trans($id, array $parameters = array(), $domain = null, $locale = null)
public function trans($id, array $parameters = [], $domain = null, $locale = null)
{
return '[trans]'.$id.'[/trans]';
}
public function transChoice($id, $number, array $parameters = array(), $domain = null, $locale = null)
public function transChoice($id, $number, array $parameters = [], $domain = null, $locale = null)
{
return '[trans]'.$id.'[/trans]';
}

View File

@ -24,9 +24,9 @@ class FormExtensionBootstrap3HorizontalLayoutTest extends AbstractBootstrap3Hori
{
use RuntimeLoaderProvider;
protected $testableFeatures = array(
protected $testableFeatures = [
'choice_attr',
);
];
/**
* @var FormRenderer
@ -37,32 +37,32 @@ class FormExtensionBootstrap3HorizontalLayoutTest extends AbstractBootstrap3Hori
{
parent::setUp();
$loader = new StubFilesystemLoader(array(
$loader = new StubFilesystemLoader([
__DIR__.'/../../Resources/views/Form',
__DIR__.'/Fixtures/templates/form',
));
]);
$environment = new Environment($loader, array('strict_variables' => true));
$environment = new Environment($loader, ['strict_variables' => true]);
$environment->addExtension(new TranslationExtension(new StubTranslator()));
$environment->addExtension(new FormExtension());
$rendererEngine = new TwigRendererEngine(array(
$rendererEngine = new TwigRendererEngine([
'bootstrap_3_horizontal_layout.html.twig',
'custom_widgets.html.twig',
), $environment);
], $environment);
$this->renderer = new FormRenderer($rendererEngine, $this->getMockBuilder('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface')->getMock());
$this->registerTwigRuntimeLoader($environment, $this->renderer);
}
protected function renderForm(FormView $view, array $vars = array())
protected function renderForm(FormView $view, array $vars = [])
{
return (string) $this->renderer->renderBlock($view, 'form', $vars);
}
protected function renderLabel(FormView $view, $label = null, array $vars = array())
protected function renderLabel(FormView $view, $label = null, array $vars = [])
{
if (null !== $label) {
$vars += array('label' => $label);
$vars += ['label' => $label];
}
return (string) $this->renderer->searchAndRenderBlock($view, 'label', $vars);
@ -78,27 +78,27 @@ class FormExtensionBootstrap3HorizontalLayoutTest extends AbstractBootstrap3Hori
return (string) $this->renderer->searchAndRenderBlock($view, 'errors');
}
protected function renderWidget(FormView $view, array $vars = array())
protected function renderWidget(FormView $view, array $vars = [])
{
return (string) $this->renderer->searchAndRenderBlock($view, 'widget', $vars);
}
protected function renderRow(FormView $view, array $vars = array())
protected function renderRow(FormView $view, array $vars = [])
{
return (string) $this->renderer->searchAndRenderBlock($view, 'row', $vars);
}
protected function renderRest(FormView $view, array $vars = array())
protected function renderRest(FormView $view, array $vars = [])
{
return (string) $this->renderer->searchAndRenderBlock($view, 'rest', $vars);
}
protected function renderStart(FormView $view, array $vars = array())
protected function renderStart(FormView $view, array $vars = [])
{
return (string) $this->renderer->renderBlock($view, 'form_start', $vars);
}
protected function renderEnd(FormView $view, array $vars = array())
protected function renderEnd(FormView $view, array $vars = [])
{
return (string) $this->renderer->renderBlock($view, 'form_end', $vars);
}

View File

@ -33,29 +33,29 @@ class FormExtensionBootstrap3LayoutTest extends AbstractBootstrap3LayoutTest
{
parent::setUp();
$loader = new StubFilesystemLoader(array(
$loader = new StubFilesystemLoader([
__DIR__.'/../../Resources/views/Form',
__DIR__.'/Fixtures/templates/form',
));
]);
$environment = new Environment($loader, array('strict_variables' => true));
$environment = new Environment($loader, ['strict_variables' => true]);
$environment->addExtension(new TranslationExtension(new StubTranslator()));
$environment->addExtension(new FormExtension());
$rendererEngine = new TwigRendererEngine(array(
$rendererEngine = new TwigRendererEngine([
'bootstrap_3_layout.html.twig',
'custom_widgets.html.twig',
), $environment);
], $environment);
$this->renderer = new FormRenderer($rendererEngine, $this->getMockBuilder('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface')->getMock());
$this->registerTwigRuntimeLoader($environment, $this->renderer);
}
public function testStartTagHasNoActionAttributeWhenActionIsEmpty()
{
$form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, array(
$form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, [
'method' => 'get',
'action' => '',
));
]);
$html = $this->renderStart($form->createView());
@ -64,10 +64,10 @@ class FormExtensionBootstrap3LayoutTest extends AbstractBootstrap3LayoutTest
public function testStartTagHasActionAttributeWhenActionIsZero()
{
$form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, array(
$form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, [
'method' => 'get',
'action' => '0',
));
]);
$html = $this->renderStart($form->createView());
@ -76,18 +76,18 @@ class FormExtensionBootstrap3LayoutTest extends AbstractBootstrap3LayoutTest
public function testMoneyWidgetInIso()
{
$environment = new Environment(new StubFilesystemLoader(array(
$environment = new Environment(new StubFilesystemLoader([
__DIR__.'/../../Resources/views/Form',
__DIR__.'/Fixtures/templates/form',
)), array('strict_variables' => true));
]), ['strict_variables' => true]);
$environment->addExtension(new TranslationExtension(new StubTranslator()));
$environment->addExtension(new FormExtension());
$environment->setCharset('ISO-8859-1');
$rendererEngine = new TwigRendererEngine(array(
$rendererEngine = new TwigRendererEngine([
'bootstrap_3_layout.html.twig',
'custom_widgets.html.twig',
), $environment);
], $environment);
$this->renderer = new FormRenderer($rendererEngine, $this->getMockBuilder('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface')->getMock());
$this->registerTwigRuntimeLoader($environment, $this->renderer);
@ -104,15 +104,15 @@ HTML
, trim($this->renderWidget($view)));
}
protected function renderForm(FormView $view, array $vars = array())
protected function renderForm(FormView $view, array $vars = [])
{
return (string) $this->renderer->renderBlock($view, 'form', $vars);
}
protected function renderLabel(FormView $view, $label = null, array $vars = array())
protected function renderLabel(FormView $view, $label = null, array $vars = [])
{
if (null !== $label) {
$vars += array('label' => $label);
$vars += ['label' => $label];
}
return (string) $this->renderer->searchAndRenderBlock($view, 'label', $vars);
@ -128,27 +128,27 @@ HTML
return (string) $this->renderer->searchAndRenderBlock($view, 'errors');
}
protected function renderWidget(FormView $view, array $vars = array())
protected function renderWidget(FormView $view, array $vars = [])
{
return (string) $this->renderer->searchAndRenderBlock($view, 'widget', $vars);
}
protected function renderRow(FormView $view, array $vars = array())
protected function renderRow(FormView $view, array $vars = [])
{
return (string) $this->renderer->searchAndRenderBlock($view, 'row', $vars);
}
protected function renderRest(FormView $view, array $vars = array())
protected function renderRest(FormView $view, array $vars = [])
{
return (string) $this->renderer->searchAndRenderBlock($view, 'rest', $vars);
}
protected function renderStart(FormView $view, array $vars = array())
protected function renderStart(FormView $view, array $vars = [])
{
return (string) $this->renderer->renderBlock($view, 'form_start', $vars);
}
protected function renderEnd(FormView $view, array $vars = array())
protected function renderEnd(FormView $view, array $vars = [])
{
return (string) $this->renderer->renderBlock($view, 'form_end', $vars);
}

View File

@ -29,9 +29,9 @@ class FormExtensionBootstrap4HorizontalLayoutTest extends AbstractBootstrap4Hori
{
use RuntimeLoaderProvider;
protected $testableFeatures = array(
protected $testableFeatures = [
'choice_attr',
);
];
private $renderer;
@ -39,32 +39,32 @@ class FormExtensionBootstrap4HorizontalLayoutTest extends AbstractBootstrap4Hori
{
parent::setUp();
$loader = new StubFilesystemLoader(array(
$loader = new StubFilesystemLoader([
__DIR__.'/../../Resources/views/Form',
__DIR__.'/Fixtures/templates/form',
));
]);
$environment = new Environment($loader, array('strict_variables' => true));
$environment = new Environment($loader, ['strict_variables' => true]);
$environment->addExtension(new TranslationExtension(new StubTranslator()));
$environment->addExtension(new FormExtension());
$rendererEngine = new TwigRendererEngine(array(
$rendererEngine = new TwigRendererEngine([
'bootstrap_4_horizontal_layout.html.twig',
'custom_widgets.html.twig',
), $environment);
], $environment);
$this->renderer = new FormRenderer($rendererEngine, $this->getMockBuilder('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface')->getMock());
$this->registerTwigRuntimeLoader($environment, $this->renderer);
}
protected function renderForm(FormView $view, array $vars = array())
protected function renderForm(FormView $view, array $vars = [])
{
return (string) $this->renderer->renderBlock($view, 'form', $vars);
}
protected function renderLabel(FormView $view, $label = null, array $vars = array())
protected function renderLabel(FormView $view, $label = null, array $vars = [])
{
if (null !== $label) {
$vars += array('label' => $label);
$vars += ['label' => $label];
}
return (string) $this->renderer->searchAndRenderBlock($view, 'label', $vars);
@ -80,27 +80,27 @@ class FormExtensionBootstrap4HorizontalLayoutTest extends AbstractBootstrap4Hori
return (string) $this->renderer->searchAndRenderBlock($view, 'errors');
}
protected function renderWidget(FormView $view, array $vars = array())
protected function renderWidget(FormView $view, array $vars = [])
{
return (string) $this->renderer->searchAndRenderBlock($view, 'widget', $vars);
}
protected function renderRow(FormView $view, array $vars = array())
protected function renderRow(FormView $view, array $vars = [])
{
return (string) $this->renderer->searchAndRenderBlock($view, 'row', $vars);
}
protected function renderRest(FormView $view, array $vars = array())
protected function renderRest(FormView $view, array $vars = [])
{
return (string) $this->renderer->searchAndRenderBlock($view, 'rest', $vars);
}
protected function renderStart(FormView $view, array $vars = array())
protected function renderStart(FormView $view, array $vars = [])
{
return (string) $this->renderer->renderBlock($view, 'form_start', $vars);
}
protected function renderEnd(FormView $view, array $vars = array())
protected function renderEnd(FormView $view, array $vars = [])
{
return (string) $this->renderer->renderBlock($view, 'form_end', $vars);
}

View File

@ -37,29 +37,29 @@ class FormExtensionBootstrap4LayoutTest extends AbstractBootstrap4LayoutTest
{
parent::setUp();
$loader = new StubFilesystemLoader(array(
$loader = new StubFilesystemLoader([
__DIR__.'/../../Resources/views/Form',
__DIR__.'/Fixtures/templates/form',
));
]);
$environment = new Environment($loader, array('strict_variables' => true));
$environment = new Environment($loader, ['strict_variables' => true]);
$environment->addExtension(new TranslationExtension(new StubTranslator()));
$environment->addExtension(new FormExtension());
$rendererEngine = new TwigRendererEngine(array(
$rendererEngine = new TwigRendererEngine([
'bootstrap_4_layout.html.twig',
'custom_widgets.html.twig',
), $environment);
], $environment);
$this->renderer = new FormRenderer($rendererEngine, $this->getMockBuilder('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface')->getMock());
$this->registerTwigRuntimeLoader($environment, $this->renderer);
}
public function testStartTagHasNoActionAttributeWhenActionIsEmpty()
{
$form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, array(
$form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, [
'method' => 'get',
'action' => '',
));
]);
$html = $this->renderStart($form->createView());
@ -68,10 +68,10 @@ class FormExtensionBootstrap4LayoutTest extends AbstractBootstrap4LayoutTest
public function testStartTagHasActionAttributeWhenActionIsZero()
{
$form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, array(
$form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, [
'method' => 'get',
'action' => '0',
));
]);
$html = $this->renderStart($form->createView());
@ -80,18 +80,18 @@ class FormExtensionBootstrap4LayoutTest extends AbstractBootstrap4LayoutTest
public function testMoneyWidgetInIso()
{
$environment = new Environment(new StubFilesystemLoader(array(
$environment = new Environment(new StubFilesystemLoader([
__DIR__.'/../../Resources/views/Form',
__DIR__.'/Fixtures/templates/form',
)), array('strict_variables' => true));
]), ['strict_variables' => true]);
$environment->addExtension(new TranslationExtension(new StubTranslator()));
$environment->addExtension(new FormExtension());
$environment->setCharset('ISO-8859-1');
$rendererEngine = new TwigRendererEngine(array(
$rendererEngine = new TwigRendererEngine([
'bootstrap_4_layout.html.twig',
'custom_widgets.html.twig',
), $environment);
], $environment);
$this->renderer = new FormRenderer($rendererEngine, $this->getMockBuilder('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface')->getMock());
$this->registerTwigRuntimeLoader($environment, $this->renderer);
@ -108,15 +108,15 @@ HTML
, trim($this->renderWidget($view)));
}
protected function renderForm(FormView $view, array $vars = array())
protected function renderForm(FormView $view, array $vars = [])
{
return (string) $this->renderer->renderBlock($view, 'form', $vars);
}
protected function renderLabel(FormView $view, $label = null, array $vars = array())
protected function renderLabel(FormView $view, $label = null, array $vars = [])
{
if (null !== $label) {
$vars += array('label' => $label);
$vars += ['label' => $label];
}
return (string) $this->renderer->searchAndRenderBlock($view, 'label', $vars);
@ -132,27 +132,27 @@ HTML
return (string) $this->renderer->searchAndRenderBlock($view, 'errors');
}
protected function renderWidget(FormView $view, array $vars = array())
protected function renderWidget(FormView $view, array $vars = [])
{
return (string) $this->renderer->searchAndRenderBlock($view, 'widget', $vars);
}
protected function renderRow(FormView $view, array $vars = array())
protected function renderRow(FormView $view, array $vars = [])
{
return (string) $this->renderer->searchAndRenderBlock($view, 'row', $vars);
}
protected function renderRest(FormView $view, array $vars = array())
protected function renderRest(FormView $view, array $vars = [])
{
return (string) $this->renderer->searchAndRenderBlock($view, 'rest', $vars);
}
protected function renderStart(FormView $view, array $vars = array())
protected function renderStart(FormView $view, array $vars = [])
{
return (string) $this->renderer->renderBlock($view, 'form_start', $vars);
}
protected function renderEnd(FormView $view, array $vars = array())
protected function renderEnd(FormView $view, array $vars = [])
{
return (string) $this->renderer->renderBlock($view, 'form_end', $vars);
}

View File

@ -35,22 +35,22 @@ class FormExtensionDivLayoutTest extends AbstractDivLayoutTest
{
parent::setUp();
$loader = new StubFilesystemLoader(array(
$loader = new StubFilesystemLoader([
__DIR__.'/../../Resources/views/Form',
__DIR__.'/Fixtures/templates/form',
));
]);
$environment = new Environment($loader, array('strict_variables' => true));
$environment = new Environment($loader, ['strict_variables' => true]);
$environment->addExtension(new TranslationExtension(new StubTranslator()));
$environment->addGlobal('global', '');
// the value can be any template that exists
$environment->addGlobal('dynamic_template_name', 'child_label');
$environment->addExtension(new FormExtension());
$rendererEngine = new TwigRendererEngine(array(
$rendererEngine = new TwigRendererEngine([
'form_div_layout.html.twig',
'custom_widgets.html.twig',
), $environment);
], $environment);
$this->renderer = new FormRenderer($rendererEngine, $this->getMockBuilder('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface')->getMock());
$this->registerTwigRuntimeLoader($environment, $this->renderer);
}
@ -62,7 +62,7 @@ class FormExtensionDivLayoutTest extends AbstractDivLayoutTest
->createView()
;
$this->setTheme($view, array('theme_use.html.twig'));
$this->setTheme($view, ['theme_use.html.twig']);
$this->assertMatchesXpath(
$this->renderWidget($view),
@ -77,7 +77,7 @@ class FormExtensionDivLayoutTest extends AbstractDivLayoutTest
->createView()
;
$this->setTheme($view, array('theme_extends.html.twig'));
$this->setTheme($view, ['theme_extends.html.twig']);
$this->assertMatchesXpath(
$this->renderWidget($view),
@ -92,7 +92,7 @@ class FormExtensionDivLayoutTest extends AbstractDivLayoutTest
->createView()
;
$this->renderer->setTheme($view, array('page_dynamic_extends.html.twig'));
$this->renderer->setTheme($view, ['page_dynamic_extends.html.twig']);
$this->assertMatchesXpath(
$this->renderer->searchAndRenderBlock($view, 'row'),
'/div/label[text()="child"]'
@ -101,18 +101,18 @@ class FormExtensionDivLayoutTest extends AbstractDivLayoutTest
public function isSelectedChoiceProvider()
{
return array(
array(true, '0', '0'),
array(true, '1', '1'),
array(true, '', ''),
array(true, '1.23', '1.23'),
array(true, 'foo', 'foo'),
array(true, 'foo10', 'foo10'),
array(true, 'foo', array(1, 'foo', 'foo10')),
return [
[true, '0', '0'],
[true, '1', '1'],
[true, '', ''],
[true, '1.23', '1.23'],
[true, 'foo', 'foo'],
[true, 'foo10', 'foo10'],
[true, 'foo', [1, 'foo', 'foo10']],
array(false, 10, array(1, 'foo', 'foo10')),
array(false, 0, array(1, 'foo', 'foo10')),
);
[false, 10, [1, 'foo', 'foo10']],
[false, 0, [1, 'foo', 'foo10']],
];
}
/**
@ -127,10 +127,10 @@ class FormExtensionDivLayoutTest extends AbstractDivLayoutTest
public function testStartTagHasNoActionAttributeWhenActionIsEmpty()
{
$form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, array(
$form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, [
'method' => 'get',
'action' => '',
));
]);
$html = $this->renderStart($form->createView());
@ -139,10 +139,10 @@ class FormExtensionDivLayoutTest extends AbstractDivLayoutTest
public function testStartTagHasActionAttributeWhenActionIsZero()
{
$form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, array(
$form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, [
'method' => 'get',
'action' => '0',
));
]);
$html = $this->renderStart($form->createView());
@ -151,10 +151,10 @@ class FormExtensionDivLayoutTest extends AbstractDivLayoutTest
public function isRootFormProvider()
{
return array(
array(true, new FormView()),
array(false, new FormView(new FormView())),
);
return [
[true, new FormView()],
[false, new FormView(new FormView())],
];
}
/**
@ -167,18 +167,18 @@ class FormExtensionDivLayoutTest extends AbstractDivLayoutTest
public function testMoneyWidgetInIso()
{
$environment = new Environment(new StubFilesystemLoader(array(
$environment = new Environment(new StubFilesystemLoader([
__DIR__.'/../../Resources/views/Form',
__DIR__.'/Fixtures/templates/form',
)), array('strict_variables' => true));
]), ['strict_variables' => true]);
$environment->addExtension(new TranslationExtension(new StubTranslator()));
$environment->addExtension(new FormExtension());
$environment->setCharset('ISO-8859-1');
$rendererEngine = new TwigRendererEngine(array(
$rendererEngine = new TwigRendererEngine([
'form_div_layout.html.twig',
'custom_widgets.html.twig',
), $environment);
], $environment);
$this->renderer = new FormRenderer($rendererEngine, $this->getMockBuilder('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface')->getMock());
$this->registerTwigRuntimeLoader($environment, $this->renderer);
@ -190,15 +190,15 @@ class FormExtensionDivLayoutTest extends AbstractDivLayoutTest
$this->assertSame('&euro; <input type="text" id="name" name="name" required="required" />', $this->renderWidget($view));
}
protected function renderForm(FormView $view, array $vars = array())
protected function renderForm(FormView $view, array $vars = [])
{
return (string) $this->renderer->renderBlock($view, 'form', $vars);
}
protected function renderLabel(FormView $view, $label = null, array $vars = array())
protected function renderLabel(FormView $view, $label = null, array $vars = [])
{
if (null !== $label) {
$vars += array('label' => $label);
$vars += ['label' => $label];
}
return (string) $this->renderer->searchAndRenderBlock($view, 'label', $vars);
@ -214,27 +214,27 @@ class FormExtensionDivLayoutTest extends AbstractDivLayoutTest
return (string) $this->renderer->searchAndRenderBlock($view, 'errors');
}
protected function renderWidget(FormView $view, array $vars = array())
protected function renderWidget(FormView $view, array $vars = [])
{
return (string) $this->renderer->searchAndRenderBlock($view, 'widget', $vars);
}
protected function renderRow(FormView $view, array $vars = array())
protected function renderRow(FormView $view, array $vars = [])
{
return (string) $this->renderer->searchAndRenderBlock($view, 'row', $vars);
}
protected function renderRest(FormView $view, array $vars = array())
protected function renderRest(FormView $view, array $vars = [])
{
return (string) $this->renderer->searchAndRenderBlock($view, 'rest', $vars);
}
protected function renderStart(FormView $view, array $vars = array())
protected function renderStart(FormView $view, array $vars = [])
{
return (string) $this->renderer->renderBlock($view, 'form_start', $vars);
}
protected function renderEnd(FormView $view, array $vars = array())
protected function renderEnd(FormView $view, array $vars = [])
{
return (string) $this->renderer->renderBlock($view, 'form_end', $vars);
}
@ -246,15 +246,15 @@ class FormExtensionDivLayoutTest extends AbstractDivLayoutTest
public static function themeBlockInheritanceProvider()
{
return array(
array(array('theme.html.twig')),
);
return [
[['theme.html.twig']],
];
}
public static function themeInheritanceProvider()
{
return array(
array(array('parent_label.html.twig'), array('child_label.html.twig')),
);
return [
[['parent_label.html.twig'], ['child_label.html.twig']],
];
}
}

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