Skip to content

Add UploadedFileStream PSR-7 decorator for multipart file uploads - #21

Open
aviator-ua wants to merge 14 commits into
auto1-oss:masterfrom
aviator-ua:support-multiform-data
Open

aviator-ua wants to merge 14 commits into
auto1-oss:masterfrom
aviator-ua:support-multiform-data

Conversation

@aviator-ua

@aviator-ua aviator-ua commented May 23, 2026 •

Copy link
Copy Markdown

Summary

Adds end-to-end multipart/form-data support to the request serializer:

  • Multipart\UploadedFileStream — a PSR-7 StreamInterface decorator that carries a
    Symfony UploadedFile's filename and MIME type (exposed via getMetadata('filename')
    / getMetadata('mime-type')) alongside the underlying stream, plus a getUploadedFile()
    escape hatch for code needing Symfony-specific file operations.
  • Service\Serializer\Normalizer\StreamInterfaceDenormalizer — passes StreamInterface
    values through denormalization untouched, so binary DTO properties survive the request
    serializer instead of being mangled.

Context

Part of the rollout to support multipart/form-data across the auto1-oss API stack.

Changes

  • Multipart/UploadedFileStream.php — new PSR-7 decorator (see Summary).
  • Service/Serializer/Normalizer/StreamInterfaceDenormalizer.php — new pass-through denormalizer.
  • Resources/config/symfony_services.yml — registers the new denormalizer in
    auto1.api.request.serializer; migrates serializer service definitions to named arguments;
    sets parent: serializer.encoder.json on the JSON encoder; wires
    serializer.name_converter.metadata_aware into the object normalizer; passes the datetime
    format via defaultContext.
  • composer.json — adds psr/http-message and symfony/http-foundation dependencies.
  • Service/Logger/LoggerAwareTrait.php — adds license header; setLogger() now returns void.
  • Tests — Tests/Multipart/UploadedFileStreamTest.php,
    Tests/Serializer/Normalizer/StreamInterfaceDenormalizerTest.php.

Architectural notes

Location

Placed at top-level Multipart/ rather than Service/Multipart/. The class is a stateful
per-request wrapper, not a DI-registered service — grouping by domain (like Symfony's
HttpFoundation\File\UploadedFile) reads more accurately than appending to Service/.

No factory

Construction is a single line at one call site today (MultipartRequestDataExtractor::wrapFiles,
in the handler bundle). A factory would just relocate the PSR-17 StreamFactoryInterface
dependency one layer deeper without removing duplication. Worth revisiting if a second call
site appears or if construction grows real logic.

Open question

The handler-bundle's extractor recursively walks nested file arrays (<input name="foo[bar]">
shape). Generated DTOs currently declare each binary property as a flat top-level
StreamInterface, so the nested walk is defensive for now.

@aivus aivus left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocker: StreamInterfaceDenormalizer doesn't implement DenormalizerInterface::getSupportedTypes(), required as of symfony/serializer 7.0. The class fatals on load and the test suite aborts at test 20 of 33 — CI will fail on every PHP 8.x row. A one-method fix takes it to 33/33 green; details inline.

The remaining inline comments: wrong exception type for the type mismatch (turns bad input into a 500 instead of a 4xx), plus header, namespace and style fixes.

use Psr\Http\Message\StreamInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;

class StreamInterfaceDenormalizer implements DenormalizerInterface

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocker: this class is a fatal error on Symfony 7 — it takes the whole test suite down with it.

Symfony\Component\Serializer\Normalizer\DenormalizerInterface has declared getSupportedTypes(?string $format): array as a required method since 7.0, and composer.json allows symfony/serializer: ~7.0. Verified on this branch with v7.4.14:

PHP Fatal error:  Class ...\StreamInterfaceDenormalizer contains 1 abstract method
and must therefore be declared abstract or implement the remaining method
(Symfony\Component\Serializer\Normalizer\DenormalizerInterface::getSupportedTypes)
in Service/Serializer/Normalizer/StreamInterfaceDenormalizer.php on line 20

vendor/bin/phpunit aborts at test 20 of 33, so CI fails on every PHP 8.x row in the matrix. The pre-existing ArrayAccessNormalizer already implements this method — this class just missed the convention.

Adding the following brings the suite to 33/33 green (verified against psr/http-message at both 1.1 and 2.0):

public function getSupportedTypes(?string $format): array
{
    return ['object' => false];
}

'object' => false rather than StreamInterface::class => true: supportsDenormalization() matches subclasses via is_a(), so an interface-keyed entry would miss a DTO property typed as a concrete implementation, and false keeps supportsDenormalization() in the loop instead of caching a wrong answer.

