Merge branch '4.3' into 4.4

* 4.3:
  [OptionsResolve] Revert change in tests for a not-merged change in code
  [HttpClient] fix handling of 3xx with no Location header - ignore Content-Length when no body is expected
  [Workflow] Made the configuration more robust for the 'property' key
  [Security/Core] make NativePasswordEncoder use sodium to validate passwords when possible
  #30432 fix an error message
  fix paths to detect code owners
  [HttpClient] ignore the body of responses to HEAD requests
  [Validator] Ensure numeric subpaths do not cause errors on PHP 7.4
  [SecurityBundle] Fix wrong assertion
  Remove unused local variables in tests
  [Yaml][Parser] Remove the getLastLineNumberBeforeDeprecation() internal unused method
  Make sure to collect child forms created on *_SET_DATA events
  [WebProfilerBundle] Improve display in Email panel for dark theme
  do not render errors for checkboxes twice
This commit is contained in:
Nicolas Grekas 2019-10-28 21:30:34 +01:00
commit 05f7f4e147
87 changed files with 304 additions and 168 deletions

26
.github/CODEOWNERS vendored
View File

@ -6,7 +6,7 @@
/src/Symfony/Component/ErrorRenderer/* @yceruto
# Form
/src/Symfony/Bridge/Twig/Extension/FormExtension.php @xabbuh
/src/Symfony/Bridge/Twig/Form/* @xabbuh
/src/Symfony/Bridge/Twig/Form/ @xabbuh
/src/Symfony/Bridge/Twig/Node/FormThemeNode.php @xabbuh
/src/Symfony/Bridge/Twig/Node/RenderBlockNode.php @xabbuh
/src/Symfony/Bridge/Twig/Node/SearchAndRenderBlockNode.php @xabbuh
@ -15,36 +15,36 @@
/src/Symfony/Bridge/Twig/Tests/TokenParser/FormThemeTokenParserTest.php @xabbuh
/src/Symfony/Bridge/Twig/TokenParser/FormThemeTokenParser.php @xabbuh
/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/FormPass.php @xabbuh
/src/Symfony/Bundle/FrameworkBundle/Resources/views/* @xabbuh
/src/Symfony/Bundle/FrameworkBundle/Resources/views/ @xabbuh
/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/FormHelper.php @xabbuh
/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/FormPassTest.php @xabbuh
/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/FormHelperTableLayoutTest.php @xabbuh
/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/FormHelperDivLayoutTest.php @xabbuh
/src/Symfony/Component/Form/* @xabbuh
/src/Symfony/Component/Form/ @xabbuh
# HttpKernel
/src/Symfony/Component/HttpKernel/Log/Logger.php @dunglas
# LDAP
/src/Symfony/Component/Ldap/* @csarrazi
/src/Symfony/Component/Ldap/ @csarrazi
# Lock
/src/Symfony/Component/Lock/* @jderusse
/src/Symfony/Component/Lock/ @jderusse
# Messenger
/src/Symfony/Bridge/Doctrine/Messenger/* @sroze
/src/Symfony/Component/Messenger/* @sroze
/src/Symfony/Bridge/Doctrine/Messenger/ @sroze
/src/Symfony/Component/Messenger/ @sroze
# PropertyInfo
/src/Symfony/Component/PropertyInfo/* @dunglas
/src/Symfony/Bridge/Doctrine/PropertyInfo/* @dunglas
/src/Symfony/Component/PropertyInfo/ @dunglas
/src/Symfony/Bridge/Doctrine/PropertyInfo/ @dunglas
# Serializer
/src/Symfony/Component/Serializer/* @dunglas
/src/Symfony/Component/Serializer/ @dunglas
# TwigBundle
/src/Symfony/Bundle/TwigBundle/ErrorRenderer/TwigHtmlErrorRenderer.php @yceruto
# WebLink
/src/Symfony/Component/WebLink/* @dunglas
/src/Symfony/Component/WebLink/ @dunglas
# Workflow
/src/Symfony/Bridge/Twig/Extension/WorkflowExtension.php @lyrixx
/src/Symfony/Bridge/Twig/Tests/Extension/WorkflowExtensionTest.php @lyrixx
/src/Symfony/Bundle/FrameworkBundle/Command/WorkflowDumpCommand.php @lyrixx
/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/ValidateWorkflowsPass.php @lyrixx
/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/WorkflowGuardListenerPass.php @lyrixx
/src/Symfony/Component/Workflow/* @lyrixx
/src/Symfony/Component/Workflow/ @lyrixx
# Yaml
/src/Symfony/Component/Yaml/* @xabbuh
/src/Symfony/Component/Yaml/ @xabbuh

View File

@ -187,7 +187,7 @@ class EntityTypeTest extends BaseTypeTest
public function testConfigureQueryBuilderWithNonQueryBuilderAndNonClosure()
{
$this->expectException('Symfony\Component\OptionsResolver\Exception\InvalidOptionsException');
$field = $this->factory->createNamed('name', static::TESTED_TYPE, null, [
$this->factory->createNamed('name', static::TESTED_TYPE, null, [
'em' => 'default',
'class' => self::SINGLE_IDENT_CLASS,
'query_builder' => new \stdClass(),

View File

@ -33,7 +33,6 @@ class SearchAndRenderBlockNode extends FunctionExpression
preg_match('/_([^_]+)$/', $this->getAttribute('name'), $matches);
$label = null;
$arguments = iterator_to_array($this->getNode('arguments'));
$blockNameSuffix = $matches[1];

View File

@ -82,7 +82,6 @@ col-sm-10
<div class="{{ block('form_group_class') }}">
{{- form_widget(form) -}}
{{- form_help(form) -}}
{{- form_errors(form) -}}
</div>{#--#}
</div>
{%- endblock checkbox_row %}

View File

@ -180,10 +180,10 @@ class AppVariableTest extends TestCase
$flashMessages = $this->setFlashMessages();
$this->assertEquals($flashMessages, $this->appVariable->getFlashes([]));
$flashMessages = $this->setFlashMessages();
$this->setFlashMessages();
$this->assertEquals([], $this->appVariable->getFlashes('this-does-not-exist'));
$flashMessages = $this->setFlashMessages();
$this->setFlashMessages();
$this->assertEquals(
['this-does-not-exist' => []],
$this->appVariable->getFlashes(['this-does-not-exist'])

View File

@ -52,7 +52,7 @@ class LintCommandTest extends TestCase
$filename = $this->createFile('');
unlink($filename);
$ret = $tester->execute(['filename' => [$filename]], ['decorated' => false]);
$tester->execute(['filename' => [$filename]], ['decorated' => false]);
}
public function testLintFileCompileTimeException()

View File

@ -34,7 +34,7 @@ class StopwatchExtensionTest extends TestCase
$twig->addExtension(new StopwatchExtension($this->getStopwatch($events)));
try {
$nodes = $twig->render('template');
$twig->render('template');
} catch (RuntimeError $e) {
throw $e->getPrevious();
}

View File

@ -60,14 +60,14 @@ class TranslationExtensionTest extends TestCase
{
$this->expectException('Twig\Error\SyntaxError');
$this->expectExceptionMessage('Unexpected token. Twig was looking for the "with", "from", or "into" keyword in "index" at line 3.');
$output = $this->getTemplate("{% trans \n\nfoo %}{% endtrans %}")->render();
$this->getTemplate("{% trans \n\nfoo %}{% endtrans %}")->render();
}
public function testTransComplexBody()
{
$this->expectException('Twig\Error\SyntaxError');
$this->expectExceptionMessage('A message inside a trans tag must be a simple text in "index" at line 2.');
$output = $this->getTemplate("{% trans %}\n{{ 1 + 2 }}{% endtrans %}")->render();
$this->getTemplate("{% trans %}\n{{ 1 + 2 }}{% endtrans %}")->render();
}
/**
@ -77,7 +77,7 @@ class TranslationExtensionTest extends TestCase
{
$this->expectException('Twig\Error\SyntaxError');
$this->expectExceptionMessage('A message inside a transchoice tag must be a simple text in "index" at line 2.');
$output = $this->getTemplate("{% transchoice count %}\n{{ 1 + 2 }}{% endtranschoice %}")->render();
$this->getTemplate("{% transchoice count %}\n{{ 1 + 2 }}{% endtranschoice %}")->render();
}
public function getTransTests()

View File

@ -510,7 +510,6 @@ class TextDescriptor extends Descriptor
$tableHeaders = ['Order', 'Callable', 'Priority'];
$tableRows = [];
$order = 1;
foreach ($eventListeners as $order => $listener) {
$tableRows[] = [sprintf('#%d', $order + 1), $this->formatCallable($listener), $eventDispatcher->getListenerPriority($event, $listener)];
}

View File

@ -322,7 +322,7 @@ class Configuration implements ConfigurationInterface
->end()
->end()
->scalarNode('property')
->defaultValue('marking')
->defaultNull() // In Symfony 5.0, set "marking" as default property
->end()
->scalarNode('service')
->cannotBeEmpty()
@ -500,6 +500,14 @@ class Configuration implements ConfigurationInterface
return $v;
})
->end()
->validate()
->ifTrue(function ($v) {
return isset($v['marking_store']['property'])
&& (!isset($v['marking_store']['type']) || 'method' !== $v['marking_store']['type'])
;
})
->thenInvalid('"property" option is only supported by the "method" marking store.')
->end()
->end()
->end()
->end()

View File

@ -697,7 +697,7 @@ class FrameworkExtension extends Extension
if ('method' === $workflow['marking_store']['type']) {
$markingStoreDefinition->setArguments([
'state_machine' === $type, //single state
$workflow['marking_store']['property'],
$workflow['marking_store']['property'] ?? 'marking',
]);
} else {
foreach ($workflow['marking_store']['arguments'] as $argument) {

View File

@ -272,8 +272,7 @@ abstract class ControllerTraitTest extends TestCase
$this->expectException('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException');
$controller = $this->createController();
/* @var BinaryFileResponse $response */
$response = $controller->file('some-file.txt', 'test.php');
$controller->file('some-file.txt', 'test.php');
}
public function testIsGranted()

