Skip to content

Commit

Permalink
Accepts nested array in multipart option field value
Browse files Browse the repository at this point in the history
  • Loading branch information
Maz committed Oct 7, 2024
1 parent a70f5c9 commit a9a3328
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/MultipartStream.php
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,23 @@ private function addElement(AppendStream $stream, array $element): void
}
}

if (is_array($element['contents'])) {
$prepare = function ($contents, $key, $root = null) use ($stream, &$values, &$prepare) {

Check failure on line 95 in src/MultipartStream.php

View workflow job for this annotation

GitHub Actions / Psalm

UndefinedVariable

src/MultipartStream.php:95:80: UndefinedVariable: Cannot find referenced variable $values (see https://psalm.dev/024)

Check failure on line 95 in src/MultipartStream.php

View workflow job for this annotation

GitHub Actions / PHPStan

Anonymous function has an unused use $values.
$fieldName = $root ? sprintf('%s[%s]', $root, $key) : $key;

if (is_array($contents)) {
array_walk($contents, $prepare, $fieldName);
return;
}

$this->addElement($stream, ['name' => $fieldName, 'contents' => Utils::streamFor($contents)]);
};

array_walk($element['contents'], $prepare, $element['name']);

return;
}

$element['contents'] = Utils::streamFor($element['contents']);

if (empty($element['filename'])) {
Expand Down
29 changes: 29 additions & 0 deletions tests/MultipartStreamTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,35 @@ public function testSerializesNonStringFields(): void
self::assertSame($expected, (string) $b);
}

public function testExpandNestedArrayFields(): void
{
$b = new MultipartStream([
[
'name' => 'foo',
'contents' => [
['key' => 'bar'],
['key' => 'baz']
]
]
], 'boundary');

$expected = \implode('', [
"--boundary\r\n",
"Content-Disposition: form-data; name=\"foo[0][key]\"\r\n",
"Content-Length: 3\r\n",
"\r\n",
"bar\r\n",
"--boundary\r\n",
"Content-Disposition: form-data; name=\"foo[1][key]\"\r\n",
"Content-Length: 3\r\n",
"\r\n",
"baz\r\n",
"--boundary--\r\n",
]);

self::assertSame($expected, (string) $b);
}

public function testSerializesFiles(): void
{
$f1 = Psr7\FnStream::decorate(Psr7\Utils::streamFor('foo'), [
Expand Down

0 comments on commit a9a3328

Please sign in to comment.