Worth adding a test that asserts the interface is satisfied — the current tests all pass in isolation on the PHP 7.4 row (Symfony 5, where the method doesn't exist), which is exactly how this got through.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 81ad073 — implemented getSupportedTypes(?string $format): array { return ['object' => false]; } and added a test asserting it. Thanks for the detailed diagnosis and the 'object' => false rationale.

Comment on lines +29 to +35
throw new InvalidArgumentException(
sprintf(
'Expected an instance of "%s", got "%s".',
StreamInterface::class,
is_object($data) ? get_class($data) : gettype($data)
)
);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wrong exception type for a value-type mismatch.

The Symfony serializer only recognises Symfony\Component\Serializer\Exception\NotNormalizableValueException for this: it's what collect_denormalization_errors gathers and what the handler bundle can translate into a 4xx. An SPL InvalidArgumentException escapes the serializer uncaught and surfaces as a 500 on malformed input.

throw NotNormalizableValueException::createForUnexpectedDataType(
    sprintf('Expected an instance of "%s".', StreamInterface::class),
    $data,
    [StreamInterface::class],
    $context['deserialization_path'] ?? null
);

Also drop the now-unused use InvalidArgumentException; on line 16 (and update the test's expected exception).

Minor and related: returning null for null $data on line 25 defers the failure to a TypeError when the target property is non-nullable. A serializer-level error would point at the actual culprit.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 81ad073 — now throws NotNormalizableValueException::createForUnexpectedDataType(...) (passing $context['deserialization_path'] ?? null), dropped the SPL use, and updated the test's expected exception.

On the minor sub-point: I kept the null → null return. A nullable binary property should denormalize a missing file to null rather than error; happy to revisit if you'd prefer it fail loud at the serializer level.

<?php

/*
* This file is part of the auto1-oss/service-api-handler-bundle.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wrong bundle name in the license header — this is service-api-components-bundle, not service-api-handler-bundle. Copy-paste from the handler bundle.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4673f3c.

<?php

/*
* This file is part of the auto1-oss/service-api-handler-bundle.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same wrong bundle name in the license header here — should be auto1-oss/service-api-components-bundle.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4673f3c.


declare(strict_types=1);

namespace Tests\Auto1\ServiceAPIComponentsBundle\Service\Serializer\Normalizer;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Namespace and file path both diverge from the repo convention.

This namespace isn't reachable through the PSR-4 map (Auto1\ServiceAPIComponentsBundle\ -> repo root) — it only loads because PHPUnit scans ./Tests directly, so the class is invisible to the autoloader. Every other test in the repo uses the Auto1\ServiceAPIComponentsBundle\Tests\... prefix, and UploadedFileStreamTest in this same PR gets it right.

The path is off too: existing tests mirror the source layout under Tests/Service/ (e.g. Tests/Service/Serializer/Encoder/UrlEncoderTest.php), and the class under test lives in Service/Serializer/Normalizer/.

Suggest moving the file to Tests/Service/Serializer/Normalizer/StreamInterfaceDenormalizerTest.php and declaring:

namespace Auto1\ServiceAPIComponentsBundle\Tests\Service\Serializer\Normalizer;

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 10605ab — moved to Tests/Service/Serializer/Normalizer/StreamInterfaceDenormalizerTest.php with namespace Auto1\ServiceAPIComponentsBundle\Tests\Service\Serializer\Normalizer, matching the rest of the repo.

Comment thread Multipart/UploadedFileStream.php Outdated
Comment on lines +102 to +108
if ('mime-type' === $key) {
return $this->uploadedFile->getClientMimeType();
}

if ('filename' === $key) {
return $this->uploadedFile->getClientOriginalName();
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These two key names are the entire contract between this decorator and its consumers, but they only exist as string literals — the handler bundle's extractor will have to hard-code 'mime-type' / 'filename' and hope they match. Please promote them to public constants:

public const METADATA_MIME_TYPE = 'mime-type';
public const METADATA_FILENAME  = 'filename';

and use them here and in the null === $key merge below (lines 116-117). Also worth a docblock on this method noting that both values are client-supplied and unvalidated, so callers don't treat the MIME type as trustworthy for validation or authorization decisions — UploadedFile::getMimeType() is the content-guessed one.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in a2d2771 — added public METADATA_MIME_TYPE / METADATA_FILENAME, used them in the null === $key merge too, and added a docblock noting both values are client-supplied and unvalidated (so callers don't trust them for validation/authorization).

Comment on lines +1 to +2
<?php
/*

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Header formatting is inconsistent across the PR: this file has no blank line between <?php and the license block, while StreamInterfaceDenormalizer.php does. Existing files in the repo use * with no leading space on the continuation lines, whereas both new files use *. Purely cosmetic, but worth picking one form — the new files' * style is the more conventional one if you'd rather converge there.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in a2d2771 — added the blank line after <?php so it matches the other new file (both use the * continuation style).

Comment on lines +23 to +26
private static $targetMimeType = 'image/png';
private static $targetFilename = 'file.txt';
private static $targetMode = 'r';
private static $targetPayload = 'Test Payload';

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These are fixtures that never change — private const expresses that and drops the self::$ indirection. Mutable statics also leak across test methods if anything ever assigns to them.

private const TARGET_MIME_TYPE = 'image/png';
private const TARGET_FILENAME = 'file.txt';
private const TARGET_MODE = 'r';
private const TARGET_PAYLOAD = 'Test Payload';

Small thing, but $targetFilename = 'file.txt' paired with an image/png MIME type reads oddly — worth making the two agree.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in de7556e — converted the shared immutable fixtures to private const (TARGET_*), and changed the filename to image.png so it agrees with the image/png MIME type.

Comment on lines +48 to +49
->willReturn(self::$targetMimeType);
;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stray empty statement — line 48 already terminates the chain, so the ; on line 49 is a no-op. The other tests in this file put the terminating ; on its own line without one on the previous line; this is the only spot with both.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in de7556e — dropped the stray ;; the chain now terminates with a single ; on its own line, matching the other tests in the file.

Correct the license header in StreamInterfaceDenormalizer and its unit test
(they referenced service-api-handler-bundle instead of components-bundle).

Add an integration test that boots the real auto1.api.request.serializer from
symfony_services.yml and asserts both a single StreamInterface and a
StreamInterface[] collection pass through denormalization untouched, guarding
the normalizer wiring against regressions.
…ption

Implement DenormalizerInterface::getSupportedTypes(), required since
symfony/serializer 7.0 — without it the class is a fatal error on the ~7.0
rows and the whole suite aborts.

Throw NotNormalizableValueException instead of an SPL InvalidArgumentException
so the serializer recognises the value-type mismatch and the handler bundle can
translate it into a 4xx rather than letting it surface as a 500.
The previous namespace (Tests\Auto1\...) was unreachable through the PSR-4 map
(Auto1\ServiceAPIComponentsBundle\ -> repo root) and only loaded because PHPUnit
scans ./Tests directly. Move the file under Tests/Service/ to mirror the source
layout, matching every other test in the repo.
Promote the 'mime-type'/'filename' metadata keys to METADATA_MIME_TYPE /
METADATA_FILENAME so consumers (the handler bundle extractor) reference the
contract instead of hard-coding literals. Document that both values are
client-supplied and unvalidated. Also align the license header spacing with
the other new file.
Convert the shared immutable scalar fixtures from private static properties to
private const (immutable, cannot leak across test methods), make the filename
agree with the image/png MIME type, and drop a stray duplicate semicolon.
The 'multipart' format string was redefined independently in the client and
handler bundles, and 'url'/'void' were duplicated across encoders and the
endpoint provider config. Define FORMAT_MULTIPART, FORMAT_URL and FORMAT_VOID
on EndpointInterface alongside FORMAT_JSON, and re-point the existing local
definitions at them so each format string has a single source.
- Untype StreamInterfaceDenormalizer params and construct
  NotNormalizableValueException directly, so the class loads on every
  symfony/serializer version composer.json allows (4.2+)
- Implement NormalizerInterface in StreamInterfaceDenormalizer to fail fast
  when a stream reaches the normalize path instead of surfacing a confusing
  encoder error
- Return [StreamInterface::class => true] from getSupportedTypes() so
  symfony/serializer 6.3+ caches the support answer
- Extract generic MetadataStream decorator; UploadedFileStream becomes a thin
  adapter, letting in-memory streams carry filename/mime-type metadata
- Announce the setLogger(): void and Monolog-removal BC breaks and the
  multipart client-side requirement in CHANGELOG
- Align tests with conventions ($target locals, METADATA_* constants, AAA)
- Migrate phpunit.xml.dist from the 4.8 schema to 9.3 (--migrate-configuration)
- Require phpunit ^9.6, drop unused phpspec/prophecy-phpunit
- Add phpcs.xml.dist (PSR-12, strict types, forbidden debug functions) and
  phpstan.neon.dist (level 6)
- Require phpstan/phpstan ^2.1 and squizlabs/php_codesniffer ^4.0
- Add declare(strict_types=1) and constant visibility across the codebase
- Add missing return types, nullable param type in EndpointFactory, and
  array value types in docblocks
- LoggerAwareTrait: annotate $traitLogger as nullable to match the
  NullLogger fallback in getLogger()
- ParameterAwareUrlResolver: drop unreachable isset() error branch
- EndpointProviderCompilerPass: type tagged services honestly as mixed and
  move the endpoint contract check into a validateEndpoint() helper
With --prefer-lowest (Symfony 4.x / console 3.x) the vendor base classes
carry no PHPDoc for phpstan to inherit, surfacing missingType.return and
missingType.iterableValue errors. Add explicit void return types and
context/configs array value types to our own overrides.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants