core icon indicating copy to clipboard operation
core copied to clipboard

Allow overide of CsvEncoder::AS_COLLECTION_KEY in context

Open Stav88 opened this issue 2 months ago • 0 comments

API Platform version(s) affected: 3.4.1 (seems on main branch by analaysing code)

Description
denormalizationContext CsvEncoder::AS_COLLECTION_KEY is erased by API platforme when defined on a route operation.

How to reproduce

  • Entity
    #[ApiResource(
        operations: [
            new Patch(
                uriTemplate: '/admin/books{._format}',
                processor: MultipleBookPersistProcessor::class,
                formats: ['csv' => ['text/csv']],
                validate: false,
                denormalizationContext: [
                    CsvEncoder::AS_COLLECTION_KEY => true, // say to CsvEncoder to output a collection
                    'deserializer_type' => self::class . '[]', // say to symfony to use ArrayDenormalizer
                ]
            ),
        ]
    )]
    class Book {...}
    
  • Processor to support an array of entity
    class MultipleBookPersistProcessor implements ProcessorInterface
    {
        public function __construct(
            private BookPersistProcessor $bookPersistProcessor,
        ) {
        }
    
        public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = [])
        {
            foreach ($data as $book) {
                $this->bookPersistProcessor->process($book, $operation, $uriVariables, $context);
            }
        }
    }
    
  • Try to patch a CSV :
    • Multi line CSV (OK) :
      book,title,author,condition
      https://openlibrary.org/books/OL2055137M.json,Hyperion,"Dan Simmons",https://schema.org/NewCondition
      https://openlibrary.org/books/OL28276567M.json,Hyperion 2,"Dan Simmons",https://schema.org/NewCondition
      
    • One line CSV (fail) :
      book,title,author,condition
      https://openlibrary.org/books/OL2055137M.json,Hyperion,"Dan Simmons",https://schema.org/NewCondition
      

Possible Solution
In src/Serializer/SerializerContextBuilder.php , it would be better set $context[CsvEncoder::AS_COLLECTION_KEY] only if it has not been set to allow override :

$context[CsvEncoder::AS_COLLECTION_KEY] = $context[CsvEncoder::AS_COLLECTION_KEY] ?? false;

Additional Context
See comment on this old PR : https://github.com/api-platform/core/pull/3009/files#r342574912

Stav88 avatar Dec 09 '25 15:12 Stav88