Skip to content

Commit bb9bd33

Browse files
committed
Initial
0 parents  commit bb9bd33

File tree

12 files changed

+531
-0
lines changed

12 files changed

+531
-0
lines changed

.gitignore

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
.idea
2+
.vscode
3+
build
4+
composer.lock
5+
docs
6+
vendor
7+
coverage

.phpunit.xml

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<phpunit backupGlobals="false"
3+
backupStaticAttributes="false"
4+
colors="true"
5+
convertErrorsToExceptions="true"
6+
convertNoticesToExceptions="true"
7+
convertWarningsToExceptions="true"
8+
processIsolation="false"
9+
stopOnFailure="false">
10+
<testsuites>
11+
<testsuite name="Application Test Suite">
12+
<directory>./tests/</directory>
13+
</testsuite>
14+
</testsuites>
15+
<filter>
16+
<whitelist>
17+
<directory suffix=".php">src/</directory>
18+
</whitelist>
19+
</filter>
20+
</phpunit>

.styleci.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
preset: laravel

CHANGELOG.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# Changelog
2+
3+
## 0.1.0
4+
5+
### Added
6+
- Initial version
7+

CONTRIBUTING.md

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# Contributing
2+
3+
Contributions are **welcome** and will be fully **credited**.
4+
5+
Please read and understand the contribution guide before creating an issue or pull request.
6+
7+
## Etiquette
8+
9+
This project is open source, and as such, the maintainers give their free time to build and maintain the source code
10+
held within. They make the code freely available in the hope that it will be of use to other developers. It would be
11+
extremely unfair for them to suffer abuse or anger for their hard work.
12+
13+
Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the
14+
world that developers are civilized and selfless people.
15+
16+
It's the duty of the maintainer to ensure that all submissions to the project are of sufficient
17+
quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used.
18+
19+
## Viability
20+
21+
When requesting or submitting new features, first consider whether it might be useful to others. Open
22+
source projects are used by many developers, who may have entirely different needs to your own. Think about
23+
whether or not your feature is likely to be used by other users of the project.
24+
25+
## Procedure
26+
27+
Before filing an issue:
28+
29+
- Attempt to replicate the problem, to ensure that it wasn't a coincidental incident.
30+
- Check to make sure your feature suggestion isn't already present within the project.
31+
- Check the pull requests tab to ensure that the bug doesn't have a fix in progress.
32+
- Check the pull requests tab to ensure that the feature isn't already in progress.
33+
34+
Before submitting a pull request:
35+
36+
- Check the codebase to ensure that your feature doesn't already exist.
37+
- Check the pull requests to ensure that another person hasn't already submitted the feature or fix.
38+
39+
## Requirements
40+
41+
If the project maintainer has any additional requirements, you will find them listed here.
42+
43+
- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer).
44+
45+
- **Add tests!** - Your patch won't be accepted if it doesn't have tests.
46+
47+
- **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date.
48+
49+
- **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option.
50+
51+
- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests.
52+
53+
- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting.
54+
55+
**Happy coding**!

LICENSE.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
The MIT License (MIT)
2+
3+
Copyright (c) Dutch Coding Company BV <[email protected]>
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in
13+
all copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21+
THE SOFTWARE.