View File

@ -27,7 +27,7 @@ class TestExtension extends Extension implements PrependExtensionInterface
public function load(array $configs, ContainerBuilder $container)
{
$configuration = $this->getConfiguration($configs, $container);
$config = $this->processConfiguration($configuration, $configs);
$this->processConfiguration($configuration, $configs);
$container->setAlias('test.annotation_reader', new Alias('annotation_reader', true));
}

View File

@ -59,7 +59,7 @@ class SessionTest extends AbstractWebTestCase
}
// set flash
$crawler = $client->request('GET', '/session_setflash/Hello%20world.');
$client->request('GET', '/session_setflash/Hello%20world.');
// check flash displays on redirect
$this->assertStringContainsString('Hello world.', $client->followRedirect()->text());

View File

@ -61,7 +61,7 @@ class AbstractFactoryTest extends TestCase
$options['failure_handler'] = $serviceId;
}
list($container, $authProviderId, $listenerId, $entryPointId) = $this->callFactory('foo', $options, 'user_provider', 'entry_point');
list($container) = $this->callFactory('foo', $options, 'user_provider', 'entry_point');
$definition = $container->getDefinition('abstract_listener.foo');
$arguments = $definition->getArguments();
@ -99,7 +99,7 @@ class AbstractFactoryTest extends TestCase
$options['success_handler'] = $serviceId;
}
list($container, $authProviderId, $listenerId, $entryPointId) = $this->callFactory('foo', $options, 'user_provider', 'entry_point');
list($container) = $this->callFactory('foo', $options, 'user_provider', 'entry_point');
$definition = $container->getDefinition('abstract_listener.foo');
$arguments = $definition->getArguments();

View File

@ -159,7 +159,7 @@ class GuardAuthenticationFactoryTest extends TestCase
'authenticators' => ['authenticator123', 'authenticatorABC'],
'entry_point' => 'authenticatorABC',
];
list($container, $entryPointId) = $this->executeCreate($config, null);
list(, $entryPointId) = $this->executeCreate($config, null);
$this->assertEquals('authenticatorABC', $entryPointId);
}
@ -172,7 +172,7 @@ class GuardAuthenticationFactoryTest extends TestCase
$userProviderId = 'my_user_provider';
$factory = new GuardAuthenticationFactory();
list($providerId, $listenerId, $entryPointId) = $factory->create($container, $id, $config, $userProviderId, $defaultEntryPointId);
list(, , $entryPointId) = $factory->create($container, $id, $config, $userProviderId, $defaultEntryPointId);
return [$container, $entryPointId];
}

View File

@ -24,7 +24,7 @@ class MissingUserProviderTest extends AbstractWebTestCase
$response = $client->getResponse();
$this->assertSame(500, $response->getStatusCode());
$this->stringContains('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException', $response->getContent());
$this->stringContains('"default" firewall requires a user provider but none was defined.', $response->getContent());
$this->assertStringContainsString('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException', $response->getContent());
$this->assertStringContainsString('"default" firewall requires a user provider but none was defined', html_entity_decode($response->getContent()));
}
}

View File

