From 08f5d7c3645a3cc8f353391d54ee3318c912e609 Mon Sep 17 00:00:00 2001 From: Lukas Naumann Date: Fri, 13 Oct 2023 10:51:09 +0200 Subject: [PATCH] [Mime] Throw InvalidArgumentException on invalid form field type inside array --- .../Mime/Part/Multipart/FormDataPart.php | 11 +++++------ .../Tests/Part/Multipart/FormDataPartTest.php | 16 ++++++++++++++++ 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/src/Symfony/Component/Mime/Part/Multipart/FormDataPart.php b/src/Symfony/Component/Mime/Part/Multipart/FormDataPart.php index bd289f8ebe7fa..904c86d6b3cfd 100644 --- a/src/Symfony/Component/Mime/Part/Multipart/FormDataPart.php +++ b/src/Symfony/Component/Mime/Part/Multipart/FormDataPart.php @@ -32,13 +32,8 @@ public function __construct(array $fields = []) { parent::__construct(); - foreach ($fields as $name => $value) { - if (!\is_string($value) && !\is_array($value) && !$value instanceof TextPart) { - throw new InvalidArgumentException(sprintf('The value of the form field "%s" can only be a string, an array, or an instance of TextPart ("%s" given).', $name, get_debug_type($value))); - } + $this->fields = $fields; - $this->fields[$name] = $value; - } // HTTP does not support \r\n in header values $this->getHeaders()->setMaxLineLength(\PHP_INT_MAX); } @@ -75,6 +70,10 @@ private function prepareFields(array $fields): array return; } + if (!\is_string($item) && !$item instanceof TextPart) { + throw new InvalidArgumentException(sprintf('The value of the form field "%s" can only be a string, an array, or an instance of TextPart, "%s" given.', $fieldName, get_debug_type($item))); + } + $values[] = $this->preparePart($fieldName, $item); }; diff --git a/src/Symfony/Component/Mime/Tests/Part/Multipart/FormDataPartTest.php b/src/Symfony/Component/Mime/Tests/Part/Multipart/FormDataPartTest.php index 1cef8f42f391b..ddc2051bac91b 100644 --- a/src/Symfony/Component/Mime/Tests/Part/Multipart/FormDataPartTest.php +++ b/src/Symfony/Component/Mime/Tests/Part/Multipart/FormDataPartTest.php @@ -199,6 +199,22 @@ public function testExceptionOnFormFieldsWithIntegerKeysAndMultipleValues() $f->getParts(); } + public function testExceptionOnFormFieldsWithDisallowedTypesInsideArray() + { + $f = new FormDataPart([ + 'foo' => [ + 'bar' => 'baz', + 'qux' => [ + 'quux' => 1, + ], + ], + ]); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('The value of the form field "foo[qux][quux]" can only be a string, an array, or an instance of TextPart, "int" given.'); + $f->getParts(); + } + public function testToString() { $p = DataPart::fromPath($file = __DIR__.'/../../Fixtures/mimetypes/test.gif');