Hi Damian,
Thanks for working on this, and for taking in so much feedback already. The RFC
4180 default, locale independence and dropping the escape character are real
improvements over the current functions.
I'd like to suggest a direction for the API, mainly about how options are
passed. Every function currently takes $delimiter, $enclosure and $eolSequence,
so callers repeat the same dialect on every call, and every future option has
to be added to every signature. A small readonly value object for the format,
with the RFC's current defaults, would avoid that, and an enum would make the
quoting mode explicit:
namespace Csv;
enum Quoting { case Minimal; case All; case NonNumeric; }
final readonly class Format {
public function __construct(
public string $delimiter = ',',
public string $enclosure = '"',
public string $eolSequence = "\r\n",
public Quoting $quoting = Quoting::Minimal,
) {}
}
A format object also allows new format options without changing the encoder and
decoder APIs. For example, a configurable null representation to distinguish
null from empty strings during round trips, or stripping a UTF-8 BOM when
reading (as Excel commonly writes one).
The format could then be used by two small classes that do only the encoding
and decoding:
final class Encoder {
public function __construct(Format $format = new Format()) {}
public function encode(array $row): string {}
}
final class Decoder {
public function __construct(Format $format = new Format()) {}
public function decode(string $chunk): array {} // rows completed by
this chunk
public function finish(): array {} // end of input: last
row, validation
}
The decoder accepts input in arbitrary chunks, so it works with any source
(files, sockets, HTTP bodies, decompression) without needing a separate
function per source.
I'd deliberately keep stream and generator handling out of these classes. "Read
a stream until EOF and decode it" and "encode everything a generator yields to
a stream" are general patterns. A JSON Lines encoder and decoder would need
exactly the same, and so would other formats later. If each format builds its
own, we end up with a different streaming API per format. With minimal codecs,
a later RFC could define a common interface for streaming any encoder or
decoder, and CSV would get it for free.
Ignace's suggestion of an enum instead of the _lax suffix could fit here as a
validation mode on the decoder.
I'm happy to help review or test the implementation if that's useful.
Frode