@ -46,6 +46,8 @@
--base-4: #666;
--base-5: #444;
--base-6: #222;
--card-label-background: #eee;
--card-label-color: var(--base-6);
}
.theme-dark {
@ -85,6 +87,8 @@
--base-4: #666;
--base-5: #e0e0e0;
--base-6: #f5f5f5;
--card-label-background: var(--tab-active-background);
--card-label-color: var(--tab-active-color);
}
{# Basic styles
@ -436,8 +440,8 @@ table tbody td.num-col {
margin-top: 0;
}
.card .label {
background-color: #EEE;
color: var(--base-6);
background-color: var(--card-label-background);
color: var(--card-label-color);
}
{# Status

View File

@ -201,7 +201,7 @@ class CookieTest extends TestCase
{
$this->expectException('UnexpectedValueException');
$this->expectExceptionMessage('The cookie expiration time "string" is not valid.');
$cookie = new Cookie('foo', 'bar', 'string');
new Cookie('foo', 'bar', 'string');
}
public function testSameSite()

View File

@ -70,7 +70,7 @@ class MaxIdLengthAdapterTest extends TestCase
{
$this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException');
$this->expectExceptionMessage('Namespace must be 26 chars max, 40 given ("----------------------------------------")');
$cache = $this->getMockBuilder(MaxIdLengthAdapter::class)
$this->getMockBuilder(MaxIdLengthAdapter::class)
->setConstructorArgs([str_repeat('-', 40)])
->getMock();
}

View File

@ -19,7 +19,7 @@ class DelegatingLoaderTest extends TestCase
{
public function testConstructor()
{
$loader = new DelegatingLoader($resolver = new LoaderResolver());
new DelegatingLoader($resolver = new LoaderResolver());
$this->assertTrue(true, '__construct() takes a loader resolver as its first argument');
}

View File

@ -67,7 +67,7 @@ EOF
$loadedClass = 123;
$res = new ClassExistenceResource('MissingFooClass', false);
new ClassExistenceResource('MissingFooClass', false);
$this->assertSame(123, $loadedClass);
} finally {

View File

@ -67,7 +67,7 @@ class DirectoryResourceTest extends TestCase
{
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessageRegExp('/The directory ".*" does not exist./');
$resource = new DirectoryResource('/____foo/foobar'.mt_rand(1, 999999));
new DirectoryResource('/____foo/foobar'.mt_rand(1, 999999));
}
public function testIsFresh()
@ -165,7 +165,7 @@ class DirectoryResourceTest extends TestCase
{
$resource = new DirectoryResource($this->directory, '/\.(foo|xml)$/');
$unserialized = unserialize(serialize($resource));
unserialize(serialize($resource));
$this->assertSame(realpath($this->directory), $resource->getResource());
$this->assertSame('/\.(foo|xml)$/', $resource->getPattern());

View File

@ -57,7 +57,7 @@ class FileResourceTest extends TestCase
{
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessageRegExp('/The file ".*" does not exist./');
$resource = new FileResource('/____foo/foobar'.mt_rand(1, 999999));
new FileResource('/____foo/foobar'.mt_rand(1, 999999));
}
public function testIsFresh()
@ -76,7 +76,7 @@ class FileResourceTest extends TestCase
public function testSerializeUnserialize()
{
$unserialized = unserialize(serialize($this->resource));
unserialize(serialize($this->resource));
$this->assertSame(realpath($this->file), $this->resource->getResource());
}

View File

@ -579,7 +579,7 @@ class ApplicationTest extends TestCase
// Subnamespace + plural
try {
$a = $application->find('foo3:');
$application->find('foo3:');
$this->fail('->find() should throw an Symfony\Component\Console\Exception\CommandNotFoundException if a command is ambiguous because of a subnamespace, with alternatives');
} catch (\Exception $e) {
$this->assertInstanceOf('Symfony\Component\Console\Exception\CommandNotFoundException', $e);

View File

@ -104,7 +104,7 @@ class ProgressIndicatorTest extends TestCase
{
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage('Must have at least 2 indicator value characters.');
$bar = new ProgressIndicator($this->getOutputStream(), null, 100, ['1']);
new ProgressIndicator($this->getOutputStream(), null, 100, ['1']);
}
public function testCannotStartAlreadyStartedIndicator()

View File

@ -486,7 +486,7 @@ class DebugClassLoader
}
if (isset($dirFiles[$file])) {
return $real .= $dirFiles[$file];
return $real.$dirFiles[$file];
}
$kFile = strtolower($file);
@ -505,7 +505,7 @@ class DebugClassLoader
self::$darwinCache[$kDir][1] = $dirFiles;
}
return $real .= $dirFiles[$kFile];
return $real.$dirFiles[$kFile];
}
/**

View File

@ -297,7 +297,7 @@ class FlattenExceptionTest extends TestCase
// assertEquals() does not like NAN values.
$this->assertEquals($array[$i][0], 'float');
$this->assertNan($array[$i++][1]);
$this->assertNan($array[$i][1]);
}
public function testRecursionInArguments()

View File

@ -268,7 +268,7 @@ EOF;
foreach ($ids as $id) {
$c .= ' '.$this->doExport($id)." => true,\n";
}
$files['removed-ids.php'] = $c .= "];\n";
$files['removed-ids.php'] = $c."];\n";
}
if (!$this->inlineFactories) {

View File

@ -24,28 +24,28 @@ class AnalyzeServiceReferencesPassTest extends TestCase
{
$container = new ContainerBuilder();
$a = $container
$container
->register('a')
->addArgument($ref1 = new Reference('b'))
;
$b = $container
$container
->register('b')
->addMethodCall('setA', [$ref2 = new Reference('a')])
;
$c = $container
$container
->register('c')
->addArgument($ref3 = new Reference('a'))
->addArgument($ref4 = new Reference('b'))
;
$d = $container
$container
->register('d')
->setProperty('foo', $ref5 = new Reference('b'))
;
$e = $container
$container
->register('e')
->setConfigurator([$ref6 = new Reference('b'), 'methodName'])
;

View File

@ -51,7 +51,7 @@ class IntegrationTest extends TestCase
->setPublic(true)
;
$b = $container
$container
->register('b', '\stdClass')
->addArgument(new Reference('c'))
->setPublic(false)

View File

@ -363,7 +363,7 @@ class ResolveChildDefinitionsPassTest extends TestCase
->setBindings(['a' => '1', 'b' => '2'])
;
$child = $container->setDefinition('child', new ChildDefinition('parent'))
$container->setDefinition('child', new ChildDefinition('parent'))
->setBindings(['b' => 'B', 'c' => 'C'])
;

View File

@ -87,8 +87,8 @@ class ResolveClassPassTest extends TestCase
$this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException');
$this->expectExceptionMessage('Service definition "App\Foo\Child" has a parent but no class, and its name looks like a FQCN. Either the class is missing or you want to inherit it from the parent service. To resolve this ambiguity, please rename this service to a non-FQCN (e.g. using dots), or create the missing class.');
$container = new ContainerBuilder();
$parent = $container->register('App\Foo', null);
$child = $container->setDefinition('App\Foo\Child', new ChildDefinition('App\Foo'));
$container->register('App\Foo', null);
$container->setDefinition('App\Foo\Child', new ChildDefinition('App\Foo'));
(new ResolveClassPass())->process($container);
}

View File

@ -1272,7 +1272,7 @@ class ContainerBuilderTest extends TestCase
$this->expectExceptionMessage('The definition for "DateTime" has no class attribute, and appears to reference a class or interface in the global namespace.');
$container = new ContainerBuilder();
$definition = $container->register(\DateTime::class);
$container->register(\DateTime::class);
$container->compile();
}
@ -1302,7 +1302,7 @@ class ContainerBuilderTest extends TestCase
$this->expectExceptionMessage('The definition for "123_abc" has no class.');
$container = new ContainerBuilder();
$definition = $container->register('123_abc');
$container->register('123_abc');
$container->compile();
}
@ -1312,7 +1312,7 @@ class ContainerBuilderTest extends TestCase
$this->expectExceptionMessage('The definition for "\foo" has no class.');
$container = new ContainerBuilder();
$definition = $container->register('\\foo');
$container->register('\\foo');
$container->compile();
}

View File

@ -1091,7 +1091,7 @@ class PhpDumperTest extends TestCase
->setPublic(true)
->addArgument($baz);
$passConfig = $container->getCompiler()->getPassConfig();
$container->getCompiler()->getPassConfig();
$container->compile();
$dumper = new PhpDumper($container);
@ -1183,7 +1183,6 @@ class PhpDumperTest extends TestCase
$container->compile();
$dumper = new PhpDumper($container);
$dump = $dumper->dump();
$this->assertStringEqualsFile(self::$fixturesPath.'/php/services_adawson.php', $dumper->dump());
}

View File

@ -884,7 +884,6 @@ class XmlFileLoaderTest extends TestCase
$container->compile();
$dumper = new PhpDumper($container);
$dump = $dumper->dump();
$this->assertStringEqualsFile(self::$fixturesPath.'/php/services_tsantos.php', $dumper->dump());
}

View File

@ -19,7 +19,7 @@ class ChoiceFormFieldTest extends FormFieldTestCase
{
$node = $this->createNode('textarea', '');
try {
$field = new ChoiceFormField($node);
new ChoiceFormField($node);
$this->fail('->initialize() throws a \LogicException if the node is not an input or a select');
} catch (\LogicException $e) {
$this->assertTrue(true, '->initialize() throws a \LogicException if the node is not an input or a select');
@ -27,7 +27,7 @@ class ChoiceFormFieldTest extends FormFieldTestCase
$node = $this->createNode('input', '', ['type' => 'text']);
try {
$field = new ChoiceFormField($node);
new ChoiceFormField($node);
$this->fail('->initialize() throws a \LogicException if the node is an input with a type different from checkbox or radio');
} catch (\LogicException $e) {
$this->assertTrue(true, '->initialize() throws a \LogicException if the node is an input with a type different from checkbox or radio');

View File

@ -24,7 +24,7 @@ class FileFormFieldTest extends FormFieldTestCase
$node = $this->createNode('textarea', '');
try {
$field = new FileFormField($node);
new FileFormField($node);
$this->fail('->initialize() throws a \LogicException if the node is not an input field');
} catch (\LogicException $e) {
$this->assertTrue(true, '->initialize() throws a \LogicException if the node is not an input field');
@ -32,7 +32,7 @@ class FileFormFieldTest extends FormFieldTestCase
$node = $this->createNode('input', '', ['type' => 'text']);
try {
$field = new FileFormField($node);
new FileFormField($node);
$this->fail('->initialize() throws a \LogicException if the node is not a file input field');
} catch (\LogicException $e) {
$this->assertTrue(true, '->initialize() throws a \LogicException if the node is not a file input field');

View File

@ -24,7 +24,7 @@ class InputFormFieldTest extends FormFieldTestCase
$node = $this->createNode('textarea', '');
try {
$field = new InputFormField($node);
new InputFormField($node);
$this->fail('->initialize() throws a \LogicException if the node is not an input');
} catch (\LogicException $e) {
$this->assertTrue(true, '->initialize() throws a \LogicException if the node is not an input');
@ -32,7 +32,7 @@ class InputFormFieldTest extends FormFieldTestCase
$node = $this->createNode('input', '', ['type' => 'checkbox']);
try {
$field = new InputFormField($node);
new InputFormField($node);
$this->fail('->initialize() throws a \LogicException if the node is a checkbox');
} catch (\LogicException $e) {
$this->assertTrue(true, '->initialize() throws a \LogicException if the node is a checkbox');
@ -40,7 +40,7 @@ class InputFormFieldTest extends FormFieldTestCase
$node = $this->createNode('input', '', ['type' => 'file']);
try {
$field = new InputFormField($node);
new InputFormField($node);
$this->fail('->initialize() throws a \LogicException if the node is a file');
} catch (\LogicException $e) {
$this->assertTrue(true, '->initialize() throws a \LogicException if the node is a file');

View File

@ -24,7 +24,7 @@ class TextareaFormFieldTest extends FormFieldTestCase
$node = $this->createNode('input', '');
try {
$field = new TextareaFormField($node);
new TextareaFormField($node);
$this->fail('->initialize() throws a \LogicException if the node is not a textarea');
} catch (\LogicException $e) {
$this->assertTrue(true, '->initialize() throws a \LogicException if the node is not a textarea');

View File

@ -39,14 +39,14 @@ class FormTest extends TestCase
$nodes = $dom->getElementsByTagName('input');
try {
$form = new Form($nodes->item(0), 'http://example.com');
new Form($nodes->item(0), 'http://example.com');
$this->fail('__construct() throws a \\LogicException if the node has no form ancestor');
} catch (\LogicException $e) {
$this->assertTrue(true, '__construct() throws a \\LogicException if the node has no form ancestor');
}
try {
$form = new Form($nodes->item(1), 'http://example.com');
new Form($nodes->item(1), 'http://example.com');
$this->fail('__construct() throws a \\LogicException if the input type is not submit, button, or image');
} catch (\LogicException $e) {
$this->assertTrue(true, '__construct() throws a \\LogicException if the input type is not submit, button, or image');
@ -55,7 +55,7 @@ class FormTest extends TestCase
$nodes = $dom->getElementsByTagName('button');
try {
$form = new Form($nodes->item(0), 'http://example.com');
new Form($nodes->item(0), 'http://example.com');
$this->fail('__construct() throws a \\LogicException if the node has no form ancestor');
} catch (\LogicException $e) {
$this->assertTrue(true, '__construct() throws a \\LogicException if the node has no form ancestor');
@ -63,11 +63,19 @@ class FormTest extends TestCase
}
/**
* __construct() should throw \\LogicException if the form attribute is invalid.
* @dataProvider constructorThrowsExceptionIfNoRelatedFormProvider
*
* __construct() should throw a \LogicException if the form attribute is invalid.
*/
public function testConstructorThrowsExceptionIfNoRelatedForm()
public function testConstructorThrowsExceptionIfNoRelatedForm(\DOMElement $node)
{
$this->expectException('LogicException');
new Form($node, 'http://example.com');
}
public function constructorThrowsExceptionIfNoRelatedFormProvider()
{
$dom = new \DOMDocument();
$dom->loadHTML('
<html>
@ -81,8 +89,10 @@ class FormTest extends TestCase
$nodes = $dom->getElementsByTagName('input');
$form = new Form($nodes->item(0), 'http://example.com');
$form = new Form($nodes->item(1), 'http://example.com');
return [
[$nodes->item(0)],
[$nodes->item(1)],
];
}
public function testConstructorLoadsOnlyFieldsOfTheRightForm()

View File

@ -63,6 +63,14 @@ class ExpressionLanguageTest extends TestCase
$this->assertSame($savedParsedExpression, $parsedExpression);
}
public function testWrongCacheImplementation()
{
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage('Cache argument has to implement Psr\Cache\CacheItemPoolInterface.');
$cacheMock = $this->getMockBuilder('Psr\Cache\CacheItemSpoolInterface')->getMock();
new ExpressionLanguage($cacheMock);
}
public function testConstantFunction()
{
$expressionLanguage = new ExpressionLanguage();
@ -158,7 +166,7 @@ class ExpressionLanguageTest extends TestCase
$cacheMock = $this->getMockBuilder('Psr\Cache\CacheItemPoolInterface')->getMock();
$cacheItemMock = $this->getMockBuilder('Psr\Cache\CacheItemInterface')->getMock();
$expressionLanguage = new ExpressionLanguage($cacheMock);
$savedParsedExpressions = [];
$savedParsedExpression = null;
$cacheMock
->expects($this->exactly(2))

View File

@ -131,7 +131,8 @@ class FormDataCollector extends DataCollector implements FormDataCollectorInterf
$hash = spl_object_hash($form);
if (!isset($this->dataByForm[$hash])) {
$this->dataByForm[$hash] = [];
// field was created by form event
$this->collectConfiguration($form);
}
$this->dataByForm[$hash] = array_replace(

View File

@ -181,10 +181,10 @@ class DateTimeToLocalizedStringTransformerTest extends TestCase
public function testTransformWrapsIntlErrors()
{
$transformer = new DateTimeToLocalizedStringTransformer();
$this->markTestIncomplete('Checking for intl errors needs to be reimplemented');
$transformer = new DateTimeToLocalizedStringTransformer();
// HOW TO REPRODUCE?
//$this->expectException('Symfony\Component\Form\Extension\Core\DataTransformer\TransformationFailedException');

View File

@ -13,10 +13,20 @@ namespace Symfony\Component\Form\Tests\Extension\DataCollector;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Form\Extension\Core\CoreExtension;
use Symfony\Component\Form\Extension\Core\DataMapper\PropertyPathMapper;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\DataCollector\FormDataCollector;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormFactory;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormRegistry;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\ResolvedFormTypeFactory;
class FormDataCollectorTest extends TestCase
{
@ -69,9 +79,9 @@ class FormDataCollectorTest extends TestCase
{
$this->dataExtractor = $this->getMockBuilder('Symfony\Component\Form\Extension\DataCollector\FormDataExtractorInterface')->getMock();
$this->dataCollector = new FormDataCollector($this->dataExtractor);
$this->dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock();
$this->factory = $this->getMockBuilder('Symfony\Component\Form\FormFactoryInterface')->getMock();
$this->dataMapper = $this->getMockBuilder('Symfony\Component\Form\DataMapperInterface')->getMock();
$this->dispatcher = new EventDispatcher();
$this->factory = new FormFactory(new FormRegistry([new CoreExtension()], new ResolvedFormTypeFactory()));
$this->dataMapper = new PropertyPathMapper();
$this->form = $this->createForm('name');
$this->childForm = $this->createForm('child');
$this->view = new FormView();
@ -726,6 +736,56 @@ class FormDataCollectorTest extends TestCase
);
}
public function testCollectMissingDataFromChildFormAddedOnFormEvents()
{
$form = $this->factory->createNamedBuilder('root', FormType::class, ['items' => null])
->add('items', CollectionType::class, [
'entry_type' => TextType::class,
'allow_add' => true,
// data is locked and modelData (null) is different to the
// configured data, so modifications of the configured data
// won't be allowed at this point. It also means *_SET_DATA
// events won't dispatched either. Therefore, no child form
// is created during the mapping of data to the form.
'data' => ['foo'],
])
->getForm()
;
$this->dataExtractor->expects($extractConfiguration = $this->exactly(4))
->method('extractConfiguration')
->willReturn([])
;
$this->dataExtractor->expects($extractDefaultData = $this->exactly(4))
->method('extractDefaultData')
->willReturnCallback(static function (FormInterface $form) {
// this simulate the call in extractDefaultData() method
// where (if defaultDataSet is false) it fires *_SET_DATA
// events, adding the form related to the configured data
$form->getNormData();
return [];
})
;
$this->dataExtractor->expects($this->exactly(4))
->method('extractSubmittedData')
->willReturn([])
;
$this->dataCollector->collectConfiguration($form);
$this->assertSame(2, $extractConfiguration->getInvocationCount(), 'only "root" and "items" forms were collected, the "items" children do not exist yet.');
$this->dataCollector->collectDefaultData($form);
$this->assertSame(3, $extractConfiguration->getInvocationCount(), 'extracted missing configuration of the "items" children ["0" => foo].');
$this->assertSame(3, $extractDefaultData->getInvocationCount());
$this->assertSame(['foo'], $form->get('items')->getData());
$form->submit(['items' => ['foo', 'bar']]);
$this->dataCollector->collectSubmittedData($form);
$this->assertSame(4, $extractConfiguration->getInvocationCount(), 'extracted missing configuration of the "items" children ["1" => bar].');
$this->assertSame(4, $extractDefaultData->getInvocationCount(), 'extracted missing default data of the "items" children ["1" => bar].');
$this->assertSame(['foo', 'bar'], $form->get('items')->getData());
}
private function createForm($name)
{
$builder = new FormBuilder($name, null, $this->dispatcher, $this->factory);

View File

@ -219,6 +219,8 @@ final class CurlHttpClient implements HttpClientInterface, LoggerAwareInterface
if ('POST' === $method) {
// Use CURLOPT_POST to have browser-like POST-to-GET redirects for 301, 302 and 303
$curlopts[CURLOPT_POST] = true;
} elseif ('HEAD' === $method) {
$curlopts[CURLOPT_NOBODY] = true;
} else {
$curlopts[CURLOPT_CUSTOMREQUEST] = $method;
}

View File

@ -356,6 +356,7 @@ final class CurlResponse implements ResponseInterface
if (200 > $statusCode = curl_getinfo($ch, CURLINFO_RESPONSE_CODE)) {
$multi->handlesActivity[$id][] = new InformationalChunk($statusCode, $headers);
$location = null;
return \strlen($data);
}
@ -379,9 +380,7 @@ final class CurlResponse implements ResponseInterface
}
}
$location = null;
if ($statusCode < 300 || 400 <= $statusCode || curl_getinfo($ch, CURLINFO_REDIRECT_COUNT) === $options['max_redirects']) {
if ($statusCode < 300 || 400 <= $statusCode || null === $location || curl_getinfo($ch, CURLINFO_REDIRECT_COUNT) === $options['max_redirects']) {
// Headers and redirects completed, time to get the response's body
$multi->handlesActivity[$id][] = new FirstChunk();
@ -405,6 +404,8 @@ final class CurlResponse implements ResponseInterface
$logger->info(sprintf('Redirecting: "%s %s"', $info['http_code'], $info['redirect_url']));
}
$location = null;
return \strlen($data);
}
}

View File

@ -183,7 +183,7 @@ class MockResponse implements ResponseInterface
try {
$offset = 0;
$chunk[1]->getStatusCode();
$response->headers = $chunk[1]->getHeaders(false);
$chunk[1]->getHeaders(false);
self::readResponse($response, $chunk[0], $chunk[1], $offset);
$multi->handlesActivity[$id][] = new FirstChunk();
$buffer = $response->requestOptions['buffer'] ?? null;
@ -269,7 +269,7 @@ class MockResponse implements ResponseInterface
$info = $mock->getInfo() ?: [];
$response->info['http_code'] = ($info['http_code'] ?? 0) ?: $mock->getStatusCode() ?: 200;
$response->addResponseHeaders($info['response_headers'] ?? [], $response->info, $response->headers);
$dlSize = isset($response->headers['content-encoding']) ? 0 : (int) ($response->headers['content-length'][0] ?? 0);
$dlSize = isset($response->headers['content-encoding']) || 'HEAD' === $response->info['http_method'] || \in_array($response->info['http_code'], [204, 304], true) ? 0 : (int) ($response->headers['content-length'][0] ?? 0);
$response->info = [
'start_time' => $response->info['start_time'],

View File

@ -195,8 +195,16 @@ final class NativeResponse implements ResponseInterface
return;
}
$this->multi->openHandles[$this->id] = [$h, $this->buffer, $this->inflate, $this->content, $this->onProgress, &$this->remaining, &$this->info];
$this->multi->handlesActivity[$this->id] = [new FirstChunk()];
if ('HEAD' === $context['http']['method'] || \in_array($this->info['http_code'], [204, 304], true)) {
$this->multi->handlesActivity[$this->id][] = null;
$this->multi->handlesActivity[$this->id][] = null;
return;
}
$this->multi->openHandles[$this->id] = [$h, $this->buffer, $this->inflate, $this->content, $this->onProgress, &$this->remaining, &$this->info];
}
/**

View File

@ -152,7 +152,7 @@ class UploadedFileTest extends TestCase
UPLOAD_ERR_OK
);
$movedFile = $file->move(__DIR__.'/Fixtures/directory');
$file->move(__DIR__.'/Fixtures/directory');
}
public function failedUploadedFile()

View File

@ -59,7 +59,7 @@ class HeaderBagTest extends TestCase
{
$this->expectException('RuntimeException');
$bag = new HeaderBag(['foo' => 'Tue']);
$headerDate = $bag->getDate('foo');
$bag->getDate('foo');
}
public function testGetCacheControlHeader()

View File

@ -30,13 +30,13 @@ class RedirectResponseTest extends TestCase
{
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage('Cannot redirect to an empty URL.');
$response = new RedirectResponse('');
new RedirectResponse('');
}
public function testRedirectResponseConstructorWrongStatusCode()
{
$this->expectException('InvalidArgumentException');
$response = new RedirectResponse('foo.bar', 404);
new RedirectResponse('foo.bar', 404);
}
public function testGenerateLocationHeader()

View File

@ -40,7 +40,7 @@ class NativeFileSessionHandlerTest extends TestCase
*/
public function testConstructSavePath($savePath, $expectedSavePath, $path)
{
$handler = new NativeFileSessionHandler($savePath);
new NativeFileSessionHandler($savePath);
$this->assertEquals($expectedSavePath, ini_get('session.save_path'));
$this->assertDirectoryExists(realpath($path));
@ -61,13 +61,13 @@ class NativeFileSessionHandlerTest extends TestCase
public function testConstructException()
{
$this->expectException('InvalidArgumentException');
$handler = new NativeFileSessionHandler('something;invalid;with;too-many-args');
new NativeFileSessionHandler('something;invalid;with;too-many-args');
}
public function testConstructDefault()
{
$path = ini_get('session.save_path');
$storage = new NativeSessionStorage(['name' => 'TESTING'], new NativeFileSessionHandler());
new NativeSessionStorage(['name' => 'TESTING'], new NativeFileSessionHandler());
$this->assertEquals($path, ini_get('session.save_path'));
}

View File

@ -28,7 +28,7 @@ class NullSessionHandlerTest extends TestCase
{
public function testSaveHandlers()
{
$storage = $this->getStorage();
$this->getStorage();
$this->assertEquals('user', ini_get('session.save_handler'));
}

View File

@ -54,7 +54,7 @@ class PdoSessionHandlerTest extends TestCase
$pdo = $this->getMemorySqlitePdo();
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_SILENT);
$storage = new PdoSessionHandler($pdo);
new PdoSessionHandler($pdo);
}
public function testInexistentTable()

View File

@ -142,7 +142,7 @@ class NativeSessionStorageTest extends TestCase
{
$this->iniSet('session.cache_limiter', 'nocache');
$storage = new NativeSessionStorage();
new NativeSessionStorage();
$this->assertEquals('', ini_get('session.cache_limiter'));
}
@ -150,7 +150,7 @@ class NativeSessionStorageTest extends TestCase
{
$this->iniSet('session.cache_limiter', 'nocache');
$storage = new NativeSessionStorage(['cache_limiter' => 'public']);
new NativeSessionStorage(['cache_limiter' => 'public']);
$this->assertEquals('public', ini_get('session.cache_limiter'));
}

View File

@ -49,7 +49,6 @@ class RequestDataCollector extends DataCollector implements EventSubscriberInter
}
}
$content = null;
try {
$content = $request->getContent();
} catch (\LogicException $e) {
@ -59,7 +58,6 @@ class RequestDataCollector extends DataCollector implements EventSubscriberInter
$sessionMetadata = [];
$sessionAttributes = [];
$session = null;
$flashes = [];
if ($request->hasSession()) {
$session = $request->getSession();

View File

@ -130,7 +130,6 @@ class ResponseCacheStrategy implements ResponseCacheStrategyInterface
$response->headers->set('Cache-Control', implode(', ', array_keys($flags)));
$maxAge = null;
$sMaxage = null;
if (is_numeric($this->ageDirectives['max-age'])) {
$maxAge = $this->ageDirectives['max-age'] + $this->age;

View File

@ -256,7 +256,7 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase
public function testControllersAreMadePublic()
{
$container = new ContainerBuilder();
$resolver = $container->register('argument_resolver.service')->addArgument([]);
$container->register('argument_resolver.service')->addArgument([]);
$container->register('foo', ArgumentWithoutTypeController::class)
->setPublic(false)

View File

@ -52,7 +52,7 @@ class StoreTest extends TestCase
public function testUnlockFileThatDoesExist()
{
$cacheKey = $this->storeSimpleEntry();
$this->storeSimpleEntry();
$this->store->lock($this->request);
$this->assertTrue($this->store->unlock($this->request));
@ -92,7 +92,7 @@ class StoreTest extends TestCase
{
$cacheKey = $this->storeSimpleEntry();
$entries = $this->getStoreMetadata($cacheKey);
list($req, $res) = $entries[0];
list(, $res) = $entries[0];
$this->assertEquals('en9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08', $res['x-content-digest'][0]);
}
@ -208,7 +208,7 @@ class StoreTest extends TestCase
{
$req1 = Request::create('/test', 'get', [], [], [], ['HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar']);
$res1 = new Response('test 1', 200, ['Vary' => 'Foo Bar']);
$key = $this->store->write($req1, $res1);
$this->store->write($req1, $res1);
$this->assertEquals($this->getStorePath('en'.hash('sha256', 'test 1')), $this->store->lookup($req1)->getContent());
$req2 = Request::create('/test', 'get', [], [], [], ['HTTP_FOO' => 'Bling', 'HTTP_BAR' => 'Bam']);
@ -229,7 +229,7 @@ class StoreTest extends TestCase
$req = Request::create('/test', 'get', [], [], [], ['HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar']);
$this->assertTrue($this->store->lock($req));
$path = $this->store->lock($req);
$this->store->lock($req);
$this->assertTrue($this->store->isLocked($req));
$this->store->unlock($req);

View File

@ -132,9 +132,6 @@ class ExecutableFinderTest extends TestCase
$this->assertSamePath(PHP_BINARY, $result);
}
/**
* @requires PHP 5.4
*/
public function testFindBatchExecutableOnWindows()
{
if (ini_get('open_basedir')) {

View File

@ -19,7 +19,7 @@ class RouteTest extends TestCase
public function testInvalidRouteParameter()
{
$this->expectException('BadMethodCallException');
$route = new Route(['foo' => 'bar']);
new Route(['foo' => 'bar']);
}
public function testTryingToSetLocalesDirectly()

View File

@ -6,7 +6,7 @@ trait FooTrait
{
public function doBar()
{
$baz = self::class;
self::class;
if (true) {
}
}

View File

@ -211,7 +211,7 @@ class PhpGeneratorDumperTest extends TestCase
include $this->testTmpFilepath;
$projectUrlGenerator = new \NonExistingRoutesUrlGenerator(new RequestContext());
$url = $projectUrlGenerator->generate('NonExisting', []);
$projectUrlGenerator->generate('NonExisting', []);
}
public function testDumpForRouteWithDefaults()

View File

@ -247,7 +247,7 @@ class RouteCompilerTest extends TestCase
$this->expectException('LogicException');
$route = new Route('/{name}/{name}');
$compiled = $route->compile();
$route->compile();
}
public function testRouteCharsetMismatch()
@ -255,7 +255,7 @@ class RouteCompilerTest extends TestCase
$this->expectException('LogicException');
$route = new Route("/\xE9/{bar}", [], ['bar' => '.'], ['utf8' => true]);
$compiled = $route->compile();
$route->compile();
}
public function testRequirementCharsetMismatch()
@ -263,7 +263,7 @@ class RouteCompilerTest extends TestCase
$this->expectException('LogicException');
$route = new Route('/foo/{bar}', [], ['bar' => "\xE9"], ['utf8' => true]);
$compiled = $route->compile();
$route->compile();
}
public function testRouteWithFragmentAsPathParameter()
@ -271,7 +271,7 @@ class RouteCompilerTest extends TestCase
$this->expectException('InvalidArgumentException');
$route = new Route('/{_fragment}');
$compiled = $route->compile();
$route->compile();
}
/**

View File

@ -48,7 +48,7 @@ final class NativePasswordEncoder implements PasswordEncoderInterface, SelfSalti
throw new \InvalidArgumentException('$cost must be in the range of 4-31.');
}
$this->algo = $algo ?? (\defined('PASSWORD_ARGON2I') ? max(PASSWORD_DEFAULT, \defined('PASSWORD_ARGON2ID') ? PASSWORD_ARGON2ID : PASSWORD_ARGON2I) : PASSWORD_DEFAULT);
$this->algo = (string) ($algo ?? \defined('PASSWORD_ARGON2ID') ? PASSWORD_ARGON2ID : (\defined('PASSWORD_ARGON2I') ? PASSWORD_ARGON2I : PASSWORD_BCRYPT));
$this->options = [
'cost' => $cost,
'time_cost' => $opsLimit,
@ -62,20 +62,13 @@ final class NativePasswordEncoder implements PasswordEncoderInterface, SelfSalti
*/
public function encodePassword($raw, $salt): string
{
if (\strlen($raw) > self::MAX_PASSWORD_LENGTH) {
if (\strlen($raw) > self::MAX_PASSWORD_LENGTH || ((string) PASSWORD_BCRYPT === $this->algo && 72 < \strlen($raw))) {
throw new BadCredentialsException('Invalid password.');
}
// Ignore $salt, the auto-generated one is always the best
$encoded = password_hash($raw, $this->algo, $this->options);
if (72 < \strlen($raw) && 0 === strpos($encoded, '$2')) {
// BCrypt encodes only the first 72 chars
throw new BadCredentialsException('Invalid password.');
}
return $encoded;
return password_hash($raw, $this->algo, $this->options);
}
/**
@ -83,12 +76,24 @@ final class NativePasswordEncoder implements PasswordEncoderInterface, SelfSalti
*/
public function isPasswordValid($encoded, $raw, $salt): bool
{
if (72 < \strlen($raw) && 0 === strpos($encoded, '$2')) {
// BCrypt encodes only the first 72 chars
if (\strlen($raw) > self::MAX_PASSWORD_LENGTH) {
return false;
}
return \strlen($raw) <= self::MAX_PASSWORD_LENGTH && password_verify($raw, $encoded);
if (0 === strpos($encoded, '$2')) {
// BCrypt encodes only the first 72 chars
return 72 >= \strlen($raw) && password_verify($raw, $encoded);
}
if (\extension_loaded('sodium') && version_compare(\SODIUM_LIBRARY_VERSION, '1.0.14', '>=')) {
return sodium_crypto_pwhash_str_verify($encoded, $raw);
}
if (\extension_loaded('libsodium') && version_compare(phpversion('libsodium'), '1.0.14', '>=')) {
return \Sodium\crypto_pwhash_str_verify($encoded, $raw);
}
return password_verify($raw, $encoded);
}
/**

View File

@ -93,7 +93,7 @@ final class SodiumPasswordEncoder implements PasswordEncoderInterface, SelfSalti
return \Sodium\crypto_pwhash_str_verify($encoded, $raw);
}
throw new LogicException('Libsodium is not available. You should either install the sodium extension, upgrade to PHP 7.2+ or use a different encoder.');
return false;
}
/**

View File

@ -117,7 +117,7 @@ class EncoderFactoryTest extends TestCase
$user = new EncAwareUser('user', 'pass');
$user->encoderName = 'invalid_encoder_name';
$encoder = $factory->getEncoder($user);
$factory->getEncoder($user);
}
public function testGetEncoderForEncoderAwareWithClassName()

View File

@ -166,7 +166,7 @@ class GuardAuthenticationProviderTest extends TestCase
$token->setAuthenticated(false);
$provider = new GuardAuthenticationProvider([], $this->userProvider, $providerKey, $this->userChecker);
$actualToken = $provider->authenticate($token);
$provider->authenticate($token);
}
public function testSupportsChecksGuardAuthenticatorsTokenOrigin()

View File

@ -21,7 +21,7 @@ class LogoutListenerTest extends TestCase
{
public function testHandleUnmatchedPath()
{
list($listener, $tokenStorage, $httpUtils, $options) = $this->getListener();
list($listener, , $httpUtils, $options) = $this->getListener();
list($event, $request) = $this->getGetResponseEvent();
@ -131,7 +131,7 @@ class LogoutListenerTest extends TestCase
$this->expectException('RuntimeException');
$successHandler = $this->getSuccessHandler();
list($listener, $tokenStorage, $httpUtils, $options) = $this->getListener($successHandler);
list($listener, , $httpUtils, $options) = $this->getListener($successHandler);
list($event, $request) = $this->getGetResponseEvent();
@ -153,7 +153,7 @@ class LogoutListenerTest extends TestCase
$this->expectException('Symfony\Component\Security\Core\Exception\LogoutException');
$tokenManager = $this->getTokenManager();
list($listener, $tokenStorage, $httpUtils, $options) = $this->getListener(null, $tokenManager);
list($listener, , $httpUtils, $options) = $this->getListener(null, $tokenManager);
list($event, $request) = $this->getGetResponseEvent();

View File

@ -224,7 +224,7 @@ class RememberMeListenerTest extends TestCase
public function testSessionStrategy()
{
list($listener, $tokenStorage, $service, $manager, , $dispatcher, $sessionStrategy) = $this->getListener(false, true, true);
list($listener, $tokenStorage, $service, $manager, , , $sessionStrategy) = $this->getListener(false, true, true);
$tokenStorage
->expects($this->once())
@ -289,7 +289,7 @@ class RememberMeListenerTest extends TestCase
public function testSessionIsMigratedByDefault()
{
list($listener, $tokenStorage, $service, $manager, , $dispatcher, $sessionStrategy) = $this->getListener(false, true, false);
list($listener, $tokenStorage, $service, $manager) = $this->getListener(false, true, false);
$tokenStorage
->expects($this->once())

View File

@ -60,7 +60,7 @@ class RemoteUserAuthenticationListenerTest extends TestCase
$method = new \ReflectionMethod($listener, 'getPreAuthenticatedData');
$method->setAccessible(true);
$result = $method->invokeArgs($listener, [$request]);
$method->invokeArgs($listener, [$request]);
}
public function testGetPreAuthenticatedDataWithDifferentKeys()

View File

@ -98,7 +98,7 @@ class X509AuthenticationListenerTest extends TestCase
$method = new \ReflectionMethod($listener, 'getPreAuthenticatedData');
$method->setAccessible(true);
$result = $method->invokeArgs($listener, [$request]);
$method->invokeArgs($listener, [$request]);
}
public function testGetPreAuthenticatedDataWithDifferentKeys()

View File

@ -66,8 +66,6 @@ class ResponseListenerTest extends TestCase
public function testItSubscribesToTheOnKernelResponseEvent()
{
$listener = new ResponseListener();
$this->assertSame([KernelEvents::RESPONSE => 'onKernelResponse'], ResponseListener::getSubscribedEvents());
}

View File

@ -27,7 +27,6 @@ class FilesystemLoaderTest extends TestCase
public function testConstructor()
{
$pathPattern = self::$fixturesPath.'/templates/%name%.%engine%';
$path = self::$fixturesPath.'/templates';
$loader = new ProjectTemplateLoader2($pathPattern);
$this->assertEquals([$pathPattern], $loader->getTemplatePathPatterns(), '__construct() takes a path as its second argument');
$loader = new ProjectTemplateLoader2([$pathPattern]);

View File

@ -61,7 +61,7 @@ class FileValidator extends ConstraintValidator
$binaryFormat = null === $constraint->binaryFormat ? true : $constraint->binaryFormat;
}
list($sizeAsString, $limitAsString, $suffix) = $this->factorizeSizes(0, $limitInBytes, $binaryFormat);
list(, $limitAsString, $suffix) = $this->factorizeSizes(0, $limitInBytes, $binaryFormat);
$this->context->buildViolation($constraint->uploadIniSizeErrorMessage)
->setParameter('{{ limit }}', $limitAsString)
->setParameter('{{ suffix }}', $suffix)

View File

@ -456,7 +456,7 @@ abstract class FileValidatorTest extends ConstraintValidatorTestCase
$reflection = new \ReflectionClass(\get_class(new FileValidator()));
$method = $reflection->getMethod('factorizeSizes');
$method->setAccessible(true);
list($sizeAsString, $limit, $suffix) = $method->invokeArgs(new FileValidator(), [0, UploadedFile::getMaxFilesize(), false]);
list(, $limit, $suffix) = $method->invokeArgs(new FileValidator(), [0, UploadedFile::getMaxFilesize(), false]);
// it correctly parses the maxSize option and not only uses simple string comparison
// 1000M should be bigger than the ini value

View File

@ -32,6 +32,7 @@ class PropertyPathTest extends TestCase
['foo', 'bar', 'foo.bar', 'It append the subPath to the basePath'],
['foo', '[bar]', 'foo[bar]', 'It does not include the dot separator if subPath uses the array notation'],
['0', 'bar', '0.bar', 'Leading zeros are kept.'],
['0', 1, '0.1', 'Numeric subpaths do not cause PHP 7.4 errors.'],
];
}
}

View File

@ -36,12 +36,13 @@ class PropertyPath
*/
public static function append($basePath, $subPath)
{
if ('' !== (string) $subPath) {
$subPath = (string) $subPath;
if ('' !== $subPath) {
if ('[' === $subPath[0]) {
return $basePath.$subPath;
}
return '' !== (string) $basePath ? $basePath.'.'.$subPath : $subPath;
return '' !== $basePath ? $basePath.'.'.$subPath : $subPath;
}
return $basePath;

View File

@ -38,7 +38,7 @@ class DefinitionTest extends TestCase
{
$this->expectException('Symfony\Component\Workflow\Exception\LogicException');
$this->expectExceptionMessage('Place "d" cannot be the initial place as it does not exist.');
$definition = new Definition([], [], 'd');
new Definition([], [], 'd');
}
public function testAddTransition()

View File

@ -7,6 +7,13 @@ use Symfony\Component\Workflow\Transition;
class TransitionTest extends TestCase
{
public function testValidateName()
{
$this->expectException('Symfony\Component\Workflow\Exception\InvalidArgumentException');
$this->expectExceptionMessage('The transition "foo.bar" contains invalid characters.');
new Transition('foo.bar', 'a', 'b');
}
public function testConstructor()
{
$transition = new Transition('name', 'a', 'b');

View File

@ -314,7 +314,7 @@ class WorkflowTest extends TestCase
$this->assertFalse($marking->has('b'));
$this->assertFalse($marking->has('c'));
$marking = $workflow->apply($subject, 'a_to_bc');
$workflow->apply($subject, 'a_to_bc');
$marking = $workflow->apply($subject, 'b_to_c');
$this->assertFalse($marking->has('a'));
@ -406,7 +406,7 @@ class WorkflowTest extends TestCase
'workflow.workflow_name.announce.t2',
];
$marking = $workflow->apply($subject, 't1');
$workflow->apply($subject, 't1');
$this->assertSame($eventNameExpected, $eventDispatcher->dispatchedEvents);
}
@ -446,7 +446,7 @@ class WorkflowTest extends TestCase
'workflow.workflow_name.announce',
];
$marking = $workflow->apply($subject, 'a-b');
$workflow->apply($subject, 'a-b');
$this->assertSame($eventNameExpected, $eventDispatcher->dispatchedEvents);
}

View File

@ -108,14 +108,6 @@ class Parser
return $data;
}
/**
* @internal
*/
public function getLastLineNumberBeforeDeprecation(): int
{
return $this->getRealCurrentLineNb();
}
private function doParse(string $value, int $flags)
{
$this->currentLineNb = -1;

View File

@ -97,7 +97,7 @@ YAML;
$filename = $this->createFile('');
unlink($filename);
$ret = $tester->execute(['filename' => $filename], ['decorated' => false]);
$tester->execute(['filename' => $filename], ['decorated' => false]);
}
private function createFile($content): string

View File

@ -64,7 +64,7 @@ class ParserTest extends TestCase
foreach ($yamls as $yaml) {
try {
$content = $this->parser->parse($yaml);
$this->parser->parse($yaml);
$this->fail('YAML files must not contain tabs');
} catch (\Exception $e) {

View File

@ -82,6 +82,11 @@ switch ($vars['REQUEST_URI']) {
header('Location: ..', true, 302);
break;
case '/304':
header('Content-Length: 10', true, 304);
echo '12345';
return;
case '/307':
header('Location: http://localhost:8057/post', true, 307);
break;

View File

@ -72,6 +72,33 @@ abstract class HttpClientTestCase extends TestCase
$response->getContent();
}
public function testHeadRequest()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('HEAD', 'http://localhost:8057', [
'headers' => ['Foo' => 'baR'],
'user_data' => $data = new \stdClass(),
]);
$this->assertSame([], $response->getInfo('response_headers'));
$this->assertSame($data, $response->getInfo()['user_data']);
$this->assertSame(200, $response->getStatusCode());
$info = $response->getInfo();
$this->assertNull($info['error']);
$this->assertSame(0, $info['redirect_count']);
$this->assertSame('HTTP/1.1 200 OK', $info['response_headers'][0]);
$this->assertSame('Host: localhost:8057', $info['response_headers'][1]);
$this->assertSame('http://localhost:8057/', $info['url']);
$headers = $response->getHeaders();
$this->assertSame('localhost:8057', $headers['host'][0]);
$this->assertSame(['application/json'], $headers['content-type']);
$this->assertSame('', $response->getContent());
}
public function testNonBufferedGetRequest()
{
$client = $this->getHttpClient(__FUNCTION__);
@ -297,6 +324,17 @@ abstract class HttpClientTestCase extends TestCase
$response->getStatusCode();
}
public function test304()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/304', [
'headers' => ['If-Match' => '"abc"'],
]);
$this->assertSame(304, $response->getStatusCode());
$this->assertSame('', $response->getContent(false));
}
public function testRedirects()
{
$client = $this->getHttpClient(__FUNCTION__);