Skip to content

Allow overide of CsvEncoder::AS_COLLECTION_KEY in context #7599

@Stav88

Description

@Stav88

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions