Symfony Unseialize форма данных перед экспортом с экспортером Sonata

1

Я создал сайт в symfony. Этот веб-сайт содержит некоторые формы с выбором флажка и другими полями. Данные из флажка сериализуются на флеше. Все хорошо.

Теперь мне нужно экспортировать эти данные, и я использую библиотеку экспортеров данных из проекта Sonata. Но данные все еще сериализованы, и у меня есть такие вещи, как в моем файле csv:

a: 2: {i: 0; s: 6: "Volets"; i: 1; s: 22: "Panneau de remplise";

Как я могу сделать unerialize мои данные, чтобы иметь чистый файл csv?

Здесь мой код Мой контроллер

/**
 * @Security("has_role('ROLE_WEBFORM')")
 */
public function exportAction(Request $request)
{
    $filters = array();
    $this->handleFilterForm($request, $filters);
    if (!$filters['webform']) {
        throw $this->createNotFoundException();
    }

    $webForm = $this->getRepository('CoreBundle:WebForm')->find($filters['webform']);
    $source = new WebFormEntryIterator($webForm, $this->getEntityManager(), $this->get('ines_core.embedded_form.field_type_registry'), $filters);
    return WebFormEntryExporter::createResponse('export.csv', $source);
}

и мой класс WebFormEntryExporter

class WebFormEntryExporter
{
public static function createResponse($filename, SourceIteratorInterface $source)
{
    $writer      = new CsvWriter('php://output', ';', '"', "", true, true);
    $contentType = 'text/csv';
    $callback = function() use ($source, $writer) {
        $handler = \Exporter\Handler::create($source, $writer);
        $handler->export();
    };

    return new StreamedResponse($callback, 200, [
        'Content-Type'        => $contentType,
        'Content-Disposition' => sprintf('attachment; filename=%s', $filename)
    ]);
}
}

И мой WebFormEntryIterator

class WebFormEntryIterator implements SourceIteratorInterface
{
    protected $em;

    protected $registry;

    protected $repository;

    protected $query;

    protected $webForm;


    protected $iterator;

    public function __construct(WebForm $webForm, EntityManager $em, FieldTypeRegistry $registry, array $filters)
    {
        $this->webForm = $webForm;
        $this->em = $em;
        $this->registry = $registry;
        $this->initQuery($filters);
    }

    /**
     * {@inheritdoc}
     */
    public function current()
    {
        $current = $this->iterator->current();
        $entity = $current[0];

        $data = [];
        $data['ID'] = $entity->getId();
        $data['Formulaire'] = $this->webForm->getName();
        $data['Date de création'] = date_format($entity->getCreatedAt(), 'd/m/Y H:i:s');
        foreach ($this->webForm->getEmbeddedFieldConfigs() as $fieldConfig) {
            $header = $fieldConfig->getLabel();
            $meta = $entity->getContentMeta($fieldConfig->getName());

            $extension = $this->registry->get($meta->getFormat());
            if (method_exists($extension, 'setEntityManager')) {
                $extension->setEntityManager($this->em);
            }

            $value = $extension->formatMeta($meta);
            $data[$header] = $value;

            unset($extension);
        }

        $this->query->getEntityManager()->getUnitOfWork()->detach($current[0]);
        unset($entity);
        unset($webForm);

        return $data;
    }

    /**
     * {@inheritdoc}
     */
    public function next()
    {
        $this->iterator->next();
    }

    /**
     * {@inheritdoc}
     */
    public function key()
    {
        return $this->iterator->key();
    }

    /**
     * {@inheritdoc}
     */
    public function valid()
    {
        return $this->iterator->valid();
    }

    /**
     * {@inheritdoc}
     */
    public function rewind()
    {
        if ($this->iterator) {
            throw new InvalidMethodCallException('Cannot rewind a Doctrine\ORM\Query');
        }

        $this->iterator = $this->query->iterate();
        $this->iterator->rewind();
    }

    protected function initQuery(array $filters)
    {
        $repository = $this->em->getRepository('InesCoreBundle:Content');
        $qb = $repository->getWebFormEntryQueryBuilder();
        $repository->applyWfeFilters($qb, $filters);
        $this->query = $qb->getQuery();
    }
}

Извините за мой сломанный английский.

большое спасибо

  • 0
    Можете ли вы показать мне свой WebFormEntryIterator?
  • 0
    Добавлено в первый пост
Теги:
csv
serialization
sonata

1 ответ

0

спасибо chalasr.

Я должен сделать tratment в этом файле, в функции current(). Это то, что я сделал:

public function current()
{
    $current = $this->iterator->current();
    $entity = $current[0];

    $data = [];
    $data['ID'] = $entity->getId();
    $data['Formulaire'] = $this->webForm->getName();
    $data['Date de création'] = date_format($entity->getCreatedAt(), 'd/m/Y H:i:s');
    foreach ($this->webForm->getEmbeddedFieldConfigs() as $fieldConfig) {
        $header = $fieldConfig->getLabel();
        $meta = $entity->getContentMeta($fieldConfig->getName());

        $extension = $this->registry->get($meta->getFormat());
        if (method_exists($extension, 'setEntityManager')) {
            $extension->setEntityManager($this->em);
        }
        $value = $extension->formatMeta($meta);

        if($this->is_serialized($value)) {
            $value = unserialize($value);
            $data[$header] = implode(' | ', $value);
        } else {
            $data[$header] = $value;
        }
        unset($extension);
    }
    $this->query->getEntityManager()->getUnitOfWork()->detach($current[0]);
    unset($entity);
    unset($webForm);

    return $data;
}
public function is_serialized($data)
{ 
    if (trim($data) == "") { return false; } 
    if (preg_match("/^(i|s|a|o|d){1}:{1}(.*)/si",$data)) { return true; } 
    return false; 
}

Ещё вопросы

Сообщество Overcoder
Наверх
Меню