dmt-software / import-reader
将文件/流的部分读取到一系列对象或数组中
v2.1.4
2024-06-07 07:00 UTC
Requires
- php: >=7.4
- ext-iconv: *
- ext-json: *
- ext-libxml: *
- ext-simplexml: *
- dmt-software/xml-parser: >=0.4
- pcrov/jsonreader: ^1.0
Requires (Dev)
- jms/serializer: ^3.18
- phpunit/phpunit: ^9.5
- psr/log: ^1.1
Suggests
- jms/serializer: to go through a collection of deserialized objects from an import file.
README
该读取器旨在遍历文件,以低内存使用返回其内容的块作为对象。
安装
composer require dmt-software/import-reader
用法
创建读取器
读取器可以手动创建,或者可以使用读取器构建器来创建(默认)读取器或预配置的读取器。
use DMT\Import\Reader\Decorators\DecoratorInterface; use DMT\Import\Reader\Decorators\Handler\GenericHandlerDecorator; use DMT\Import\Reader\Handlers\JsonReaderHandler; use DMT\Import\Reader\Reader; use DMT\Import\Reader\Handlers\Sanitizers\SanitizerInterface; use pcrov\JsonReader\JsonReader; $internalReader = new JsonReader(); $internalReader->open('/path/to/some.json'); /** @var DecoratorInterface[] $decorators */ /** @var SanitizerInterface[] $sanitizers */ $reader = new Reader( new JsonReaderHandler($internalReader, ...$sanitizers), new GenericHandlerDecorator(), ...$decorators );
有关处理程序内部读取器和清理器的更多信息,请参阅读取器处理程序文档。
添加装饰器
一旦创建了默认读取器,就可以添加额外的装饰器以应用于由读取方法返回的每个对象。
use DMT\Import\Reader\Decorators\ToObjectDecorator; use DMT\Import\Reader\Reader; /** @var Reader $reader */ $reader->addDecorator(new ToObjectDecorator(Customer::class, ['id' => 'id', 'name' => 'fullName', ])); foreach ($reader->read() as $customer) { // import customer; }
有关装饰器的更多信息,请参阅文档。
添加过滤器
除了使用装饰器控制输出外,还可以跳过或过滤读取器返回的对象流的一部分。
use DMT\Import\Reader\Reader; /** start on item 4 */ $skip = 3; /** skip all objects that has no id */ $filter = function (object $current) { return isset($current->id); } foreach ($reader->read($skip, $filter) as $item) { // import item }
有关过滤器回调的更多信息,请参阅过滤器部分。
错误处理
UnreadableException
当给定的文件无法读取时,将抛出此异常。这可能由几个原因引起
- 文件不可读
- 无法设置文件指针
- 在设置文件指针时到达文件末尾
- 文件指针设置为错误的返回类型
use DMT\Import\Reader\Exceptions\UnreadableException; try { $readerBuilder->build($file, $options = []); } catch (UnreadableException $exception) { // file can not be processed }
ReaderReadException
当无法从文件中读取单个块时,可能会发生这种情况。它将停止读取过程的执行。
use DMT\Import\Reader\Exceptions\ReaderReadException; try { foreach ($reader->read() as $n => $object) { // import object } } catch (ReaderReadException $exception) { // execution stopped, after $n rows }
DecoratorException
此异常会静默发生。它触发用户警告并继续读取过程。根据您的服务器配置,此警告可能被忽略或发送到STDOUT或STDERR。
其他异常或错误
任何其他类型的失败(最可能是)由配置错误或软件实现不正确引起的。