PHPackages                             nalabdou/algebra-csv - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. nalabdou/algebra-csv

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

nalabdou/algebra-csv
====================

CSV adapter for algebra-php — file paths, SplFileInfo, raw strings, resource handles. Auto-detect delimiter, encoding conversion, type coercion.

1.0.0(1mo ago)00MITPHPPHP &gt;=8.2CI passing

Since Mar 20Pushed 1mo agoCompare

[ Source](https://github.com/nalabdou/algebra-csv)[ Packagist](https://packagist.org/packages/nalabdou/algebra-csv)[ RSS](/packages/nalabdou-algebra-csv/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (4)Versions (3)Used By (0)

algebra-csv
===========

[](#algebra-csv)

[![PHP](https://camo.githubusercontent.com/187240af044d09d5b14a1d9d9ebdf3f7a993e4c7bc09bdb46b4ba661a891bf5b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e322532422d626c7565)](https://php.net)[![License: MIT](https://camo.githubusercontent.com/f8df3091bbe1149f398a5369b2c39e896766f9f6efba3477c63e9b4aa940ef14/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e)](LICENSE)

CSV adapter for [algebra-php](https://github.com/nalabdou/algebra-php).
Accepts file paths, `SplFileInfo`, raw CSV strings, and resource handles.
Auto-detects delimiter. Encoding conversion. Type coercion.

---

Installation
------------

[](#installation)

```
composer require nalabdou/algebra-csv
```

**Requirements:** PHP ≥ 8.2, `ext-mbstring`

---

Quick start
-----------

[](#quick-start)

Register adapters once at bootstrap, then use `Algebra::from()` anywhere.

### File path

[](#file-path)

```
use Nalabdou\Algebra\Algebra;
use Nalabdou\Algebra\Csv\CsvFileAdapter;
use Nalabdou\Algebra\Csv\ValueObject\CsvOptions;

Algebra::adapters()->register(CsvFileAdapter::from(new CsvOptions(coerceTypes: true)), priority: 100);

$result = Algebra::from('/data/orders.csv')
    ->where("item['status'] == 'paid'")
    ->groupBy('region')
    ->aggregate(['revenue' => 'sum(amount)', 'orders' => 'count(*)'])
    ->orderBy('revenue', 'desc')
    ->toArray();
```

### Raw CSV string

[](#raw-csv-string)

```
use Nalabdou\Algebra\Algebra;
use Nalabdou\Algebra\Csv\CsvStringAdapter;
use Nalabdou\Algebra\Csv\ValueObject\CsvOptions;
use Nalabdou\Algebra\Csv\ValueObject\CsvString;

Algebra::adapters()->register(CsvStringAdapter::from(new CsvOptions()), priority: 90);

$csv = CsvString::from(
    "id,status,amount\n1,paid,100\n2,pending,200\n3,paid,300\n",
    new CsvOptions(coerceTypes: true),
);

$result = Algebra::from($csv)
    ->where("item['status'] == 'paid'")
    ->toArray();
```

### Resource handle

[](#resource-handle)

```
use Nalabdou\Algebra\Algebra;
use Nalabdou\Algebra\Csv\CsvResourceAdapter;
use Nalabdou\Algebra\Csv\ValueObject\CsvOptions;

Algebra::adapters()->register(CsvResourceAdapter::from(new CsvOptions()), priority: 80);

$handle = fopen('/data/exports.csv', 'rb');

$result = Algebra::from($handle)
    ->tally('status')
    ->toArray();

fclose($handle); // caller owns the handle lifecycle
```

---

Bootstrap — register all adapters at once
-----------------------------------------

[](#bootstrap--register-all-adapters-at-once)

A single setup call at application entry point covers all three input types:

```
use Nalabdou\Algebra\Algebra;
use Nalabdou\Algebra\Csv\CsvFileAdapter;
use Nalabdou\Algebra\Csv\CsvStringAdapter;
use Nalabdou\Algebra\Csv\CsvResourceAdapter;
use Nalabdou\Algebra\Csv\ValueObject\CsvOptions;

Algebra::adapters()->register(CsvFileAdapter::from(new CsvOptions(coerceTypes: true)),  priority: 100);
Algebra::adapters()->register(CsvStringAdapter::from(new CsvOptions()),                  priority: 90);
Algebra::adapters()->register(CsvResourceAdapter::from(new CsvOptions()),                priority: 80);
```

After that, `Algebra::from()` accepts file paths, `SplFileInfo`, `CsvString`, and resource handles with no further configuration.

---

Named constructors (`::from()`)
-------------------------------

[](#named-constructors-from)

Every adapter exposes a `::from(CsvOptions)` static named constructor:

```
$adapter = CsvFileAdapter::from(new CsvOptions(delimiter: ';', coerceTypes: true));

// Also valid — same result
$adapter = new CsvFileAdapter(new CsvOptions(delimiter: ';', coerceTypes: true));
```

`CsvString` follows the same pattern:

```
$csv = CsvString::from("id,name\n1,Alice\n");

$csv = CsvString::from("id;name\n1;Alice\n", new CsvOptions(delimiter: ';'));
```

---

Supported inputs
----------------

[](#supported-inputs)

InputAdapterNotes`string` (file path)`CsvFileAdapter`Must exist and be readable`SplFileInfo` / `SplFileObject``CsvFileAdapter`Symfony's `File` works too`CsvString``CsvStringAdapter`Wraps raw CSV content`resource` (stream)`CsvResourceAdapter`Caller owns `fclose()`---

Configuration
-------------

[](#configuration)

All adapters accept a `CsvOptions` instance:

```
use Nalabdou\Algebra\Csv\ValueObject\CsvOptions;

$opts = new CsvOptions(
    delimiter:   null,         // null = auto-detect from [',', ';', "\t", '|']
    enclosure:   '"',          // field enclosure character
    escape:      '\\',         // escape character
    hasHeader:   true,         // first row = column names
    encoding:    null,         // null = UTF-8; set 'Windows-1252', 'ISO-8859-1', etc.
    skipEmpty:   false,        // skip rows where all cells are empty
    coerceTypes: false,        // convert '42' → 42, '1.5' → 1.5
);
```

### Fluent builder

[](#fluent-builder)

```
$opts = (new CsvOptions())
    ->withDelimiter(';')
    ->withEncoding('Windows-1252')
    ->withTypeCoercion()
    ->withSkipEmpty();

Algebra::adapters()->register(CsvFileAdapter::from($opts), priority: 100);
```

---

Auto-delimiter detection
------------------------

[](#auto-delimiter-detection)

When `delimiter` is `null` (the default), `DelimiterDetector` samples the first 4 KB and picks the most consistently-occurring character from `[',', ';', "\t", '|']`:

```
Algebra::from('orders.csv')   // comma — auto-detected
Algebra::from('exports.csv')  // semicolon — auto-detected
Algebra::from('data.tsv')     // tab — auto-detected
```

---

Encoding conversion
-------------------

[](#encoding-conversion)

Pass the source encoding — the parser converts everything to UTF-8 automatically:

```
Algebra::adapters()->register(
    CsvFileAdapter::from(new CsvOptions(encoding: 'Windows-1252')),
    priority: 100,
);

$result = Algebra::from('/data/french_export.csv')->toArray();
// All strings arrive as UTF-8
```

---

Type coercion
-------------

[](#type-coercion)

With `coerceTypes: true`, numeric strings are cast to `int` or `float`:

```
Algebra::adapters()->register(
    CsvFileAdapter::from(new CsvOptions(coerceTypes: true)),
    priority: 100,
);

// Without coercion:  $row['amount'] === '500'  (string)
// With coercion:     $row['amount'] === 500    (int)
```

---

Interfaces
----------

[](#interfaces)

The `src/Contract/` directory exposes stable interfaces for DI and extension:

InterfacePurpose`CsvAdapterInterface`All adapters; adds `::from()` and `getOptions()` on top of `AdapterInterface``CsvParserInterface`Low-level parser — swap in a custom implementation via constructor injection`DelimiterDetectorInterface`Detector — swap in a custom strategy```
use Nalabdou\Algebra\Csv\Contract\CsvAdapterInterface;

function registerAdapters(CsvAdapterInterface ...$adapters): void {
    foreach ($adapters as $priority => $adapter) {
        Algebra::adapters()->register($adapter, priority: $priority);
    }
}
```

---

With algebra-symfony
--------------------

[](#with-algebra-symfony)

```
use Nalabdou\AlgebraSymfony\Attribute\AsAlgebraAdapter;
use Nalabdou\Algebra\Csv\CsvFileAdapter;
use Nalabdou\Algebra\Csv\ValueObject\CsvOptions;

#[AsAlgebraAdapter(priority: 50)]
final class AppCsvAdapter extends CsvFileAdapter
{
    public function __construct()
    {
        parent::__construct(new CsvOptions(coerceTypes: true, skipEmpty: true));
    }
}
```

Registered automatically — no `services.yaml` needed. Use `Algebra::from()` directly throughout the application.

---

Requirements
------------

[](#requirements)

VersionPHP≥ 8.2ext-mbstring\*nalabdou/algebra-php^1.0---

Contributing
------------

[](#contributing)

See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup, coding standards, and how to add adapters or parser features.

License
-------

[](#license)

MIT — see [LICENSE](LICENSE).

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance90

Actively maintained with recent releases

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

50d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e872d64f192da649961f598268ebc6a7622495868821b602fee29233ec58c70b?d=identicon)[nalabdou](/maintainers/nalabdou)

---

Top Contributors

[![nalabdou](https://avatars.githubusercontent.com/u/46465503?v=4)](https://github.com/nalabdou "nalabdou (12 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/nalabdou-algebra-csv/health.svg)

```
[![Health](https://phpackages.com/badges/nalabdou-algebra-csv/health.svg)](https://phpackages.com/packages/nalabdou-algebra-csv)
```

###  Alternatives

[bigwhoop/sentence-breaker

Sentence boundary disambiguation (SBD) - or sentence breaking - library written in PHP.

42132.3k](/packages/bigwhoop-sentence-breaker)[j0k3r/graby-site-config

Graby site config files

23365.8k3](/packages/j0k3r-graby-site-config)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
