diff --git a/Csv.php b/Csv.php new file mode 100644 index 0000000..107a723 --- /dev/null +++ b/Csv.php @@ -0,0 +1,37 @@ + + * @link https://github.com/distantnative/kirby-csv-field + * @copyright Nico Hoffmann + * @license https://opensource.org/licenses/MIT + */ +class Csv extends Collection +{ + public function columns(): array + { + return array_keys($this->first()); + } + + public static function for(string $file, string $delimiter = ','): static + { + $lines = file($file); + $lines[0] = str_replace("\xEF\xBB\xBF", '', $lines[0]); + $csv = array_map(fn ($d) => str_getcsv($d, $delimiter), $lines); + + array_walk($csv, fn (&$a) => $a = array_combine($csv[0], $a)); + array_shift($csv); + + return new static($csv); + } + + public function rows(): array + { + return $this->toArray(); + } +} diff --git a/composer.json b/composer.json index a02e92f..289aec1 100644 --- a/composer.json +++ b/composer.json @@ -3,7 +3,7 @@ "description": "Kirby CMS Panel field to upload and display a single CSV file", "license": "MIT", "type": "kirby-plugin", - "version": "1.0.0-beta.2", + "version": "1.0.0-beta.3", "homepage": "https://distantnative.com/kirby-csv-field/", "authors": [ { diff --git a/docs/templates.md b/docs/templates.md index fe859c2..33a6c44 100644 --- a/docs/templates.md +++ b/docs/templates.md @@ -1,9 +1,38 @@ # Use in templates +To use your `csv` field in your templates, the plugin also ships with a `->toCsv()` field method. + +```php +$csv = $page->myCsvField()->toCsv(';'); +``` + +## `Csv` object + +The field method returns a `distantnative\CsvField\Csv` object. The `Csv` object is basically a [Kirby collection](https://getkirby.com/docs/reference/objects/toolkit/collection): + ```php -$table = $page->myCsvField()->toCsv(';'); +$csv->first(); +$csv->last(); +$csv->paginate(); +// ... +``` + +With a little added sugar for rows and columns: -var_dump($table); +```php +var_dump($csv->columns()); +``` + +``` +array (size=4) + 0 => string 'Username' (length=8) + 1 => string 'Identifier' (length=10) + 2 => string 'First name' (length=10) + 3 => string 'Last name' (length=9) +``` + +```php +var_dump($csv->rows()); ``` ``` @@ -40,3 +69,26 @@ array (size=5) 'Last name' => string 'Smith' (length=5) ``` + +## Example + +```php +myCsvField()->toCsv(';')): ?> +
= $column ?> | + + + + rows() as $row): ?> +
---|
= $cell ?> | + +