|
| 1 | +<?php |
| 2 | + |
| 3 | +// $ php examples/12-csv2tsv.php < examples/users.csv > examples/users.tsv |
| 4 | +// see also https://github.com/clue/reactphp-tsv |
| 5 | + |
| 6 | +use Clue\React\Csv\Decoder; |
| 7 | +use React\EventLoop\Factory; |
| 8 | +use React\Stream\ReadableResourceStream; |
| 9 | +use React\Stream\WritableResourceStream; |
| 10 | +use React\Stream\ThroughStream; |
| 11 | + |
| 12 | +require __DIR__ . '/../vendor/autoload.php'; |
| 13 | + |
| 14 | +$loop = Factory::create(); |
| 15 | + |
| 16 | +$exit = 0; |
| 17 | +$in = new ReadableResourceStream(STDIN, $loop); |
| 18 | +$out = new WritableResourceStream(STDOUT, $loop); |
| 19 | +$info = new WritableResourceStream(STDERR, $loop); |
| 20 | + |
| 21 | +$delimiter = isset($argv[1]) ? $argv[1] : ','; |
| 22 | + |
| 23 | +$decoder = new Decoder($in, $delimiter); |
| 24 | + |
| 25 | +$encoder = new ThroughStream(function ($data) { |
| 26 | + $data = \array_map(function ($value) { |
| 27 | + return \addcslashes($value, "\0..\37"); |
| 28 | + }, $data); |
| 29 | + |
| 30 | + return \implode("\t", $data) . "\n"; |
| 31 | +}); |
| 32 | + |
| 33 | +$decoder->pipe($encoder)->pipe($out); |
| 34 | + |
| 35 | +$decoder->on('error', function (Exception $e) use ($info, &$exit) { |
| 36 | + $info->write('ERROR: ' . $e->getMessage() . PHP_EOL); |
| 37 | + $exit = 1; |
| 38 | +}); |
| 39 | + |
| 40 | +// TSV files MUST include a header line, so complain if CSV input ends without a single line |
| 41 | +$decoder->on('end', $empty = function () use ($info, &$exit) { |
| 42 | + $info->write('ERROR: Empty CSV input' . PHP_EOL); |
| 43 | + $exit = 1; |
| 44 | +}); |
| 45 | +$decoder->once('data', function () use ($decoder, $empty) { |
| 46 | + $decoder->removeListener('end', $empty); |
| 47 | +}); |
| 48 | + |
| 49 | +$info->write('You can pipe/write a valid CSV stream to STDIN' . PHP_EOL); |
| 50 | +$info->write('Valid TSV (Tab-Separated Values) will be forwarded to STDOUT' . PHP_EOL); |
| 51 | +$info->write('Invalid CSV will raise an error on STDERR and exit with code 1' . PHP_EOL); |
| 52 | + |
| 53 | +$loop->run(); |
| 54 | + |
| 55 | +exit($exit); |
0 commit comments