README.md

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
# CSV Collection
2+
3+
[![Latest Version on Packagist](https://img.shields.io/packagist/v/dutchcodingcompany/csv-collection.svg?style=flat-square)](https://packagist.org/packages/dutchcodingcompany/csv-collection)
4+
[![Total Downloads](https://img.shields.io/packagist/dt/dutchcodingcompany/csv-collection.svg?style=flat-square)](https://packagist.org/packages/dutchcodingcompany/csv-collection)
5+
6+
This package provides a simple but powerful way to read and write large CSV files using the power of Laravel's lazy
7+
collections.
8+
9+
## Installation
10+
11+
You can install the package via composer:
12+
13+
```bash
14+
composer require dutchcodingcompany/csv-collection
15+
```
16+
17+
## Usage
18+
19+
You may create a collection using the `new` keyword or the `make` method.
20+
21+
```php
22+
CsvCollection::make();
23+
```
24+
25+
This gives you access to all [Collection](https://laravel.com/docs/8.x/collections#available-methods)
26+
and [Lazy Collection](https://laravel.com/docs/8.x/collections#lazy-collection-methods) methods.
27+
28+
### Open
29+
30+
To open a file and load it's content into a new collection you may use the `open` method on the collection.
31+
32+
```php
33+
use DutchCodingCompany\CsvCollection\CsvCollection;
34+
35+
CsvCollection::make()
36+
->open('path/to/file.csv')
37+
->count();
38+
```
39+
40+
### Save
41+
42+
To save the collection items to a file you may use the `save` method on the collection.
43+
44+
```php
45+
use DutchCodingCompany\CsvCollection\CsvCollection;
46+
47+
CsvCollection::make(static function () {
48+
//
49+
})
50+
->save('path/to/file.csv');
51+
```
52+
53+
### Options
54+
55+
The following options are available to suit your needs:
56+
57+
- `header`, default: `true`
58+
- `delimiter`, default: `,`
59+
- `enclosure`, default: `"`
60+
- `escape`, default: `\\`
61+
62+
These options could be passed to the `open` and `save` methods, be set using the `options` method, or be set as the
63+
global default using the static `defaults` method.
64+
65+
#### Header
66+
67+
When using a header, lines will contain an associated array. Otherwise, lines will contain an indexed array.
68+
69+
```php
70+
// Without header
71+
[
72+
0 => 'John',
73+
1 => 'Doe',
74+
]
75+
76+
// With header
77+
[
78+
'first_name' => 'John',
79+
'last_name' => 'Doe',
80+
]
81+
```
82+
83+
_**Note**: When saving a collection to a file the keys of the first element in the collection will be used as the header._
84+
85+
## Testing
86+
87+
```bash
88+
composer test
89+
```
90+
91+
## Credits
92+
93+
- [Bjorn Voesten](https://github.com/bjornvoesten)
94+
- [Dutch Coding Company](https://github.com/dutchcodingcompany)
95+
- [All contributors](https://github.com/dutchcodingcompany/csv-collection/graphs/contributors)
96+
97+
## License
98+
99+
The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

composer.json

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
{
2+
"name": "dutchcodingcompany/csv-collection",
3+
"description": "Read and write large csv files using Laravel's Illuminate Collections",
4+
"keywords": [
5+
"dutch coding company",
6+
"dcc",
7+
"csv collection",
8+
"csv",
9+
"collection",
10+
"laravel",
11+
"illuminate"
12+
],
13+
"scripts": {
14+
"test": "./vendor/bin/phpunit ./tests"
15+
},
16+
"require": {
17+
"php": "^7.4",
18+
"illuminate/collections": "^6.0|^7.0|^8.0"
19+
},
20+
"require-dev": {
21+
"phpunit/phpunit": "*"
22+
},
23+
"autoload": {
24+
"psr-4": {
25+
"DutchCodingCompany\\CsvCollection\\": "src/",
26+
"Tests\\": "tests/"
27+
}
28+
},
29+
"config": {
30+
"sort-packages": true
31+
},
32+
"homepage": "https://dutchcodingcompany.com",
33+
"license": "MIT",
34+
"minimum-stability": "dev",
35+
"prefer-stable": true
36+
}

src/CsvCollection.php

Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
<?php
2+
3+
namespace DutchCodingCompany\CsvCollection;
4+
5+
use Illuminate\Support\LazyCollection;
6+
7+
class CsvCollection extends LazyCollection
8+
{
9+
/**
10+
* The collection's default options.
11+
*
12+
* @var array
13+
*/
14+
public static array $defaults = [
15+
'delimiter' => ',',
16+
'enclosure' => '"',
17+
'escape' => '\\',
18+
'header' => true,
19+
];
20+
21+
/**
22+
* The collection's options.
23+
*
24+
* @var array
25+
*/
26+
public array $options = [];
27+
28+
/**
29+
* Create a new csv collection instance.
30+
*
31+
* @param mixed $source
32+
* @return void
33+
*/
34+
public function __construct($source = null)
35+
{
36+
parent::__construct($source);
37+
38+
$this->options(static::$defaults);
39+
}
40+
41+
/**
42+
* Load the csv file items into a new collection.
43+
*
44+
* @param string $file
45+
* @param array $options
46+
* @return static
47+
*/
48+
public function open(string $file, array $options = []): self
49+
{
50+
$options = array_merge(
51+
$this->options, $options
52+
);
53+
54+
return static::make(static function () use ($file, $options) {
55+
$resource = fopen($file, 'r');
56+
57+
$read = static fn() => fgetcsv(
58+
$resource, 0,
59+
$options['delimiter'],
60+
$options['enclosure'],
61+
$options['escape'],
62+
);
63+
64+
$header = null;
65+
66+
// Loop over the rows and yield them into a generator.
67+
while (($line = $read()) !== false) {
68+
if (! ($options['header'])) {
69+
yield $line;
70+
continue;
71+
}
72+
73+
if (! $header) {
74+
$header = $line;
75+
continue;
76+
}
77+
78+
yield array_combine($header, $line);
79+
}
80+
81+
fclose($resource);
82+
});
83+
}
84+
85+
/**
86+
* Save the collection items to the csv file.
87+
*
88+
* @param string|null $file
89+
* @param array $options
90+
* @return $this
91+
*/
92+
public function save(string $file, array $options = []): self
93+
{
94+
$options = array_merge(
95+
$this->options, $options
96+
);
97+
98+
$resource = fopen($file, 'w');
99+
100+
$write = static fn(array $line) => fputcsv(
101+
$resource, $line,
102+
$options['delimiter'],
103+
$options['enclosure'],
104+
$options['escape'],
105+
);
106+
107+
if ($options['header']) {
108+
$write(array_keys($this->first()));
109+
}
110+
111+
$this->each($write);
112+
113+
fclose($resource);
114+
115+
return $this;
116+
}
117+
118+
/**
119+
* Set the collection's options.
120+
*
121+
* @param array $options
122+
* @return static
123+
*/
124+
public function options(array $options): self
125+
{
126+
$this->options = array_merge(
127+
$this->options, $options
128+
);
129+
130+
return $this;
131+
}
132+
133+
/**
134+
* Set the collection's default options.
135+
*
136+
* @param array $options
137+
* @return void
138+
*/
139+
public static function defaults(array $options): void
140+
{
141+
static::$defaults = array_merge(
142+
static::$defaults, $options
143+
);
144+
}
145+
}

0 commit comments

Comments
 (0)