Core: Bug in ApiPlatform\Core\DataPersister\ChainDataPersister (or DataPersister doc is inconsistent)

Created on 22 Aug 2018  路  2Comments  路  Source: api-platform/core

As it's stated in https://api-platform.com/docs/core/data-persisters

Custom data persisters can be used to do so. A project can include as many data persisters as it needs. The first able to persist data for a given resource will be used.

I expect that "The first able to persist data for a given resource will be used." _and no other data persister will be used_. I could be wrong, but this is what I understood from doc.

# vendor/api-platform/core/src/DataPersister/ChainDataPersister.php
...
    public function persist($data)
    {
        foreach ($this->persisters as $persister) {
            if ($persister->supports($data)) {
                $data = $persister->persist($data) ?? $data;
            }
        }

        return $data;
    }
...

Indeed, if there will be more than one data persister that supports object passed in $data, then all of them will be used.
Moreover, at the moment when ChainDataPersister::persist($data) has been called there could be only one data persister that supports object passed in $data.
But this data persister should return an object, and returned object could be of different type and for that object another data persister may support it, and it will be called (in case it goes after).

For me this behaviour seems to be not correct as may lead to unexpected results.

Example:

  1. we have 2 data persisters - CustomDataPersister (to process a specific DTO) and a generic Doctrine DataPersister that ships with Api-platform.
  2. Imagine a case when CustomDataPersister after saving data will return a new Doctrine entity object (it's just possible, regardless the reason)

Then 2 scenarios:

  1. if Doctrine DataPersister goes 1st in foreach ($this->persisters as $persister) then it will not be used and only CustomDataPersister::persist will be executed
  2. or Doctrine DataPersister goes after CustomDataPersister, then both of them will be executed.

So, if it's not a bug, but a feature, then it should be properly documented, imho. ))

Most helpful comment

@dunglas perfect! yes, I confirm, now it works as expected.

All 2 comments

@Perf this faulty behavior been fixed in the version released of today. API Platform now behaves as documented. Can you try if it's ok on your project?

@dunglas perfect! yes, I confirm, now it works as expected.

Was this page helpful?
0 / 5 - 0 ratings