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() return PhpCsFixer\Config::create()
->setRules(array( ->setRules([
'@Symfony' => true, '@Symfony' => true,
'@Symfony:risky' => true, '@Symfony:risky' => true,
'@PHPUnit48Migration: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 '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, 'fopen_flags' => false,
'ordered_imports' => true, 'ordered_imports' => true,
'protected_to_private' => false, 'protected_to_private' => false,
// Part of @Symfony:risky in PHP-CS-Fixer 2.13.0. To be removed from the config file once upgrading // 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 // 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) ->setRiskyAllowed(true)
->setFinder( ->setFinder(
PhpCsFixer\Finder::create() PhpCsFixer\Finder::create()
->in(__DIR__.'/src') ->in(__DIR__.'/src')
->append(array(__FILE__)) ->append([__FILE__])
->exclude(array( ->exclude([
// directories containing files with content that is autogenerated by `var_export`, which breaks CS in output code // directories containing files with content that is autogenerated by `var_export`, which breaks CS in output code
'Symfony/Component/DependencyInjection/Tests/Fixtures', 'Symfony/Component/DependencyInjection/Tests/Fixtures',
'Symfony/Component/Routing/Tests/Fixtures/dumper', 'Symfony/Component/Routing/Tests/Fixtures/dumper',
@ -38,7 +38,7 @@ return PhpCsFixer\Config::create()
'Symfony/Bundle/FrameworkBundle/Resources/views/Form', 'Symfony/Bundle/FrameworkBundle/Resources/views/Form',
// explicit trigger_error tests // explicit trigger_error tests
'Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/', 'Symfony/Bridge/PhpUnit/Tests/DeprecationErrorHandler/',
)) ])
// Support for older PHPunit version // Support for older PHPunit version
->notPath('Symfony/Bridge/PhpUnit/SymfonyTestsListener.php') ->notPath('Symfony/Bridge/PhpUnit/SymfonyTestsListener.php')
// file content autogenerated by `var_export` // file content autogenerated by `var_export`

View File

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

View File

@ -65,13 +65,13 @@ class RegisterEventListenersAndSubscribersPass implements CompilerPassInterface
foreach ($taggedSubscribers as $taggedSubscriber) { foreach ($taggedSubscribers as $taggedSubscriber) {
list($id, $tag) = $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) { foreach ($connections as $con) {
if (!isset($this->connections[$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)))); 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)); 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) { foreach ($connections as $con) {
if (!isset($this->connections[$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)))); 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 // 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) private function findAndSortTags($tagName, ContainerBuilder $container)
{ {
$sortedTags = array(); $sortedTags = [];
foreach ($container->findTaggedServiceIds($tagName, true) as $serviceId => $tags) { foreach ($container->findTaggedServiceIds($tagName, true) as $serviceId => $tags) {
foreach ($tags as $attributes) { foreach ($tags as $attributes) {
$priority = isset($attributes['priority']) ? $attributes['priority'] : 0; $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 // Performance optimization
if (empty($choices)) { if (empty($choices)) {
return array(); return [];
} }
// Optimize performance for single-field identifiers. We already // 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 // Attention: This optimization does not check choices for existence
if ($optimize && !$this->choiceList && $this->idReader->isSingleId()) { if ($optimize && !$this->choiceList && $this->idReader->isSingleId()) {
$values = array(); $values = [];
// Maintain order and indices of the given objects // Maintain order and indices of the given objects
foreach ($choices as $i => $object) { foreach ($choices as $i => $object) {
@ -115,7 +115,7 @@ class DoctrineChoiceLoader implements ChoiceLoaderInterface
// statements, consequently no test fails when this code is removed. // statements, consequently no test fails when this code is removed.
// https://github.com/symfony/symfony/pull/8981#issuecomment-24230557 // https://github.com/symfony/symfony/pull/8981#issuecomment-24230557
if (empty($values)) { if (empty($values)) {
return array(); return [];
} }
// Optimize performance in case we have an object loader and // 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()) { if ($optimize && !$this->choiceList && $this->objectLoader && $this->idReader->isSingleId()) {
$unorderedObjects = $this->objectLoader->getEntitiesByIds($this->idReader->getIdField(), $values); $unorderedObjects = $this->objectLoader->getEntitiesByIds($this->idReader->getIdField(), $values);
$objectsById = array(); $objectsById = [];
$objects = array(); $objects = [];
// Maintain order and indices from the given $values // Maintain order and indices from the given $values
// An alternative approach to the following loop is to add the // An alternative approach to the following loop is to add the

View File

@ -43,7 +43,7 @@ class IdReader
$this->om = $om; $this->om = $om;
$this->classMetadata = $classMetadata; $this->classMetadata = $classMetadata;
$this->singleId = 1 === \count($ids); $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); $this->idField = current($ids);
// single field association are resolved, since the schema column could be an int // 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 // Guess type
$entity = current($qb->getRootEntities()); $entity = current($qb->getRootEntities());
$metadata = $qb->getEntityManager()->getClassMetadata($entity); $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; $parameterType = Connection::PARAM_INT_ARRAY;
// Filter out non-integer values (e.g. ""). If we don't, some // 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) { $values = array_values(array_filter($values, function ($v) {
return (string) $v === (string) (int) $v || ctype_digit($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; $parameterType = Connection::PARAM_STR_ARRAY;
// Like above, but we just filter out empty strings. // Like above, but we just filter out empty strings.
@ -83,7 +83,7 @@ class ORMQueryBuilderLoader implements EntityLoaderInterface
$parameterType = Connection::PARAM_STR_ARRAY; $parameterType = Connection::PARAM_STR_ARRAY;
} }
if (!$values) { if (!$values) {
return array(); return [];
} }
return $qb->andWhere($where) return $qb->andWhere($where)

View File

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

View File

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

View File

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

View File

@ -40,7 +40,7 @@ class EntityType extends DoctrineType
}; };
$resolver->setNormalizer('query_builder', $queryBuilderNormalizer); $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) public function getQueryBuilderPartsForCachingHash($queryBuilder)
{ {
return array( return [
$queryBuilder->getQuery()->getSQL(), $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) 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) { 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} * {@inheritdoc}
*/ */
public function getProperties($class, array $context = array()) public function getProperties($class, array $context = [])
{ {
try { try {
$metadata = $this->classMetadataFactory->getMetadataFor($class); $metadata = $this->classMetadataFactory->getMetadataFor($class);
@ -63,7 +63,7 @@ class DoctrineExtractor implements PropertyListExtractorInterface, PropertyTypeE
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function getTypes($class, $property, array $context = array()) public function getTypes($class, $property, array $context = [])
{ {
try { try {
$metadata = $this->classMetadataFactory->getMetadataFor($class); $metadata = $this->classMetadataFactory->getMetadataFor($class);
@ -85,7 +85,7 @@ class DoctrineExtractor implements PropertyListExtractorInterface, PropertyTypeE
$nullable = false; $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; $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, Type::BUILTIN_TYPE_OBJECT,
false, false,
'Doctrine\Common\Collections\Collection', 'Doctrine\Common\Collections\Collection',
true, true,
new Type($collectionKeyType), new Type($collectionKeyType),
new Type(Type::BUILTIN_TYPE_OBJECT, false, $class) new Type(Type::BUILTIN_TYPE_OBJECT, false, $class)
)); )];
} }
if ($metadata instanceof ClassMetadataInfo && class_exists('Doctrine\ORM\Mapping\Embedded') && isset($metadata->embeddedClasses[$property])) { 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)) { if ($metadata->hasField($property)) {
@ -136,30 +136,30 @@ class DoctrineExtractor implements PropertyListExtractorInterface, PropertyTypeE
case DBALType::DATETIMETZ: case DBALType::DATETIMETZ:
case 'vardatetime': case 'vardatetime':
case DBALType::TIME: 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 'date_immutable':
case 'datetime_immutable': case 'datetime_immutable':
case 'datetimetz_immutable': case 'datetimetz_immutable':
case 'time_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': case 'dateinterval':
return array(new Type(Type::BUILTIN_TYPE_OBJECT, $nullable, 'DateInterval')); return [new Type(Type::BUILTIN_TYPE_OBJECT, $nullable, 'DateInterval')];
case DBALType::TARRAY: 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: 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: 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: default:
$builtinType = $this->getPhpType($typeOfField); $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 // the alias for lastUsed works around case insensitivity in PostgreSQL
$sql = 'SELECT class, username, value, lastUsed AS last_used' $sql = 'SELECT class, username, value, lastUsed AS last_used'
.' FROM rememberme_token WHERE series=:series'; .' FROM rememberme_token WHERE series=:series';
$paramValues = array('series' => $series); $paramValues = ['series' => $series];
$paramTypes = array('series' => \PDO::PARAM_STR); $paramTypes = ['series' => \PDO::PARAM_STR];
$stmt = $this->conn->executeQuery($sql, $paramValues, $paramTypes); $stmt = $this->conn->executeQuery($sql, $paramValues, $paramTypes);
$row = $stmt->fetch(\PDO::FETCH_ASSOC); $row = $stmt->fetch(\PDO::FETCH_ASSOC);
@ -71,8 +71,8 @@ class DoctrineTokenProvider implements TokenProviderInterface
public function deleteTokenBySeries($series) public function deleteTokenBySeries($series)
{ {
$sql = 'DELETE FROM rememberme_token WHERE series=:series'; $sql = 'DELETE FROM rememberme_token WHERE series=:series';
$paramValues = array('series' => $series); $paramValues = ['series' => $series];
$paramTypes = array('series' => \PDO::PARAM_STR); $paramTypes = ['series' => \PDO::PARAM_STR];
$this->conn->executeUpdate($sql, $paramValues, $paramTypes); $this->conn->executeUpdate($sql, $paramValues, $paramTypes);
} }
@ -83,16 +83,16 @@ class DoctrineTokenProvider implements TokenProviderInterface
{ {
$sql = 'UPDATE rememberme_token SET value=:value, lastUsed=:lastUsed' $sql = 'UPDATE rememberme_token SET value=:value, lastUsed=:lastUsed'
.' WHERE series=:series'; .' WHERE series=:series';
$paramValues = array( $paramValues = [
'value' => $tokenValue, 'value' => $tokenValue,
'lastUsed' => $lastUsed, 'lastUsed' => $lastUsed,
'series' => $series, 'series' => $series,
); ];
$paramTypes = array( $paramTypes = [
'value' => \PDO::PARAM_STR, 'value' => \PDO::PARAM_STR,
'lastUsed' => DoctrineType::DATETIME, 'lastUsed' => DoctrineType::DATETIME,
'series' => \PDO::PARAM_STR, 'series' => \PDO::PARAM_STR,
); ];
$updated = $this->conn->executeUpdate($sql, $paramValues, $paramTypes); $updated = $this->conn->executeUpdate($sql, $paramValues, $paramTypes);
if ($updated < 1) { if ($updated < 1) {
throw new TokenNotFoundException('No token found.'); throw new TokenNotFoundException('No token found.');
@ -107,20 +107,20 @@ class DoctrineTokenProvider implements TokenProviderInterface
$sql = 'INSERT INTO rememberme_token' $sql = 'INSERT INTO rememberme_token'
.' (class, username, series, value, lastUsed)' .' (class, username, series, value, lastUsed)'
.' VALUES (:class, :username, :series, :value, :lastUsed)'; .' VALUES (:class, :username, :series, :value, :lastUsed)';
$paramValues = array( $paramValues = [
'class' => $token->getClass(), 'class' => $token->getClass(),
'username' => $token->getUsername(), 'username' => $token->getUsername(),
'series' => $token->getSeries(), 'series' => $token->getSeries(),
'value' => $token->getTokenValue(), 'value' => $token->getTokenValue(),
'lastUsed' => $token->getLastUsed(), 'lastUsed' => $token->getLastUsed(),
); ];
$paramTypes = array( $paramTypes = [
'class' => \PDO::PARAM_STR, 'class' => \PDO::PARAM_STR,
'username' => \PDO::PARAM_STR, 'username' => \PDO::PARAM_STR,
'series' => \PDO::PARAM_STR, 'series' => \PDO::PARAM_STR,
'value' => \PDO::PARAM_STR, 'value' => \PDO::PARAM_STR,
'lastUsed' => DoctrineType::DATETIME, 'lastUsed' => DoctrineType::DATETIME,
); ];
$this->conn->executeUpdate($sql, $paramValues, $paramTypes); $this->conn->executeUpdate($sql, $paramValues, $paramTypes);
} }
} }

View File

@ -48,7 +48,7 @@ class EntityUserProvider implements UserProviderInterface
{ {
$repository = $this->getRepository(); $repository = $this->getRepository();
if (null !== $this->property) { if (null !== $this->property) {
$user = $repository->findOneBy(array($this->property => $username)); $user = $repository->findOneBy([$this->property => $username]);
} else { } else {
if (!$repository instanceof UserLoaderInterface) { 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))); 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(); $config = self::createTestConfiguration();
} }
$params = array( $params = [
'driver' => 'pdo_sqlite', 'driver' => 'pdo_sqlite',
'memory' => true, 'memory' => true,
); ];
return EntityManager::create($params, $config); return EntityManager::create($params, $config);
} }
@ -56,7 +56,7 @@ class DoctrineTestHelper
public static function createTestConfiguration() public static function createTestConfiguration()
{ {
$config = new Configuration(); $config = new Configuration();
$config->setEntityNamespaces(array('SymfonyTestsDoctrine' => 'Symfony\Bridge\Doctrine\Tests\Fixtures')); $config->setEntityNamespaces(['SymfonyTestsDoctrine' => 'Symfony\Bridge\Doctrine\Tests\Fixtures']);
$config->setAutoGenerateProxyClasses(true); $config->setAutoGenerateProxyClasses(true);
$config->setProxyDir(\sys_get_temp_dir()); $config->setProxyDir(\sys_get_temp_dir());
$config->setProxyNamespace('SymfonyTests\Doctrine'); $config->setProxyNamespace('SymfonyTests\Doctrine');

View File

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

View File

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

View File

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

View File

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

View File

@ -34,17 +34,17 @@ class ORMQueryBuilderLoaderTest extends TestCase
$em = DoctrineTestHelper::createTestEntityManager(); $em = DoctrineTestHelper::createTestEntityManager();
$query = $this->getMockBuilder('QueryMock') $query = $this->getMockBuilder('QueryMock')
->setMethods(array('setParameter', 'getResult', 'getSql', '_doExecute')) ->setMethods(['setParameter', 'getResult', 'getSql', '_doExecute'])
->getMock(); ->getMock();
$query->expects($this->once()) $query->expects($this->once())
->method('setParameter') ->method('setParameter')
->with('ORMQueryBuilderLoader_getEntitiesByIds_id', array(1, 2), $expectedType) ->with('ORMQueryBuilderLoader_getEntitiesByIds_id', [1, 2], $expectedType)
->willReturn($query); ->willReturn($query);
$qb = $this->getMockBuilder('Doctrine\ORM\QueryBuilder') $qb = $this->getMockBuilder('Doctrine\ORM\QueryBuilder')
->setConstructorArgs(array($em)) ->setConstructorArgs([$em])
->setMethods(array('getQuery')) ->setMethods(['getQuery'])
->getMock(); ->getMock();
$qb->expects($this->once()) $qb->expects($this->once())
@ -55,7 +55,7 @@ class ORMQueryBuilderLoaderTest extends TestCase
->from($classname, 'e'); ->from($classname, 'e');
$loader = new ORMQueryBuilderLoader($qb); $loader = new ORMQueryBuilderLoader($qb);
$loader->getEntitiesByIds('id', array(1, 2)); $loader->getEntitiesByIds('id', [1, 2]);
} }
public function testFilterNonIntegerValues() public function testFilterNonIntegerValues()
@ -63,17 +63,17 @@ class ORMQueryBuilderLoaderTest extends TestCase
$em = DoctrineTestHelper::createTestEntityManager(); $em = DoctrineTestHelper::createTestEntityManager();
$query = $this->getMockBuilder('QueryMock') $query = $this->getMockBuilder('QueryMock')
->setMethods(array('setParameter', 'getResult', 'getSql', '_doExecute')) ->setMethods(['setParameter', 'getResult', 'getSql', '_doExecute'])
->getMock(); ->getMock();
$query->expects($this->once()) $query->expects($this->once())
->method('setParameter') ->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); ->willReturn($query);
$qb = $this->getMockBuilder('Doctrine\ORM\QueryBuilder') $qb = $this->getMockBuilder('Doctrine\ORM\QueryBuilder')
->setConstructorArgs(array($em)) ->setConstructorArgs([$em])
->setMethods(array('getQuery')) ->setMethods(['getQuery'])
->getMock(); ->getMock();
$qb->expects($this->once()) $qb->expects($this->once())
@ -84,7 +84,7 @@ class ORMQueryBuilderLoaderTest extends TestCase
->from('Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity', 'e'); ->from('Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity', 'e');
$loader = new ORMQueryBuilderLoader($qb); $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(); $em = DoctrineTestHelper::createTestEntityManager();
$query = $this->getMockBuilder('QueryMock') $query = $this->getMockBuilder('QueryMock')
->setMethods(array('setParameter', 'getResult', 'getSql', '_doExecute')) ->setMethods(['setParameter', 'getResult', 'getSql', '_doExecute'])
->getMock(); ->getMock();
$query->expects($this->once()) $query->expects($this->once())
->method('setParameter') ->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); ->willReturn($query);
$qb = $this->getMockBuilder('Doctrine\ORM\QueryBuilder') $qb = $this->getMockBuilder('Doctrine\ORM\QueryBuilder')
->setConstructorArgs(array($em)) ->setConstructorArgs([$em])
->setMethods(array('getQuery')) ->setMethods(['getQuery'])
->getMock(); ->getMock();
$qb->expects($this->once()) $qb->expects($this->once())
@ -116,7 +116,7 @@ class ORMQueryBuilderLoaderTest extends TestCase
->from($entityClass, 'e'); ->from($entityClass, 'e');
$loader = new ORMQueryBuilderLoader($qb); $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() public function testEmbeddedIdentifierName()
@ -130,17 +130,17 @@ class ORMQueryBuilderLoaderTest extends TestCase
$em = DoctrineTestHelper::createTestEntityManager(); $em = DoctrineTestHelper::createTestEntityManager();
$query = $this->getMockBuilder('QueryMock') $query = $this->getMockBuilder('QueryMock')
->setMethods(array('setParameter', 'getResult', 'getSql', '_doExecute')) ->setMethods(['setParameter', 'getResult', 'getSql', '_doExecute'])
->getMock(); ->getMock();
$query->expects($this->once()) $query->expects($this->once())
->method('setParameter') ->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); ->willReturn($query);
$qb = $this->getMockBuilder('Doctrine\ORM\QueryBuilder') $qb = $this->getMockBuilder('Doctrine\ORM\QueryBuilder')
->setConstructorArgs(array($em)) ->setConstructorArgs([$em])
->setMethods(array('getQuery')) ->setMethods(['getQuery'])
->getMock(); ->getMock();
$qb->expects($this->once()) $qb->expects($this->once())
->method('getQuery') ->method('getQuery')
@ -150,14 +150,14 @@ class ORMQueryBuilderLoaderTest extends TestCase
->from('Symfony\Bridge\Doctrine\Tests\Fixtures\EmbeddedIdentifierEntity', 'e'); ->from('Symfony\Bridge\Doctrine\Tests\Fixtures\EmbeddedIdentifierEntity', 'e');
$loader = new ORMQueryBuilderLoader($qb); $loader = new ORMQueryBuilderLoader($qb);
$loader->getEntitiesByIds('id.value', array(1, '', 2, 3, 'foo')); $loader->getEntitiesByIds('id.value', [1, '', 2, 3, 'foo']);
} }
public function provideGuidEntityClasses() public function provideGuidEntityClasses()
{ {
return array( return [
array('Symfony\Bridge\Doctrine\Tests\Fixtures\GuidIdEntity'), ['Symfony\Bridge\Doctrine\Tests\Fixtures\GuidIdEntity'],
array('Symfony\Bridge\Doctrine\Tests\Fixtures\UuidIdEntity'), ['Symfony\Bridge\Doctrine\Tests\Fixtures\UuidIdEntity'],
); ];
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

@ -30,7 +30,7 @@ class ManagerRegistryTest extends TestCase
{ {
$container = new \LazyServiceProjectServiceContainer(); $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); $registry->setTestContainer($container);
$foo = $container->get('foo'); $foo = $container->get('foo');

View File

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

View File

@ -38,7 +38,7 @@ class DoctrineFooType extends Type
*/ */
public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform) 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'); $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))); $this->assertTrue($provider->supportsClass(\get_class($user2)));
} }
@ -196,7 +196,7 @@ class EntityUserProviderTest extends TestCase
private function getObjectManager($repository) private function getObjectManager($repository)
{ {
$em = $this->getMockBuilder('\Doctrine\Common\Persistence\ObjectManager') $em = $this->getMockBuilder('\Doctrine\Common\Persistence\ObjectManager')
->setMethods(array('getClassMetadata', 'getRepository')) ->setMethods(['getClassMetadata', 'getRepository'])
->getMockForAbstractClass(); ->getMockForAbstractClass();
$em->expects($this->any()) $em->expects($this->any())
->method('getRepository') ->method('getRepository')
@ -208,8 +208,8 @@ class EntityUserProviderTest extends TestCase
private function createSchema($em) private function createSchema($em)
{ {
$schemaTool = new SchemaTool($em); $schemaTool = new SchemaTool($em);
$schemaTool->createSchema(array( $schemaTool->createSchema([
$em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\User'), $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\User'),
)); ]);
} }
} }

View File

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

View File

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

View File

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

View File

@ -22,7 +22,7 @@ use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
*/ */
class ChromePhpHandler extends BaseChromePhpHandler class ChromePhpHandler extends BaseChromePhpHandler
{ {
private $headers = array(); private $headers = [];
/** /**
* @var Response * @var Response
@ -40,7 +40,7 @@ class ChromePhpHandler extends BaseChromePhpHandler
if (!preg_match(static::USER_AGENT_REGEX, $event->getRequest()->headers->get('User-Agent'))) { if (!preg_match(static::USER_AGENT_REGEX, $event->getRequest()->headers->get('User-Agent'))) {
$this->sendHeaders = false; $this->sendHeaders = false;
$this->headers = array(); $this->headers = [];
return; return;
} }
@ -49,7 +49,7 @@ class ChromePhpHandler extends BaseChromePhpHandler
foreach ($this->headers as $header => $content) { foreach ($this->headers as $header => $content) {
$this->response->headers->set($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 class FirePHPHandler extends BaseFirePHPHandler
{ {
private $headers = array(); private $headers = [];
/** /**
* @var Response * @var Response
@ -42,7 +42,7 @@ class FirePHPHandler extends BaseFirePHPHandler
if (!preg_match('{\bFirePHP/\d+\.\d+\b}', $request->headers->get('User-Agent')) if (!preg_match('{\bFirePHP/\d+\.\d+\b}', $request->headers->get('User-Agent'))
&& !$request->headers->has('X-FirePHP-Version')) { && !$request->headers->has('X-FirePHP-Version')) {
self::$sendHeaders = false; self::$sendHeaders = false;
$this->headers = array(); $this->headers = [];
return; return;
} }
@ -51,7 +51,7 @@ class FirePHPHandler extends BaseFirePHPHandler
foreach ($this->headers as $header => $content) { foreach ($this->headers as $header => $content) {
$this->response->headers->set($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 \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; $records['extra']['token'] = null;
if (null !== $token = $this->tokenStorage->getToken()) { if (null !== $token = $this->tokenStorage->getToken()) {
$records['extra']['token'] = array( $records['extra']['token'] = [
'username' => $token->getUsername(), 'username' => $token->getUsername(),
'authenticated' => $token->isAuthenticated(), 'authenticated' => $token->isAuthenticated(),
'roles' => array_map(function ($role) { return $role->getRole(); }, $token->getRoles()), 'roles' => array_map(function ($role) { return $role->getRole(); }, $token->getRoles()),
); ];
} }
return $records; return $records;

View File

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

View File

@ -38,13 +38,13 @@ class ConsoleHandlerTest extends TestCase
public function testIsHandling() public function testIsHandling()
{ {
$handler = new ConsoleHandler(); $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 * @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 = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface')->getMock();
$output $output
@ -53,7 +53,7 @@ class ConsoleHandlerTest extends TestCase
->will($this->returnValue($verbosity)) ->will($this->returnValue($verbosity))
; ;
$handler = new ConsoleHandler($output, true, $map); $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' '->isHandling returns correct value depending on console verbosity and log level'
); );
@ -61,7 +61,7 @@ class ConsoleHandlerTest extends TestCase
$levelName = Logger::getLevelName($level); $levelName = Logger::getLevelName($level);
$levelName = sprintf('%-9s', $levelName); $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); $realOutput->setVerbosity($verbosity);
if ($realOutput->isDebug()) { if ($realOutput->isDebug()) {
$log = "16:21:54 $levelName [app] My info message\n"; $log = "16:21:54 $levelName [app] My info message\n";
@ -74,38 +74,38 @@ class ConsoleHandlerTest extends TestCase
->with($log, false); ->with($log, false);
$handler = new ConsoleHandler($realOutput, true, $map); $handler = new ConsoleHandler($realOutput, true, $map);
$infoRecord = array( $infoRecord = [
'message' => 'My info message', 'message' => 'My info message',
'context' => array(), 'context' => [],
'level' => $level, 'level' => $level,
'level_name' => Logger::getLevelName($level), 'level_name' => Logger::getLevelName($level),
'channel' => 'app', 'channel' => 'app',
'datetime' => new \DateTime('2013-05-29 16:21:54'), 'datetime' => new \DateTime('2013-05-29 16:21:54'),
'extra' => array(), 'extra' => [],
); ];
$this->assertFalse($handler->handle($infoRecord), 'The handler finished handling the log.'); $this->assertFalse($handler->handle($infoRecord), 'The handler finished handling the log.');
} }
public function provideVerbosityMappingTests() public function provideVerbosityMappingTests()
{ {
return array( return [
array(OutputInterface::VERBOSITY_QUIET, Logger::ERROR, true), [OutputInterface::VERBOSITY_QUIET, Logger::ERROR, true],
array(OutputInterface::VERBOSITY_QUIET, Logger::WARNING, false), [OutputInterface::VERBOSITY_QUIET, Logger::WARNING, false],
array(OutputInterface::VERBOSITY_NORMAL, Logger::WARNING, true), [OutputInterface::VERBOSITY_NORMAL, Logger::WARNING, true],
array(OutputInterface::VERBOSITY_NORMAL, Logger::NOTICE, false), [OutputInterface::VERBOSITY_NORMAL, Logger::NOTICE, false],
array(OutputInterface::VERBOSITY_VERBOSE, Logger::NOTICE, true), [OutputInterface::VERBOSITY_VERBOSE, Logger::NOTICE, true],
array(OutputInterface::VERBOSITY_VERBOSE, Logger::INFO, false), [OutputInterface::VERBOSITY_VERBOSE, Logger::INFO, false],
array(OutputInterface::VERBOSITY_VERY_VERBOSE, Logger::INFO, true), [OutputInterface::VERBOSITY_VERY_VERBOSE, Logger::INFO, true],
array(OutputInterface::VERBOSITY_VERY_VERBOSE, Logger::DEBUG, false), [OutputInterface::VERBOSITY_VERY_VERBOSE, Logger::DEBUG, false],
array(OutputInterface::VERBOSITY_DEBUG, Logger::DEBUG, true), [OutputInterface::VERBOSITY_DEBUG, Logger::DEBUG, true],
array(OutputInterface::VERBOSITY_DEBUG, Logger::EMERGENCY, true), [OutputInterface::VERBOSITY_DEBUG, Logger::EMERGENCY, true],
array(OutputInterface::VERBOSITY_NORMAL, Logger::NOTICE, true, array( [OutputInterface::VERBOSITY_NORMAL, Logger::NOTICE, true, [
OutputInterface::VERBOSITY_NORMAL => Logger::NOTICE, OutputInterface::VERBOSITY_NORMAL => Logger::NOTICE,
)), ]],
array(OutputInterface::VERBOSITY_DEBUG, Logger::NOTICE, true, array( [OutputInterface::VERBOSITY_DEBUG, Logger::NOTICE, true, [
OutputInterface::VERBOSITY_NORMAL => Logger::NOTICE, OutputInterface::VERBOSITY_NORMAL => Logger::NOTICE,
)), ]],
); ];
} }
public function testVerbosityChanged() public function testVerbosityChanged()
@ -122,10 +122,10 @@ class ConsoleHandlerTest extends TestCase
->will($this->returnValue(OutputInterface::VERBOSITY_DEBUG)) ->will($this->returnValue(OutputInterface::VERBOSITY_DEBUG))
; ;
$handler = new ConsoleHandler($output); $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' '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' '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 = new ConsoleHandler(null, false);
$handler->setOutput($output); $handler->setOutput($output);
$infoRecord = array( $infoRecord = [
'message' => 'My info message', 'message' => 'My info message',
'context' => array(), 'context' => [],
'level' => Logger::INFO, 'level' => Logger::INFO,
'level_name' => Logger::getLevelName(Logger::INFO), 'level_name' => Logger::getLevelName(Logger::INFO),
'channel' => 'app', 'channel' => 'app',
'datetime' => new \DateTime('2013-05-29 16:21:54'), '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.'); $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 = new RequestStack();
$requestStack->push(Request::create($url)); $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)); $this->assertEquals($expected, $strategy->isHandlerActivated($record));
} }
public function isActivatedProvider() public function isActivatedProvider()
{ {
return array( return [
array('/test', array('level' => Logger::DEBUG), false), ['/test', ['level' => Logger::DEBUG], false],
array('/foo', array('level' => Logger::DEBUG, 'context' => $this->getContextException(404)), false), ['/foo', ['level' => Logger::DEBUG, 'context' => $this->getContextException(404)], false],
array('/baz/bar', array('level' => Logger::ERROR, 'context' => $this->getContextException(404)), false), ['/baz/bar', ['level' => Logger::ERROR, 'context' => $this->getContextException(404)], false],
array('/foo', array('level' => Logger::ERROR, 'context' => $this->getContextException(404)), false), ['/foo', ['level' => Logger::ERROR, 'context' => $this->getContextException(404)], false],
array('/foo', array('level' => Logger::ERROR, 'context' => $this->getContextException(500)), true), ['/foo', ['level' => Logger::ERROR, 'context' => $this->getContextException(500)], true],
array('/test', array('level' => Logger::ERROR), true), ['/test', ['level' => Logger::ERROR], true],
array('/baz', array('level' => Logger::ERROR, 'context' => $this->getContextException(404)), true), ['/baz', ['level' => Logger::ERROR, 'context' => $this->getContextException(404)], true],
array('/baz', array('level' => Logger::ERROR, 'context' => $this->getContextException(500)), true), ['/baz', ['level' => Logger::ERROR, 'context' => $this->getContextException(500)], true],
); ];
} }
protected function getContextException($code) 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() 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 = $this->getMockBuilder(TokenStorageInterface::class)->getMock();
$tokenStorage->method('getToken')->willReturn($token); $tokenStorage->method('getToken')->willReturn($token);
$processor = new TokenProcessor($tokenStorage); $processor = new TokenProcessor($tokenStorage);
$record = array('extra' => array()); $record = ['extra' => []];
$record = $processor($record); $record = $processor($record);
$this->assertArrayHasKey('token', $record['extra']); $this->assertArrayHasKey('token', $record['extra']);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -18,15 +18,15 @@ class DnsMockTest extends TestCase
{ {
protected function tearDown() protected function tearDown()
{ {
DnsMock::withMockedHosts(array()); DnsMock::withMockedHosts([]);
} }
public function testCheckdnsrr() public function testCheckdnsrr()
{ {
DnsMock::withMockedHosts(array('example.com' => array(array('type' => 'MX')))); DnsMock::withMockedHosts(['example.com' => [['type' => 'MX']]]);
$this->assertTrue(DnsMock::checkdnsrr('example.com')); $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->assertFalse(DnsMock::checkdnsrr('example.com'));
$this->assertTrue(DnsMock::checkdnsrr('example.com', 'a')); $this->assertTrue(DnsMock::checkdnsrr('example.com', 'a'));
$this->assertTrue(DnsMock::checkdnsrr('example.com', 'any')); $this->assertTrue(DnsMock::checkdnsrr('example.com', 'any'));
@ -35,34 +35,34 @@ class DnsMockTest extends TestCase
public function testGetmxrr() public function testGetmxrr()
{ {
DnsMock::withMockedHosts(array( DnsMock::withMockedHosts([
'example.com' => array(array( 'example.com' => [[
'type' => 'MX', 'type' => 'MX',
'host' => 'mx.example.com', 'host' => 'mx.example.com',
'pri' => 10, 'pri' => 10,
)), ]],
)); ]);
$this->assertFalse(DnsMock::getmxrr('foobar.com', $mxhosts, $weight)); $this->assertFalse(DnsMock::getmxrr('foobar.com', $mxhosts, $weight));
$this->assertTrue(DnsMock::getmxrr('example.com', $mxhosts, $weight)); $this->assertTrue(DnsMock::getmxrr('example.com', $mxhosts, $weight));
$this->assertSame(array('mx.example.com'), $mxhosts); $this->assertSame(['mx.example.com'], $mxhosts);
$this->assertSame(array(10), $weight); $this->assertSame([10], $weight);
} }
public function testGethostbyaddr() public function testGethostbyaddr()
{ {
DnsMock::withMockedHosts(array( DnsMock::withMockedHosts([
'example.com' => array( 'example.com' => [
array( [
'type' => 'A', 'type' => 'A',
'ip' => '1.2.3.4', 'ip' => '1.2.3.4',
), ],
array( [
'type' => 'AAAA', 'type' => 'AAAA',
'ipv6' => '::12', 'ipv6' => '::12',
), ],
), ],
)); ]);
$this->assertSame('::21', DnsMock::gethostbyaddr('::21')); $this->assertSame('::21', DnsMock::gethostbyaddr('::21'));
$this->assertSame('example.com', DnsMock::gethostbyaddr('::12')); $this->assertSame('example.com', DnsMock::gethostbyaddr('::12'));
@ -71,18 +71,18 @@ class DnsMockTest extends TestCase
public function testGethostbyname() public function testGethostbyname()
{ {
DnsMock::withMockedHosts(array( DnsMock::withMockedHosts([
'example.com' => array( 'example.com' => [
array( [
'type' => 'AAAA', 'type' => 'AAAA',
'ipv6' => '::12', 'ipv6' => '::12',
), ],
array( [
'type' => 'A', 'type' => 'A',
'ip' => '1.2.3.4', 'ip' => '1.2.3.4',
), ],
), ],
)); ]);
$this->assertSame('foobar.com', DnsMock::gethostbyname('foobar.com')); $this->assertSame('foobar.com', DnsMock::gethostbyname('foobar.com'));
$this->assertSame('1.2.3.4', DnsMock::gethostbyname('example.com')); $this->assertSame('1.2.3.4', DnsMock::gethostbyname('example.com'));
@ -90,59 +90,59 @@ class DnsMockTest extends TestCase
public function testGethostbynamel() public function testGethostbynamel()
{ {
DnsMock::withMockedHosts(array( DnsMock::withMockedHosts([
'example.com' => array( 'example.com' => [
array( [
'type' => 'A', 'type' => 'A',
'ip' => '1.2.3.4', 'ip' => '1.2.3.4',
), ],
array( [
'type' => 'A', 'type' => 'A',
'ip' => '2.3.4.5', 'ip' => '2.3.4.5',
), ],
), ],
)); ]);
$this->assertFalse(DnsMock::gethostbynamel('foobar.com')); $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() public function testDnsGetRecord()
{ {
DnsMock::withMockedHosts(array( DnsMock::withMockedHosts([
'example.com' => array( 'example.com' => [
array( [
'type' => 'A', 'type' => 'A',
'ip' => '1.2.3.4', 'ip' => '1.2.3.4',
), ],
array( [
'type' => 'PTR', 'type' => 'PTR',
'ip' => '2.3.4.5', 'ip' => '2.3.4.5',
), ],
), ],
)); ]);
$records = array( $records = [
array( [
'host' => 'example.com', 'host' => 'example.com',
'class' => 'IN', 'class' => 'IN',
'ttl' => 1, 'ttl' => 1,
'type' => 'A', 'type' => 'A',
'ip' => '1.2.3.4', 'ip' => '1.2.3.4',
), ],
$ptr = array( $ptr = [
'host' => 'example.com', 'host' => 'example.com',
'class' => 'IN', 'class' => 'IN',
'ttl' => 1, 'ttl' => 1,
'type' => 'PTR', 'type' => 'PTR',
'ip' => '2.3.4.5', 'ip' => '2.3.4.5',
), ],
); ];
$this->assertFalse(DnsMock::dns_get_record('foobar.com')); $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'));
$this->assertSame($records, DnsMock::dns_get_record('example.com', DNS_ALL)); $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($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'); $prevRoot = getenv('COMPOSER_ROOT_VERSION');
putenv("COMPOSER_ROOT_VERSION=$PHPUNIT_VERSION.99"); 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 // --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 : '')); putenv('COMPOSER_ROOT_VERSION'.(false !== $prevRoot ? '='.$prevRoot : ''));
if ($exit) { if ($exit) {
exit($exit); exit($exit);
@ -145,9 +145,9 @@ EOPHP
} }
global $argv, $argc; global $argv, $argc;
$argv = isset($_SERVER['argv']) ? $_SERVER['argv'] : array(); $argv = isset($_SERVER['argv']) ? $_SERVER['argv'] : [];
$argc = isset($_SERVER['argc']) ? $_SERVER['argc'] : 0; $argc = isset($_SERVER['argc']) ? $_SERVER['argc'] : 0;
$components = array(); $components = [];
$cmd = array_map('escapeshellarg', $argv); $cmd = array_map('escapeshellarg', $argv);
$exit = 0; $exit = 0;
@ -182,7 +182,7 @@ if ('\\' === DIRECTORY_SEPARATOR) {
if ($components) { if ($components) {
$skippedTests = isset($_SERVER['SYMFONY_PHPUNIT_SKIPPED_TESTS']) ? $_SERVER['SYMFONY_PHPUNIT_SKIPPED_TESTS'] : false; $skippedTests = isset($_SERVER['SYMFONY_PHPUNIT_SKIPPED_TESTS']) ? $_SERVER['SYMFONY_PHPUNIT_SKIPPED_TESTS'] : false;
$runningProcs = array(); $runningProcs = [];
foreach ($components as $component) { foreach ($components as $component) {
// Run phpunit tests in parallel // Run phpunit tests in parallel
@ -193,7 +193,7 @@ if ($components) {
$c = escapeshellarg($component); $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; $runningProcs[$component] = $proc;
} else { } else {
$exit = 1; $exit = 1;
@ -203,7 +203,7 @@ if ($components) {
while ($runningProcs) { while ($runningProcs) {
usleep(300000); usleep(300000);
$terminatedProcs = array(); $terminatedProcs = [];
foreach ($runningProcs as $component => $proc) { foreach ($runningProcs as $component => $proc) {
$procStatus = proc_get_status($proc); $procStatus = proc_get_status($proc);
if (!$procStatus['running']) { if (!$procStatus['running']) {
@ -214,7 +214,7 @@ if ($components) {
} }
foreach ($terminatedProcs as $component => $procStatus) { foreach ($terminatedProcs as $component => $procStatus) {
foreach (array('out', 'err') as $file) { foreach (['out', 'err'] as $file) {
$file = "$component/phpunit.std$file"; $file = "$component/phpunit.std$file";
readfile($file); readfile($file);
unlink($file); unlink($file);
@ -224,7 +224,7 @@ if ($components) {
// STATUS_STACK_BUFFER_OVERRUN (-1073740791/0xC0000409) // STATUS_STACK_BUFFER_OVERRUN (-1073740791/0xC0000409)
// STATUS_ACCESS_VIOLATION (-1073741819/0xC0000005) // STATUS_ACCESS_VIOLATION (-1073741819/0xC0000005)
// STATUS_HEAP_CORRUPTION (-1073740940/0xC0000374) // 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; $exit = $procStatus;
echo "\033[41mKO\033[0m $component\n\n"; echo "\033[41mKO\033[0m $component\n\n";
} else { } else {
@ -236,7 +236,7 @@ if ($components) {
if (!class_exists('SymfonyBlacklistSimplePhpunit', false)) { if (!class_exists('SymfonyBlacklistSimplePhpunit', false)) {
class SymfonyBlacklistSimplePhpunit {} class SymfonyBlacklistSimplePhpunit {}
} }
array_splice($argv, 1, 0, array('--colors=always')); array_splice($argv, 1, 0, ['--colors=always']);
$_SERVER['argv'] = $argv; $_SERVER['argv'] = $argv;
$_SERVER['argc'] = ++$argc; $_SERVER['argc'] = ++$argc;
include "$PHPUNIT_DIR/phpunit-$PHPUNIT_VERSION/phpunit"; include "$PHPUNIT_DIR/phpunit-$PHPUNIT_VERSION/phpunit";

View File

@ -69,6 +69,6 @@ class PhpDumperTest extends TestCase
$dumper->setProxyDumper(new ProxyDumper()); $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 $initialized = false;
public $configured = false; public $configured = false;
public $called = false; public $called = false;
public $arguments = array(); public $arguments = [];
public function __construct($arguments = array()) public function __construct($arguments = [])
{ {
$this->arguments = $arguments; $this->arguments = $arguments;
} }
public static function getInstance($arguments = array()) public static function getInstance($arguments = [])
{ {
$obj = new self($arguments); $obj = new self($arguments);
$obj->called = true; $obj->called = true;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -48,10 +48,10 @@ class TranslationExtension extends AbstractExtension
*/ */
public function getFilters() public function getFilters()
{ {
return array( return [
new TwigFilter('trans', array($this, 'trans')), new TwigFilter('trans', [$this, 'trans']),
new TwigFilter('transchoice', array($this, 'transchoice')), new TwigFilter('transchoice', [$this, 'transchoice']),
); ];
} }
/** /**
@ -61,7 +61,7 @@ class TranslationExtension extends AbstractExtension
*/ */
public function getTokenParsers() public function getTokenParsers()
{ {
return array( return [
// {% trans %}Symfony is great!{% endtrans %} // {% trans %}Symfony is great!{% endtrans %}
new TransTokenParser(), new TransTokenParser(),
@ -72,7 +72,7 @@ class TranslationExtension extends AbstractExtension
// {% trans_default_domain "foobar" %} // {% trans_default_domain "foobar" %}
new TransDefaultDomainTokenParser(), new TransDefaultDomainTokenParser(),
); ];
} }
/** /**
@ -80,7 +80,7 @@ class TranslationExtension extends AbstractExtension
*/ */
public function getNodeVisitors() public function getNodeVisitors()
{ {
return array($this->getTranslationNodeVisitor(), new TranslationDefaultDomainNodeVisitor()); return [$this->getTranslationNodeVisitor(), new TranslationDefaultDomainNodeVisitor()];
} }
public function getTranslationNodeVisitor() public function getTranslationNodeVisitor()
@ -88,7 +88,7 @@ class TranslationExtension extends AbstractExtension
return $this->translationNodeVisitor ?: $this->translationNodeVisitor = new TranslationNodeVisitor(); 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) { if (null === $this->translator) {
return strtr($message, $arguments); return strtr($message, $arguments);
@ -97,13 +97,13 @@ class TranslationExtension extends AbstractExtension
return $this->translator->trans($message, $arguments, $domain, $locale); 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) { if (null === $this->translator) {
return strtr($message, $arguments); 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() public function getFunctions()
{ {
return array( return [
new TwigFunction('link', array($this, 'link')), new TwigFunction('link', [$this, 'link']),
new TwigFunction('preload', array($this, 'preload')), new TwigFunction('preload', [$this, 'preload']),
new TwigFunction('dns_prefetch', array($this, 'dnsPrefetch')), new TwigFunction('dns_prefetch', [$this, 'dnsPrefetch']),
new TwigFunction('preconnect', array($this, 'preconnect')), new TwigFunction('preconnect', [$this, 'preconnect']),
new TwigFunction('prefetch', array($this, 'prefetch')), new TwigFunction('prefetch', [$this, 'prefetch']),
new TwigFunction('prerender', array($this, 'prerender')), new TwigFunction('prerender', [$this, 'prerender']),
); ];
} }
/** /**
@ -51,11 +51,11 @@ class WebLinkExtension extends AbstractExtension
* *
* @param string $uri The relation URI * @param string $uri The relation URI
* @param string $rel The relation type (e.g. "preload", "prefetch", "prerender" or "dns-prefetch") * @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 * @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()) { if (!$request = $this->requestStack->getMasterRequest()) {
return $uri; return $uri;
@ -76,11 +76,11 @@ class WebLinkExtension extends AbstractExtension
* Preloads a resource. * Preloads a resource.
* *
* @param string $uri A public path * @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 * @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); return $this->link($uri, 'preload', $attributes);
} }
@ -89,11 +89,11 @@ class WebLinkExtension extends AbstractExtension
* Resolves a resource origin as early as possible. * Resolves a resource origin as early as possible.
* *
* @param string $uri A public path * @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 * @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); 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). * Initiates a early connection to a resource (DNS resolution, TCP handshake, TLS negotiation).
* *
* @param string $uri A public path * @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 * @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); return $this->link($uri, 'preconnect', $attributes);
} }
@ -115,11 +115,11 @@ class WebLinkExtension extends AbstractExtension
* Indicates to the client that it should prefetch this resource. * Indicates to the client that it should prefetch this resource.
* *
* @param string $uri A public path * @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 * @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); return $this->link($uri, 'prefetch', $attributes);
} }
@ -128,11 +128,11 @@ class WebLinkExtension extends AbstractExtension
* Indicates to the client that it should prerender this resource . * Indicates to the client that it should prerender this resource .
* *
* @param string $uri A public path * @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 * @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); return $this->link($uri, 'prerender', $attributes);
} }

View File

@ -28,10 +28,10 @@ class YamlExtension extends AbstractExtension
*/ */
public function getFilters() public function getFilters()
{ {
return array( return [
new TwigFilter('yaml_encode', array($this, 'encode')), new TwigFilter('yaml_encode', [$this, 'encode']),
new TwigFilter('yaml_dump', array($this, 'dump')), new TwigFilter('yaml_dump', [$this, 'dump']),
); ];
} }
public function encode($input, $inline = 0, $dumpObjects = 0) 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) public function __construct($varPrefix, Node $values = null, int $lineno, string $tag = null)
{ {
$nodes = array(); $nodes = [];
if (null !== $values) { if (null !== $values) {
$nodes['values'] = $values; $nodes['values'] = $values;
} }
parent::__construct($nodes, array(), $lineno, $tag); parent::__construct($nodes, [], $lineno, $tag);
$this->varPrefix = $varPrefix; $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 // Only insert the label into the array if it is not empty
if (!twig_test_empty($label->getAttribute('value'))) { if (!twig_test_empty($label->getAttribute('value'))) {
$originalVariables = $variables; $originalVariables = $variables;
$variables = new ArrayExpression(array(), $lineno); $variables = new ArrayExpression([], $lineno);
$labelKey = new ConstantExpression('label', $lineno); $labelKey = new ConstantExpression('label', $lineno);
if (null !== $originalVariables) { 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) 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) 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) 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) 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) 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) { if (null !== $domain) {
$nodes['domain'] = $domain; $nodes['domain'] = $domain;
} }
@ -43,14 +43,14 @@ class TransNode extends Node
$nodes['locale'] = $locale; $nodes['locale'] = $locale;
} }
parent::__construct($nodes, array(), $lineno, $tag); parent::__construct($nodes, [], $lineno, $tag);
} }
public function compile(Compiler $compiler) public function compile(Compiler $compiler)
{ {
$compiler->addDebugInfo($this); $compiler->addDebugInfo($this);
$defaults = new ArrayExpression(array(), -1); $defaults = new ArrayExpression([], -1);
if ($this->hasNode('vars') && ($vars = $this->getNode('vars')) instanceof ArrayExpression) { if ($this->hasNode('vars') && ($vars = $this->getNode('vars')) instanceof ArrayExpression) {
$defaults = $this->getNode('vars'); $defaults = $this->getNode('vars');
$vars = null; $vars = null;
@ -109,7 +109,7 @@ class TransNode extends Node
} elseif ($body instanceof TextNode) { } elseif ($body instanceof TextNode) {
$msg = $body->getAttribute('data'); $msg = $body->getAttribute('data');
} else { } else {
return array($body, $vars); return [$body, $vars];
} }
preg_match_all('/(?<!%)%([^%]+)%/', $msg, $matches); 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 class Scope
{ {
private $parent; private $parent;
private $data = array(); private $data = [];
private $left = false; private $left = false;
public function __construct(self $parent = null) public function __construct(self $parent = null)

View File

@ -56,7 +56,7 @@ class TranslationDefaultDomainNodeVisitor extends AbstractNodeVisitor
$name = new AssignNameExpression($var, $node->getTemplateLine()); $name = new AssignNameExpression($var, $node->getTemplateLine());
$this->scope->set('domain', new NameExpression($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; 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'); $arguments = $node->getNode('arguments');
$ind = 'trans' === $node->getNode('filter')->getAttribute('value') ? 1 : 2; $ind = 'trans' === $node->getNode('filter')->getAttribute('value') ? 1 : 2;
if ($this->isNamedArguments($arguments)) { if ($this->isNamedArguments($arguments)) {
@ -74,7 +74,7 @@ class TranslationDefaultDomainNodeVisitor extends AbstractNodeVisitor
} else { } else {
if (!$arguments->hasNode($ind)) { if (!$arguments->hasNode($ind)) {
if (!$arguments->hasNode($ind - 1)) { 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')); $arguments->setNode($ind, $this->scope->get('domain'));

View File

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

View File

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

View File

@ -23,7 +23,7 @@ class DebugCommandTest extends TestCase
public function testDebugCommand() public function testDebugCommand()
{ {
$tester = $this->createCommandTester(); $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->assertEquals(0, $ret, 'Returns 0 in case of success');
$this->assertContains('Functions', trim($tester->getDisplay())); $this->assertContains('Functions', trim($tester->getDisplay()));
@ -33,12 +33,12 @@ class DebugCommandTest extends TestCase
{ {
// these paths aren't realistic, // these paths aren't realistic,
// they're configured to force the line separator // they're configured to force the line separator
$tester = $this->createCommandTester(array( $tester = $this->createCommandTester([
'Acme' => array('extractor', 'extractor'), 'Acme' => ['extractor', 'extractor'],
'!Acme' => array('extractor', 'extractor'), '!Acme' => ['extractor', 'extractor'],
FilesystemLoader::MAIN_NAMESPACE => array('extractor', 'extractor'), FilesystemLoader::MAIN_NAMESPACE => ['extractor', 'extractor'],
)); ]);
$ret = $tester->execute(array(), array('decorated' => false)); $ret = $tester->execute([], ['decorated' => false]);
$ds = \DIRECTORY_SEPARATOR; $ds = \DIRECTORY_SEPARATOR;
$loaderPaths = <<<TXT $loaderPaths = <<<TXT
Loader Paths Loader Paths
@ -62,9 +62,9 @@ TXT;
$this->assertContains($loaderPaths, trim($tester->getDisplay(true))); $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 ($paths as $namespace => $relDirs) {
foreach ($relDirs as $relDir) { foreach ($relDirs as $relDir) {
$filesystemLoader->addPath($relDir, $namespace); $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'); $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\DateType');
$view = $form->createView(); $view = $form->createView();
$this->renderWidget($view, array('label' => 'foo')); $this->renderWidget($view, ['label' => 'foo']);
$html = $this->renderLabel($view); $html = $this->renderLabel($view);
$this->assertMatchesXpath($html, $this->assertMatchesXpath($html,
@ -31,11 +31,11 @@ abstract class AbstractBootstrap3HorizontalLayoutTest extends AbstractBootstrap3
public function testLabelDoesNotRenderFieldAttributes() public function testLabelDoesNotRenderFieldAttributes()
{ {
$form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType'); $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType');
$html = $this->renderLabel($form->createView(), null, array( $html = $this->renderLabel($form->createView(), null, [
'attr' => array( 'attr' => [
'class' => 'my&class', 'class' => 'my&class',
), ],
)); ]);
$this->assertMatchesXpath($html, $this->assertMatchesXpath($html,
'/label '/label
@ -48,11 +48,11 @@ abstract class AbstractBootstrap3HorizontalLayoutTest extends AbstractBootstrap3
public function testLabelWithCustomAttributesPassedDirectly() public function testLabelWithCustomAttributesPassedDirectly()
{ {
$form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType'); $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType');
$html = $this->renderLabel($form->createView(), null, array( $html = $this->renderLabel($form->createView(), null, [
'label_attr' => array( 'label_attr' => [
'class' => 'my&class', 'class' => 'my&class',
), ],
)); ]);
$this->assertMatchesXpath($html, $this->assertMatchesXpath($html,
'/label '/label
@ -65,11 +65,11 @@ abstract class AbstractBootstrap3HorizontalLayoutTest extends AbstractBootstrap3
public function testLabelWithCustomTextAndCustomAttributesPassedDirectly() public function testLabelWithCustomTextAndCustomAttributesPassedDirectly()
{ {
$form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType'); $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType');
$html = $this->renderLabel($form->createView(), 'Custom label', array( $html = $this->renderLabel($form->createView(), 'Custom label', [
'label_attr' => array( 'label_attr' => [
'class' => 'my&class', 'class' => 'my&class',
), ],
)); ]);
$this->assertMatchesXpath($html, $this->assertMatchesXpath($html,
'/label '/label
@ -82,14 +82,14 @@ abstract class AbstractBootstrap3HorizontalLayoutTest extends AbstractBootstrap3
public function testLabelWithCustomTextAsOptionAndCustomAttributesPassedDirectly() 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', 'label' => 'Custom label',
)); ]);
$html = $this->renderLabel($form->createView(), null, array( $html = $this->renderLabel($form->createView(), null, [
'label_attr' => array( 'label_attr' => [
'class' => 'my&class', 'class' => 'my&class',
), ],
)); ]);
$this->assertMatchesXpath($html, $this->assertMatchesXpath($html,
'/label '/label
@ -102,10 +102,10 @@ abstract class AbstractBootstrap3HorizontalLayoutTest extends AbstractBootstrap3
public function testStartTag() 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', 'method' => 'get',
'action' => 'http://example.com/directory', 'action' => 'http://example.com/directory',
)); ]);
$html = $this->renderStart($form->createView()); $html = $this->renderStart($form->createView());
@ -114,25 +114,25 @@ abstract class AbstractBootstrap3HorizontalLayoutTest extends AbstractBootstrap3
public function testStartTagWithOverriddenVars() 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', 'method' => 'put',
'action' => 'http://example.com/directory', 'action' => 'http://example.com/directory',
)); ]);
$html = $this->renderStart($form->createView(), array( $html = $this->renderStart($form->createView(), [
'method' => 'post', 'method' => 'post',
'action' => 'http://foo.com/directory', 'action' => 'http://foo.com/directory',
)); ]);
$this->assertSame('<form name="form" method="post" action="http://foo.com/directory" class="form-horizontal">', $html); $this->assertSame('<form name="form" method="post" action="http://foo.com/directory" class="form-horizontal">', $html);
} }
public function testStartTagForMultipartForm() 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', 'method' => 'get',
'action' => 'http://example.com/directory', 'action' => 'http://example.com/directory',
)) ])
->add('file', 'Symfony\Component\Form\Extension\Core\Type\FileType') ->add('file', 'Symfony\Component\Form\Extension\Core\Type\FileType')
->getForm(); ->getForm();
@ -143,14 +143,14 @@ abstract class AbstractBootstrap3HorizontalLayoutTest extends AbstractBootstrap3
public function testStartTagWithExtraAttributes() 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', 'method' => 'get',
'action' => 'http://example.com/directory', 'action' => 'http://example.com/directory',
)); ]);
$html = $this->renderStart($form->createView(), array( $html = $this->renderStart($form->createView(), [
'attr' => array('class' => 'foobar'), 'attr' => ['class' => 'foobar'],
)); ]);
$this->assertSame('<form name="form" method="get" action="http://example.com/directory" class="foobar form-horizontal">', $html); $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'); $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\CheckboxType');
$view = $form->createView(); $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); $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'); $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\DateType');
$view = $form->createView(); $view = $form->createView();
$this->renderWidget($view, array('label' => 'foo')); $this->renderWidget($view, ['label' => 'foo']);
$html = $this->renderLabel($view); $html = $this->renderLabel($view);
$this->assertMatchesXpath($html, $this->assertMatchesXpath($html,
@ -63,11 +63,11 @@ abstract class AbstractBootstrap4HorizontalLayoutTest extends AbstractBootstrap4
public function testLabelDoesNotRenderFieldAttributes() public function testLabelDoesNotRenderFieldAttributes()
{ {
$form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType'); $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType');
$html = $this->renderLabel($form->createView(), null, array( $html = $this->renderLabel($form->createView(), null, [
'attr' => array( 'attr' => [
'class' => 'my&class', 'class' => 'my&class',
), ],
)); ]);
$this->assertMatchesXpath($html, $this->assertMatchesXpath($html,
'/label '/label
@ -80,11 +80,11 @@ abstract class AbstractBootstrap4HorizontalLayoutTest extends AbstractBootstrap4
public function testLabelWithCustomAttributesPassedDirectly() public function testLabelWithCustomAttributesPassedDirectly()
{ {
$form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType'); $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType');
$html = $this->renderLabel($form->createView(), null, array( $html = $this->renderLabel($form->createView(), null, [
'label_attr' => array( 'label_attr' => [
'class' => 'my&class', 'class' => 'my&class',
), ],
)); ]);
$this->assertMatchesXpath($html, $this->assertMatchesXpath($html,
'/label '/label
@ -97,11 +97,11 @@ abstract class AbstractBootstrap4HorizontalLayoutTest extends AbstractBootstrap4
public function testLabelWithCustomTextAndCustomAttributesPassedDirectly() public function testLabelWithCustomTextAndCustomAttributesPassedDirectly()
{ {
$form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType'); $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType');
$html = $this->renderLabel($form->createView(), 'Custom label', array( $html = $this->renderLabel($form->createView(), 'Custom label', [
'label_attr' => array( 'label_attr' => [
'class' => 'my&class', 'class' => 'my&class',
), ],
)); ]);
$this->assertMatchesXpath($html, $this->assertMatchesXpath($html,
'/label '/label
@ -114,14 +114,14 @@ abstract class AbstractBootstrap4HorizontalLayoutTest extends AbstractBootstrap4
public function testLabelWithCustomTextAsOptionAndCustomAttributesPassedDirectly() 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', 'label' => 'Custom label',
)); ]);
$html = $this->renderLabel($form->createView(), null, array( $html = $this->renderLabel($form->createView(), null, [
'label_attr' => array( 'label_attr' => [
'class' => 'my&class', 'class' => 'my&class',
), ],
)); ]);
$this->assertMatchesXpath($html, $this->assertMatchesXpath($html,
'/label '/label
@ -134,11 +134,11 @@ abstract class AbstractBootstrap4HorizontalLayoutTest extends AbstractBootstrap4
public function testLegendOnExpandedType() 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', 'label' => 'Custom label',
'expanded' => true, 'expanded' => true,
'choices' => array('Choice&A' => '&a', 'Choice&B' => '&b'), 'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'],
)); ]);
$view = $form->createView(); $view = $form->createView();
$this->renderWidget($view); $this->renderWidget($view);
$html = $this->renderLabel($view); $html = $this->renderLabel($view);
@ -153,10 +153,10 @@ abstract class AbstractBootstrap4HorizontalLayoutTest extends AbstractBootstrap4
public function testStartTag() 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', 'method' => 'get',
'action' => 'http://example.com/directory', 'action' => 'http://example.com/directory',
)); ]);
$html = $this->renderStart($form->createView()); $html = $this->renderStart($form->createView());
@ -165,25 +165,25 @@ abstract class AbstractBootstrap4HorizontalLayoutTest extends AbstractBootstrap4
public function testStartTagWithOverriddenVars() 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', 'method' => 'put',
'action' => 'http://example.com/directory', 'action' => 'http://example.com/directory',
)); ]);
$html = $this->renderStart($form->createView(), array( $html = $this->renderStart($form->createView(), [
'method' => 'post', 'method' => 'post',
'action' => 'http://foo.com/directory', 'action' => 'http://foo.com/directory',
)); ]);
$this->assertSame('<form name="form" method="post" action="http://foo.com/directory">', $html); $this->assertSame('<form name="form" method="post" action="http://foo.com/directory">', $html);
} }
public function testStartTagForMultipartForm() 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', 'method' => 'get',
'action' => 'http://example.com/directory', 'action' => 'http://example.com/directory',
)) ])
->add('file', 'Symfony\Component\Form\Extension\Core\Type\FileType') ->add('file', 'Symfony\Component\Form\Extension\Core\Type\FileType')
->getForm(); ->getForm();
@ -194,14 +194,14 @@ abstract class AbstractBootstrap4HorizontalLayoutTest extends AbstractBootstrap4
public function testStartTagWithExtraAttributes() 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', 'method' => 'get',
'action' => 'http://example.com/directory', 'action' => 'http://example.com/directory',
)); ]);
$html = $this->renderStart($form->createView(), array( $html = $this->renderStart($form->createView(), [
'attr' => array('class' => 'foobar'), 'attr' => ['class' => 'foobar'],
)); ]);
$this->assertSame('<form name="form" method="get" action="http://example.com/directory" class="foobar">', $html); $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'); $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\CheckboxType');
$view = $form->createView(); $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); $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() public function getClassNameProvider()
{ {
return array( return [
array('F\Q\N\Foo', '<abbr title="F\Q\N\Foo">Foo</abbr>'), ['F\Q\N\Foo', '<abbr title="F\Q\N\Foo">Foo</abbr>'],
array('Bare', '<abbr title="Bare">Bare</abbr>'), ['Bare', '<abbr title="Bare">Bare</abbr>'],
); ];
} }
public function getMethodNameProvider() public function getMethodNameProvider()
{ {
return array( return [
array('F\Q\N\Foo::Method', '<abbr title="F\Q\N\Foo">Foo</abbr>::Method()'), ['F\Q\N\Foo::Method', '<abbr title="F\Q\N\Foo">Foo</abbr>::Method()'],
array('Bare::Method', '<abbr title="Bare">Bare</abbr>::Method()'), ['Bare::Method', '<abbr title="Bare">Bare</abbr>::Method()'],
array('Closure', '<abbr title="Closure">Closure</abbr>'), ['Closure', '<abbr title="Closure">Closure</abbr>'],
array('Method', '<abbr title="Method">Method</abbr>()'), ['Method', '<abbr title="Method">Method</abbr>()'],
); ];
} }
public function testGetName() public function testGetName()

View File

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

View File

@ -21,7 +21,7 @@ class ExpressionExtensionTest extends TestCase
public function testExpressionCreation() public function testExpressionCreation()
{ {
$template = "{{ expression('1 == 1') }}"; $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()); $twig->addExtension(new ExpressionExtension());
$output = $twig->render('template'); $output = $twig->render('template');

View File

@ -15,12 +15,12 @@ use Symfony\Component\Translation\TranslatorInterface;
class StubTranslator implements 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]'; 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]'; return '[trans]'.$id.'[/trans]';
} }

View File

@ -24,9 +24,9 @@ class FormExtensionBootstrap3HorizontalLayoutTest extends AbstractBootstrap3Hori
{ {
use RuntimeLoaderProvider; use RuntimeLoaderProvider;
protected $testableFeatures = array( protected $testableFeatures = [
'choice_attr', 'choice_attr',
); ];
/** /**
* @var FormRenderer * @var FormRenderer
@ -37,32 +37,32 @@ class FormExtensionBootstrap3HorizontalLayoutTest extends AbstractBootstrap3Hori
{ {
parent::setUp(); parent::setUp();
$loader = new StubFilesystemLoader(array( $loader = new StubFilesystemLoader([
__DIR__.'/../../Resources/views/Form', __DIR__.'/../../Resources/views/Form',
__DIR__.'/Fixtures/templates/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 TranslationExtension(new StubTranslator()));
$environment->addExtension(new FormExtension()); $environment->addExtension(new FormExtension());
$rendererEngine = new TwigRendererEngine(array( $rendererEngine = new TwigRendererEngine([
'bootstrap_3_horizontal_layout.html.twig', 'bootstrap_3_horizontal_layout.html.twig',
'custom_widgets.html.twig', 'custom_widgets.html.twig',
), $environment); ], $environment);
$this->renderer = new FormRenderer($rendererEngine, $this->getMockBuilder('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface')->getMock()); $this->renderer = new FormRenderer($rendererEngine, $this->getMockBuilder('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface')->getMock());
$this->registerTwigRuntimeLoader($environment, $this->renderer); $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); 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) { if (null !== $label) {
$vars += array('label' => $label); $vars += ['label' => $label];
} }
return (string) $this->renderer->searchAndRenderBlock($view, 'label', $vars); return (string) $this->renderer->searchAndRenderBlock($view, 'label', $vars);
@ -78,27 +78,27 @@ class FormExtensionBootstrap3HorizontalLayoutTest extends AbstractBootstrap3Hori
return (string) $this->renderer->searchAndRenderBlock($view, 'errors'); 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); 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); 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); 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); 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); return (string) $this->renderer->renderBlock($view, 'form_end', $vars);
} }

View File

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

View File

@ -29,9 +29,9 @@ class FormExtensionBootstrap4HorizontalLayoutTest extends AbstractBootstrap4Hori
{ {
use RuntimeLoaderProvider; use RuntimeLoaderProvider;
protected $testableFeatures = array( protected $testableFeatures = [
'choice_attr', 'choice_attr',
); ];
private $renderer; private $renderer;
@ -39,32 +39,32 @@ class FormExtensionBootstrap4HorizontalLayoutTest extends AbstractBootstrap4Hori
{ {
parent::setUp(); parent::setUp();
$loader = new StubFilesystemLoader(array( $loader = new StubFilesystemLoader([
__DIR__.'/../../Resources/views/Form', __DIR__.'/../../Resources/views/Form',
__DIR__.'/Fixtures/templates/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 TranslationExtension(new StubTranslator()));
$environment->addExtension(new FormExtension()); $environment->addExtension(new FormExtension());
$rendererEngine = new TwigRendererEngine(array( $rendererEngine = new TwigRendererEngine([
'bootstrap_4_horizontal_layout.html.twig', 'bootstrap_4_horizontal_layout.html.twig',
'custom_widgets.html.twig', 'custom_widgets.html.twig',
), $environment); ], $environment);
$this->renderer = new FormRenderer($rendererEngine, $this->getMockBuilder('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface')->getMock()); $this->renderer = new FormRenderer($rendererEngine, $this->getMockBuilder('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface')->getMock());
$this->registerTwigRuntimeLoader($environment, $this->renderer); $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); 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) { if (null !== $label) {
$vars += array('label' => $label); $vars += ['label' => $label];
} }
return (string) $this->renderer->searchAndRenderBlock($view, 'label', $vars); return (string) $this->renderer->searchAndRenderBlock($view, 'label', $vars);
@ -80,27 +80,27 @@ class FormExtensionBootstrap4HorizontalLayoutTest extends AbstractBootstrap4Hori
return (string) $this->renderer->searchAndRenderBlock($view, 'errors'); 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); 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); 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); 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); 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); return (string) $this->renderer->renderBlock($view, 'form_end', $vars);
} }

View File

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

View File

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

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