laravel-excel 0.3.0

Excel, CSV, ODS, HTML and PDF exports and imports with typed columns for Laravel Rust: a port of Laravel Excel (maatwebsite/excel).
Documentation
//! Laravel Excel's configuration: `config/excel.php`.

use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::Arc;

use laravel::config::Section;

use crate::excel::Type;
use crate::spreadsheet::Properties;
use crate::value::Value;

/// Laravel Excel's settings, with the defaults of `config/excel.php`.
///
/// Change them in your application's `with_config` callback:
///
/// ```ignore
/// use laravel_excel::ExcelConfig;
///
/// Application::configure()
///     .with_config(|config, _| {
///         config.section_mut::<ExcelConfig>().exports.csv.delimiter = ";".into();
///     })
/// ```
#[derive(Debug, Clone, Section)]
pub struct ExcelConfig {
    /// `excel.exports.chunk_size`: how many rows `FromQuery` reads at a time.
    #[env("EXCEL_CHUNK_SIZE", default = 1000)]
    pub chunk_size: u64,
    /// `excel.exports`.
    #[section(default = ExportsConfig::default())]
    pub exports: ExportsConfig,
    /// `excel.imports`.
    #[section(default = ImportsConfig::default())]
    pub imports: ImportsConfig,
    /// `excel.extension_detector`: the type for each file extension.
    #[section(default = default_extension_detector())]
    pub extension_detector: BTreeMap<String, Type>,
    /// `excel.value_binder.default`.
    #[section(default = ValueBinderKind::Default)]
    pub value_binder: ValueBinderKind,
    /// `excel.transactions`: whether an import runs in a database transaction.
    #[section(default = TransactionsConfig::default())]
    pub transactions: TransactionsConfig,
    /// `excel.temporary_files`.
    #[section(default = TemporaryFilesConfig::default())]
    pub temporary_files: TemporaryFilesConfig,
}

/// `excel.exports`.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ExportsConfig {
    /// `pre_calculate_formulas`. This port can't calculate formulas, so `true` is rejected when a
    /// file is written; see the README.
    pub pre_calculate_formulas: bool,
    /// `strict_null_comparison`: write `null` values as empty cells instead of skipping them.
    pub strict_null_comparison: bool,
    /// `csv`.
    pub csv: CsvExportSettings,
    /// `properties`.
    pub properties: Properties,
}

/// `excel.exports.csv`, and the settings `WithCustomCsvSettings` overrides.
#[derive(Debug, Clone, PartialEq)]
pub struct CsvExportSettings {
    /// `delimiter`.
    pub delimiter: String,
    /// `enclosure`. An empty enclosure only encloses values that need it.
    pub enclosure: String,
    /// `line_ending`, `PHP_EOL` by default.
    pub line_ending: String,
    /// `use_bom`.
    pub use_bom: bool,
    /// `include_separator_line`: a first `sep=,` line.
    pub include_separator_line: bool,
    /// `excel_compatibility`: a BOM, a separator line, `;` and `"`, and `\r\n` line endings.
    pub excel_compatibility: bool,
    /// `output_encoding`, such as `ISO-8859-15`; empty for UTF-8.
    pub output_encoding: String,
    /// `test_auto_detect`. It only affects PHP's line ending detection, which this port doesn't
    /// need, so it's kept for parity and has no effect.
    pub test_auto_detect: bool,
}

impl Default for CsvExportSettings {
    fn default() -> Self {
        Self {
            delimiter: ",".to_owned(),
            enclosure: "\"".to_owned(),
            line_ending: "\n".to_owned(),
            use_bom: false,
            include_separator_line: false,
            excel_compatibility: false,
            output_encoding: String::new(),
            test_auto_detect: true,
        }
    }
}

/// `excel.imports`.
#[derive(Debug, Clone)]
pub struct ImportsConfig {
    /// `read_only`. The readers this port uses never read styles, so this has no effect.
    pub read_only: bool,
    /// `ignore_empty`: skip rows whose cells are all empty, also without `SkipsEmptyRows`.
    pub ignore_empty: bool,
    /// `heading_row.formatter`: `slug`, `none`, or the name of a formatter registered with
    /// [`HeadingRowFormatter::extend`](crate::HeadingRowFormatter::extend).
    pub heading_row_formatter: String,
    /// `csv`.
    pub csv: CsvImportSettings,
    /// `properties`. Readers don't use them; kept for parity.
    pub properties: Properties,
    /// `cells.middleware`: run on every imported cell value, in order.
    pub cell_middleware: Vec<CellMiddleware>,
}

impl Default for ImportsConfig {
    fn default() -> Self {
        Self {
            read_only: true,
            ignore_empty: false,
            heading_row_formatter: "slug".to_owned(),
            csv: CsvImportSettings::default(),
            properties: Properties::default(),
            cell_middleware: Vec::new(),
        }
    }
}

