FOSRestBundle icon indicating copy to clipboard operation
FOSRestBundle copied to clipboard

Unable to serialize php Generator (yield)

Open sarramegnag opened this issue 7 years ago • 1 comments

Greetings,

I just tried to return a Generator directly from my action, using @Rest\View annotation but FOSRestBundle generated an empty {}.

If I use iterator_to_array to transform the Generator object to an array, it properly works.

Is there any plan to support automatic serialization of generators ? Is this a JMS Serializer or FOSRestBundle issue ?

Regards,

Guillaume

<?php

namespace AppBundle\Controller;

use FOS\RestBundle\Controller\Annotations as Rest;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class ProspectController extends Controller
{
    /**
     * @ApiDoc(
     *     section="Prospects",
     *     description="Récupère la liste des prospects",
     *     statusCodes={
     *         200="Succès"
     *     }
     * )
     *
     * @Rest\Get("/prospects")
     * @Rest\View()
     *
     * @return array
     */
    public function getProspectsAction()
    {
        $prospects = $this->get('app.client.prospect')->findAll();
        return $this->get('app.mapper.client')->mapToProspectList($prospects);
    }
}
<?php

namespace AppBundle\Client\Proxiel\Mapper;

class Client
{
    public function mapToProspectList(array $prospectDTOs)
    {
        foreach ($prospectDTOs as $prospectDTO) {
            yield [
                'id' => $prospectDTO['Id'],
                'firstName' => $prospectDTO['FirstName'],
                'lastName' => $prospectDTO['LastName'],
                'email' => $prospectDTO['Email'],
                'phone' => $prospectDTO['TelephonePersonnel'],
                'birthDate' => $prospectDTO['BirthDate'],
                'state' => $prospectDTO['Disponibilite'],
            ];
        }
    }
}

sarramegnag avatar Jun 07 '17 08:06 sarramegnag

+1 Serialize every iterable return expression could be a nice feature

tmbdrogba avatar Dec 18 '17 16:12 tmbdrogba