stream = $stream; fwrite( $this->stream, "\xEF\xBB\xBF" ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fwrite } /** * Write one row. * * @param array $row Cells. */ public function row( array $row ): void { $cells = array_map( [ $this, 'safe' ], $row ); fputcsv( $this->stream, $cells, $this->delimiter, '"', '' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fputcsv } /** * Flush the underlying stream. */ public function flush(): void { fflush( $this->stream ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fflush } /** * Complete the file. The stream stays open; its owner closes it. */ public function close(): void { $this->flush(); } /** * Neutralise formula injection. * * @param mixed $value Cell value. */ private function safe( mixed $value ): string { $value = (string) ( $value ?? '' ); // Line breaks inside a cell (addresses, notes) split rows in some // Excel versions. Flatten them; a CSV cell is one line. $value = trim( (string) preg_replace( '/\s*[\r\n]+\s*/', ' ', $value ) ); if ( '' !== $value && in_array( $value[0], [ '=', '+', '-', '@', "\t", "\r" ], true ) ) { // Numbers like "-12.50" are legitimate; only quote true formulas. if ( ! is_numeric( $value ) ) { $value = "'" . $value; } } return $value; } /** * Delimiters we allow from the UI. * * @param string $delimiter Requested delimiter. */ public static function sanitize_delimiter( string $delimiter ): string { return in_array( $delimiter, [ ',', ';', "\t", '|' ], true ) ? $delimiter : ','; } }