misatotremor/csv-bundle 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

misatotremor/csv-bundle

Composer 安装命令:

composer require misatotremor/csv-bundle

包简介

Symfony2 CSV Bundle

README 文档

README

This bundle provides an easy way to upload data to your db using csv files with just a few configuration parameters.

This is a fork of jdewits original code.

Status

This bundle is under development and may break.

Limitations

This bundle uses php and Doctrine and is not your best bet for importing gargantuan csv files. Use your databases native importing & exporting solutions to skin that cat.

Features

  • Import data by csv file
  • Export data to csv file
  • A few services for reading/writing csv files

Supports

  • Doctrine ORM

Installation

This bundle is listed on packagist.

Download the bundle

$ composer require misatotremor/csv-bundle

Enable the bundle as well as the dependent AvroCaseBundle:

<?php
// config/bundles.php

return [
    // ...
    Avro\CaseBundle\AvroCaseBundle::class => ['all' => true],
    Avro\CsvBundle\AvroCsvBundle::class => ['all' => true],
    // ...
];

Configuration

Add this required config

# config/packages/avro_csv.yaml
avro_csv:
    db_driver: 'orm' # supports orm
    batch_size: 15 # The batch size between flushing & clearing the doctrine object manager
    tmp_upload_dir: '%kernel.root_dir%/../web/uploads/tmp/' # The directory to upload the csv files to
    sample_count: 5 # The number of sample rows to show during mapping

Add routes to your config

# config/routes/avro_csv.yaml
avro_csv:
    resource: '@AvroCsvBundle/Resources/config/routing.yml'

Add the entities/documents you want to implement importing/exporting for

# config/packages/avro_csv.yaml
avro_csv:
    # 
    objects: # the entities/documents you want to be able to import/export data with 
        client:
            class: 'Avro\CrmBundle\Entity\Client' # The entity/document class
            redirect_route: 'avro_crm_client_list' # The route to redirect to after import
        invoice:
            class: 'Avro\CrmBundle\Entity\Invoice'
            redirect_route: 'avro_crm_invoice_list'

To exclude certain fields from being mapped, use the ImportExclude annotation like so.

namespace Avro\CrmBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Avro\CsvBundle\Annotation\ImportExclude;

/**
 * Avro\CrmBundle\Entity\Client
 *
 * @ORM\Entity
 */
class Client
{
    /**
     * @var string
     *
     * @ORM\Column(type="string", length=100, nullable=true)
     * @ImportExclude
     */
    protected $password;
    // ...
}

Since PHP 8 you can also use it as an attribute like this

namespace Avro\CrmBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Avro\CsvBundle\Annotation\ImportExclude;

#[ORM\Entity]
class Client
{
    #[ORM\Column(type: 'string', length: 100, nullable: true)]
    #[ImportExclude]
    protected string $password;
    // ...
}

Importing

Implement importing for as many entities/documents as you like. All you have to do is add them to the objects node as mentioned previously.

Then just include a link to specific import page like so:

<a href="{{ path('avro_csv_import_upload', {'alias': 'client'}) }}">Go to import page</a>

Replace "client" with whatever alias you called your entity/document in the config.

Views

The bundle comes with some basic twitter bootstrap views that you can override by extending the bundle.

Association mapping

An event is fired when importing an association field to allow implementing your own logic fitting

Just create a custom listener in your app that listens for the AssociationFieldEvent::class event.

A simple implementation getting an associated entity by name could look like:

namespace App\EventListener;

use Avro\CsvBundle\Event\AssociationFieldEvent;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Csv import listener
 */
class ImportListener implements EventSubscriberInterface
{
    private $em;

    /**
     * @param EntityManagerInterface   $em      The entity manager
     */
    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }
    
    public static function getSubscribedEvents()
    {
        return [
            AssociationFieldEvent::class => 'importAssociation',
        ];
    }

    /**
     * Set the objects createdBy field
     *
     * @param AssociationFieldEvent $event
     */
    public function importAssociation(AssociationFieldEvent $event)
    {
        $association = $event->getAssociationMapping();
        switch ($association['type']) {
            case ClassMetadataInfo::ONE_TO_ONE:
            case ClassMetadataInfo::MANY_TO_ONE:
                $relation = $this->em->getRepository($association['targetEntity'])->findOneBy(
                    [
                        'name' => $event->getRow()[$event->getIndex()],
                    ]
                );
                if ($relation) {
                    $event->getObject()->{'set'.ucfirst($association['fieldName'])}($relation);
                }
                break;
        }
    }
}

