‪TYPO3CMS  ‪main
/mnt/doxygen/typo3/sysext/core/Classes/IO/CsvStreamFilter.php

Implicitly handles stream filter when writing CSV data - example:

$resource = fopen('file.csv', 'w');
$modifier = CsvUtility::applyStreamFilter($resource);
fputcsv($resource, $modifier($fieldValues));
fclose($resource);
Parameters
resource$in
resource$out
int$consumed
bool$closing
<?php
declare(strict_types=1);
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
class CsvStreamFilter extends \php_user_filter
{
protected const ‪NAME = 'csv.typo3';
public function ‪filter($in, $out, &$consumed, $closing): int
{
while ($bucket = stream_bucket_make_writeable($in)) {
// removes sequence boundary indicator
$bucket->data = str_replace(
$this->params['sequence'],
'',
$bucket->data
);
if ($this->params['LF'] === false) {
// remove line-feed added by `fputcsv` per default
$bucket->data = preg_replace('#\r?\n$#', '', $bucket->data);
}
$consumed += $bucket->datalen;
stream_bucket_append($out, $bucket);
}
return PSFS_PASS_ON;
}
public static function ‪applyStreamFilter($stream, bool $LF = true): \Closure
{
// must contain a spacing character to enforce enclosure
$sequence = "\t\x1d\x1e\x1f";
stream_filter_append(
$stream,
self::NAME,
STREAM_FILTER_WRITE,
['sequence' => $sequence, 'LF' => $LF]
);
}
protected static function ‪registerStreamFilter()
{
if (in_array(self::NAME, stream_get_filters(), true)) {
return;
}
stream_filter_register(
self::NAME,
static::class
);
}
protected static function ‪buildStreamFilterModifier(string $sequence): \Closure
{
return static function ($element) use ($sequence) {
foreach ($element as &$value) {
if (is_numeric($value) || $value === '') {
continue;
}
$value = $sequence . $value;
}
unset($value); // de-reference
return $element;
};
}
}
‪TYPO3\CMS\Core\IO\CsvStreamFilter\NAME
‪const NAME
Definition: CsvStreamFilter.php:28
‪TYPO3\CMS\Core\IO\CsvStreamFilter\registerStreamFilter
‪static registerStreamFilter()
Definition: CsvStreamFilter.php:87
‪TYPO3\CMS\Core\IO\CsvStreamFilter\applyStreamFilter
‪static applyStreamFilter($stream, bool $LF=true)
Definition: CsvStreamFilter.php:70
‪TYPO3\CMS\Core\IO\CsvStreamFilter\buildStreamFilterModifier
‪static buildStreamFilterModifier(string $sequence)
Definition: CsvStreamFilter.php:98
‪TYPO3\CMS\Core\IO\CsvStreamFilter\filter
‪filter($in, $out, &$consumed, $closing)
Definition: CsvStreamFilter.php:47
‪TYPO3\CMS\Core\IO
Definition: CsvStreamFilter.php:18