/// A cell middleware: `Maatwebsite\Excel\Middleware\CellMiddleware`, run on each imported
/// cell's value.
#[derive(Clone)]
pub struct CellMiddleware(Arc<dyn Fn(Value) -> Value + Send + Sync>);

impl CellMiddleware {
    /// A middleware that maps each value.
    pub fn new(middleware: impl Fn(Value) -> Value + Send + Sync + 'static) -> Self {
        Self(Arc::new(middleware))
    }

    pub(crate) fn call(&self, value: Value) -> Value {
        (self.0)(value)
    }
}

impl std::fmt::Debug for CellMiddleware {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("CellMiddleware")
    }
}

/// `TrimCellValue`: trims whitespace, BOMs and zero width spaces from text.
pub fn trim_cell_value() -> CellMiddleware {
    CellMiddleware::new(|value| match value {
        Value::String(text) => Value::String(
            text.trim_matches(|c: char| c.is_whitespace() || c == '\u{FEFF}' || c == '\u{200B}')
                .to_owned(),
        ),
        other => other,
    })
}

/// `ConvertEmptyCellValuesToNull`: turns empty text into `null`.
pub fn convert_empty_cell_values_to_null() -> CellMiddleware {
    CellMiddleware::new(|value| match value {
        Value::String(text) if text.is_empty() => Value::Null,
        other => other,
    })
}

/// `excel.imports.csv`, and the settings `WithCustomCsvSettings` overrides.
#[derive(Debug, Clone, PartialEq)]
pub struct CsvImportSettings {
    /// `delimiter`; `None` detects it from the file.
    pub delimiter: Option<String>,
    /// `enclosure`.
    pub enclosure: String,
    /// `escape_character`.
    pub escape_character: String,
    /// `contiguous`. It only matters for PHP's read filters; kept for parity.
    pub contiguous: bool,
    /// `input_encoding`: `guess` (`Csv::GUESS_ENCODING`) or an encoding such as `UTF-8` or
    /// `ISO-8859-1`.
    pub input_encoding: String,
}

impl Default for CsvImportSettings {
    fn default() -> Self {
        Self {
            delimiter: None,
            enclosure: "\"".to_owned(),
            escape_character: "\\".to_owned(),
            contiguous: false,
            input_encoding: "guess".to_owned(),
        }
    }
}

/// `excel.value_binder.default`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ValueBinderKind {
    /// `Maatwebsite\Excel\DefaultValueBinder`.
    #[default]
    Default,
    /// PhpSpreadsheet's `StringValueBinder`.
    String,
    /// PhpSpreadsheet's `AdvancedValueBinder`.
    Advanced,
}

/// `excel.transactions`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TransactionsConfig {
    /// `handler`: `db` (the default) or `null` (`None`).
    pub handler: Option<String>,
    /// `db.connection`: the connection to run the transaction on, or the default connection.
    pub connection: Option<String>,
}

impl Default for TransactionsConfig {
    fn default() -> Self {
        Self {
            handler: Some("db".to_owned()),
            connection: None,
        }
    }
}

/// `excel.temporary_files`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TemporaryFilesConfig {
    /// `local_path`: relative to the application's `storage` directory unless absolute.
    pub local_path: PathBuf,
    /// `remote_disk`: a disk shared by all servers, for queued exports and imports.
    pub remote_disk: Option<String>,
    /// `remote_prefix`.
    pub remote_prefix: Option<String>,
    /// `force_resync_remote`: delete the local copy after each queued chunk.
    pub force_resync_remote: bool,
}

impl Default for TemporaryFilesConfig {
    fn default() -> Self {
        Self {
            local_path: PathBuf::from("framework/cache/laravel-excel"),
            remote_disk: None,
            remote_prefix: None,
            force_resync_remote: false,
        }
    }
}

fn default_extension_detector() -> BTreeMap<String, Type> {
    [
        ("xlsx", Type::Xlsx),
        ("xlsm", Type::Xlsx),
        ("xltx", Type::Xlsx),
        ("xltm", Type::Xlsx),
        ("xls", Type::Xls),
        ("xlt", Type::Xls),
        ("ods", Type::Ods),
        ("ots", Type::Ods),
        ("slk", Type::Slk),
        ("xml", Type::Xml),
        ("gnumeric", Type::Gnumeric),
        ("htm", Type::Html),
        ("html", Type::Html),
        ("csv", Type::Csv),
        ("tsv", Type::Tsv),
        ("pdf", Type::Dompdf),
    ]
    .into_iter()
    .map(|(extension, kind)| (extension.to_owned(), kind))
    .collect()
}

pub(crate) fn current() -> ExcelConfig {
    laravel::config().section::<ExcelConfig>().clone()
}