Customizing each row

Want to customize certain fields on each row? No problem.

An event is fired when a row is added that you can tap into to customize each row of data.

Just create a custom listener in your app that listens for the RowAddedEvent::class event.

For example...

namespace App\EventListener;

use Avro\CsvBundle\Event\RowAddedEvent;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\SecurityContextInterface;

/**
 * Csv import listener
 */
class ImportListener implements EventSubscriberInterface
{
    private $em;
    private $context;

    /**
     * @param EntityManagerInterface   $em      The entity manager
     * @param SecurityContextInterface $context The security context
     */
    public function __construct(EntityManagerInterface $em, SecurityContextInterface $context)
    {
        $this->em = $em;
        $this->context = $context;
    }
    
    public static function getSubscribedEvents()
    {
        return [
            RowAddedEvent::class => 'setCreatedBy',
        ];
    }

    /**
     * Set the objects createdBy field
     *
     * @param RowAddedEvent $event
     */
    public function setCreatedBy(RowAddedEvent $event)
    {
        $object = $event->getObject();

        $user = $this->context->getToken()->getUser();

        $object->setCreatedBy($user);
    }
}

Register your listener or use autowiring

Exporting

This bundle provides some simple exporting functionality.

Navigating to "/export/your-alias" will export all of your data to a csv and allow you to download it from the browser.

You can customize the export query builder and the exported data by listening to the corresponding events (See events in the Avro\CsvBundle\Event namespace).

If you want to customize data returned, just create your own controller action and grab the queryBuilder from the exporter and add your constraints before calling "getContent()".

Ex.

namespace App\Controller;

use Avro\CsvBundle\Event\ExportedEvent;
use Avro\CsvBundle\Event\ExportEvent;
use Avro\CsvBundle\Export\ExporterInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Response;

class ExportController
{
    private ExporterInterface $exporter;
    private EventDispatcherInterface $eventDispatcher;
    /**
     * @psalm-var list<array{class: class-string, redirect_route: string}>
     */
    private array $aliases;

    /**
     * ExportController constructor.
     */
    public function __construct(
        EventDispatcherInterface $eventDispatcher,
        ExporterInterface $exporter,
        array $aliases
    ) {
        $this->eventDispatcher = $eventDispatcher;
        $this->exporter = $exporter;
        $this->aliases = $aliases;
    }

    /**
     * Export a db table.
     *
     * @param string $alias The objects alias
     *
     * @return Response
     */
    public function exportAction(string $alias): Response
    {
        $exporter->init($this->aliases[$alias]['class']);

        $this->eventDispatcher->dispatch(new ExportEvent($this->exporter));

        // customize the query
        $qb = $exporter->getQueryBuilder();
        $qb->where('o.fieldName =? 1')->setParameter(1, false);

        $exportedEvent = new ExportedEvent($this->exporter->getContent());

        $this->eventDispatcher->dispatch($exportedEvent);

        $response = new Response($exportedEvent->getContent());
        $response->headers->set('Content-Type', 'application/csv');
        $response->headers->set('Content-Disposition', sprintf('attachment; filename="%s.csv"', $alias));

        return $response;
    }
}

Register your controller or use your already setup autowiring

To Do:

  • Finish mongodb support

Acknowledgements

Thanks to jwage's EasyCSV for some ground work.

Feedback and pull requests are much appreciated!

misatotremor/csv-bundle 适用场景与选型建议

misatotremor/csv-bundle 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 3.45k 次下载、GitHub Stars 达 1, 最近一次更新时间为 2021 年 11 月 23 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「csv」 「import」 「export」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 misatotremor/csv-bundle 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 misatotremor/csv-bundle 我们能提供哪些服务?
定制开发 / 二次开发

基于 misatotremor/csv-bundle 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 3.45k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 1
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 1
  • Forks: 12
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2021-11-23