mirror of
https://github.com/parsecsv/parsecsv-for-php.git
synced 2026-02-19 08:36:39 +00:00
Compare commits
120 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6c0e74c89e | ||
|
|
c47ba7934c | ||
|
|
653d5c0307 | ||
|
|
ff0e0c77fe | ||
|
|
f9b08cb0ac | ||
|
|
71e5f223a4 | ||
|
|
24e229ddfa | ||
|
|
259e9a6c31 | ||
|
|
27ab8a3e05 | ||
|
|
fe27ca6a7d | ||
|
|
33f0b6aa7c | ||
|
|
260de6126c | ||
|
|
1465973860 | ||
|
|
2c46b3fd14 | ||
|
|
bb3abe97de | ||
|
|
ac6b2665cd | ||
|
|
919528bb2f | ||
|
|
c4a90941e2 | ||
|
|
e967067a46 | ||
|
|
11dbbcb40e | ||
|
|
67163568ee | ||
|
|
6648dc99d5 | ||
|
|
2d6236cae0 | ||
|
|
f2b0aecd12 | ||
|
|
5d4643b201 | ||
| d5606f8b2a | |||
| 8cebcbd9bb | |||
| 518f5081fb | |||
|
|
a28fc6ab0a | ||
|
|
009820d190 | ||
|
|
facdf1c06c | ||
|
|
ee13c17157 | ||
|
|
99daaa7235 | ||
|
|
05826c2bbf | ||
|
|
731900effe | ||
|
|
913c3b1b94 | ||
|
|
96b2784d3c | ||
|
|
be01bc9ae4 | ||
|
|
b444afae2f | ||
|
|
bd6befe01e | ||
|
|
05ed8ec667 | ||
|
|
d21233c0f8 | ||
|
|
7a066f9d5e | ||
|
|
2425c1bbda | ||
|
|
eb502f9dad | ||
|
|
0af6e98670 | ||
|
|
b38d0de800 | ||
|
|
e15d144e27 | ||
|
|
4518e944c4 | ||
|
|
3ce6a82052 | ||
|
|
abae91a1a2 | ||
|
|
45f079b5dd | ||
|
|
fba67b84ff | ||
|
|
2a154869b4 | ||
|
|
d1186fcafa | ||
|
|
9c5eee23f6 | ||
|
|
6a54a6a509 | ||
|
|
8277b9682d | ||
|
|
0e54a2b9fa | ||
|
|
9c35237b1b | ||
|
|
1528a1f6ae | ||
|
|
aadb654edf | ||
|
|
8069409c73 | ||
|
|
947b1c0866 | ||
|
|
a3981edb84 | ||
|
|
b4e4c14b42 | ||
|
|
89429ebd60 | ||
|
|
548a9fe551 | ||
|
|
5336800ec6 | ||
|
|
6bd53940c5 | ||
|
|
a9297449b9 | ||
|
|
c12b6ba671 | ||
|
|
b792a6cc7b | ||
|
|
af442cdd0e | ||
|
|
95810ec2fa | ||
|
|
d79160f40a | ||
|
|
7ba2f9b296 | ||
|
|
d7ba892d38 | ||
|
|
38e9fff285 | ||
|
|
174d2e6070 | ||
|
|
d93036ca87 | ||
|
|
62fc367c14 | ||
|
|
044122efb9 | ||
|
|
18cbc3ab87 | ||
|
|
af75206e86 | ||
|
|
e45eb18213 | ||
|
|
5340ab9584 | ||
|
|
f3601dbfb5 | ||
|
|
67c8a0167c | ||
|
|
8b583daa08 | ||
|
|
b6dccf5fa6 | ||
|
|
5ca540daa7 | ||
|
|
f89ed5978d | ||
|
|
f053cdde80 | ||
|
|
62ae4e5fc3 | ||
|
|
a286556c16 | ||
|
|
7326262304 | ||
|
|
b746ea1de0 | ||
|
|
ef5e81f837 | ||
|
|
637f79c2e6 | ||
|
|
e3105d4003 | ||
|
|
5874b768b9 | ||
|
|
5d766adc17 | ||
|
|
67ed765eff | ||
|
|
a7be07cc02 | ||
|
|
b4cef37bb5 | ||
|
|
f97f03a088 | ||
|
|
2e94f4ad41 | ||
|
|
d03f8a2f09 | ||
|
|
14c9254ed4 | ||
|
|
78c288db8c | ||
|
|
531ac26e11 | ||
|
|
65566adcd3 | ||
|
|
2d428ffa93 | ||
|
|
bc9207de09 | ||
|
|
ace09c3c11 | ||
|
|
52ad56c66a | ||
|
|
ab9e8a0af9 | ||
|
|
8aa61914f7 | ||
|
|
3b74f7ce57 |
@@ -13,3 +13,9 @@ insert_final_newline = true
|
|||||||
|
|
||||||
[composer.json]
|
[composer.json]
|
||||||
indent_size = 4
|
indent_size = 4
|
||||||
|
|
||||||
|
[Makefile]
|
||||||
|
indent_style = tab
|
||||||
|
|
||||||
|
[*.yml,*.yaml]
|
||||||
|
indent_size = 2
|
||||||
|
|||||||
9
.gitattributes
vendored
Normal file
9
.gitattributes
vendored
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
/.editorconfig export-ignore
|
||||||
|
/.gitattributes export-ignore
|
||||||
|
/.gitignore export-ignore
|
||||||
|
/.travis.yml export-ignore
|
||||||
|
/ChangeLog.txt export-ignore
|
||||||
|
/examples export-ignore
|
||||||
|
/Makefile export-ignore
|
||||||
|
/ruleset.xml export-ignore
|
||||||
|
/tests export-ignore
|
||||||
82
.github/workflows/phpunit.yml
vendored
Normal file
82
.github/workflows/phpunit.yml
vendored
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
---
|
||||||
|
name: PHPUnit
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test_php_82_and_newer:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
php_version:
|
||||||
|
- "8.3"
|
||||||
|
- "8.2"
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
- uses: shivammathur/setup-php@v2
|
||||||
|
with:
|
||||||
|
php-version: ${{ matrix.php_version }}
|
||||||
|
env:
|
||||||
|
COMPOSER_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
- name: Get composer cache directory
|
||||||
|
id: composer-cache
|
||||||
|
run: echo "::set-output name=dir::$(composer config cache-files-dir)"
|
||||||
|
- name: Cache composer dependencies
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: ${{ steps.composer-cache.outputs.dir }}
|
||||||
|
key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }}
|
||||||
|
restore-keys: ${{ runner.os }}-composer-
|
||||||
|
- name: Update PHPUnit
|
||||||
|
run: composer require phpunit/phpunit --dev -W
|
||||||
|
- name: Install dependencies
|
||||||
|
run: composer update
|
||||||
|
- name: Validate dependencies
|
||||||
|
run: composer validate
|
||||||
|
- name: install Rector
|
||||||
|
run: composer require rector/rector --dev -W
|
||||||
|
- name: run Rector
|
||||||
|
run: cd tests && ../vendor/bin/phpunit --migrate-configuration
|
||||||
|
shell: bash
|
||||||
|
- name: run Rector
|
||||||
|
run: cd tests && ../vendor/bin/rector process .
|
||||||
|
shell: bash
|
||||||
|
- name: Run tests
|
||||||
|
run: vendor/bin/phpunit --configuration tests/phpunit.xml
|
||||||
|
test_php_81_and_lower:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
php_version:
|
||||||
|
- "8.1"
|
||||||
|
- "8.0"
|
||||||
|
- "7.4"
|
||||||
|
- "7.3"
|
||||||
|
- "7.2"
|
||||||
|
- "7.1"
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
- uses: shivammathur/setup-php@v2
|
||||||
|
with:
|
||||||
|
php-version: ${{ matrix.php_version }}
|
||||||
|
env:
|
||||||
|
COMPOSER_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
- name: Get composer cache directory
|
||||||
|
id: composer-cache
|
||||||
|
run: echo "::set-output name=dir::$(composer config cache-files-dir)"
|
||||||
|
- name: Cache composer dependencies
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: ${{ steps.composer-cache.outputs.dir }}
|
||||||
|
key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }}
|
||||||
|
restore-keys: ${{ runner.os }}-composer-
|
||||||
|
- name: Update PHPUnit
|
||||||
|
run: composer require phpunit/phpunit --dev -W
|
||||||
|
- name: Install dependencies
|
||||||
|
run: composer update
|
||||||
|
- name: Validate dependencies
|
||||||
|
run: composer validate
|
||||||
|
- name: Run tests
|
||||||
|
run: vendor/bin/phpunit --configuration tests/phpunit.xml
|
||||||
12
.gitignore
vendored
12
.gitignore
vendored
@@ -1,6 +1,14 @@
|
|||||||
*.bak
|
*.bak
|
||||||
|
.env
|
||||||
|
.envrc
|
||||||
/.idea
|
/.idea
|
||||||
|
/.vscode
|
||||||
|
/composer-setup.php
|
||||||
|
/composer.lock
|
||||||
|
/coverage_clover.xml
|
||||||
|
/docker-compose.yml
|
||||||
|
/examples/people.csv
|
||||||
/phive.xml
|
/phive.xml
|
||||||
|
/tests/.phpunit.result.cache
|
||||||
/tools
|
/tools
|
||||||
composer.lock
|
/vendor/
|
||||||
vendor/
|
|
||||||
|
|||||||
18
.travis.yml
18
.travis.yml
@@ -1,18 +0,0 @@
|
|||||||
language: php
|
|
||||||
|
|
||||||
php:
|
|
||||||
- 7.2
|
|
||||||
- 7.1
|
|
||||||
- 7.0
|
|
||||||
- 5.6
|
|
||||||
- 5.5
|
|
||||||
|
|
||||||
script:
|
|
||||||
- phpunit --version
|
|
||||||
- phpunit --configuration tests/phpunit.xml
|
|
||||||
|
|
||||||
notifications:
|
|
||||||
email:
|
|
||||||
- will.knauss@gmail.com
|
|
||||||
on_success: never
|
|
||||||
on_failure: always
|
|
||||||
150
ChangeLog.txt
150
ChangeLog.txt
@@ -1,16 +1,156 @@
|
|||||||
ParseCSV dev-master
|
ParseCSV 1.3.2
|
||||||
-----------------------------------
|
-----------------------------------
|
||||||
Date: unreleased
|
Date: 07-Nov-2021
|
||||||
|
|
||||||
- New function getTotalDataRowCount() - useful if
|
Bugfix:
|
||||||
$limit is set - see pull request #122.
|
- Allow _guess_delimiter to work with a single
|
||||||
|
row of data. As a consequence, `$csv->auto()`
|
||||||
|
now works for files with just one row of data.
|
||||||
|
See issue #206.
|
||||||
|
|
||||||
- Dropped support for PHP 5.4
|
-----------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
ParseCSV 1.3.1
|
||||||
|
-----------------------------------
|
||||||
|
Date: 20-Jun-2021
|
||||||
|
|
||||||
|
Bugfix:
|
||||||
|
- `parseFile()` will now set `$csv->data`.
|
||||||
|
Until now, the parsed data was only returned.
|
||||||
|
This adds consistency with `$csv->parse()`
|
||||||
|
for the following operations on the object.
|
||||||
|
|
||||||
|
-----------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
ParseCSV 1.3.0
|
||||||
|
-----------------------------------
|
||||||
|
Date: 14-Apr-2021
|
||||||
|
|
||||||
|
Breaking changes:
|
||||||
|
- Passing file paths to parse() or new Csv() is now deprecated
|
||||||
|
and will be removed in v2.0.0. Use ->parseFile() instead.
|
||||||
|
|
||||||
|
WARNING: It will call trigger_error() for now.
|
||||||
|
This may still break your application, depending on your
|
||||||
|
php.ini config. You can add E_USER_DEPRECATED to the
|
||||||
|
error_reporting mask to avoid breaking your application:
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_USER_DEPRECATED
|
||||||
|
|
||||||
|
This change is to avoid security issues: see issue #198.
|
||||||
|
|
||||||
|
Non-breaking deprecations:
|
||||||
|
- The function load_data() is deprecated.
|
||||||
|
Call loadFile() or loadDataString() instead.
|
||||||
|
- Supplying CSV data (file content) to auto() is deprecated.
|
||||||
|
Please use autoDetectionForDataString().
|
||||||
|
|
||||||
|
The motivation is to make subtle gotchas less likely: when the
|
||||||
|
file cannot be found or read by PHP (permissions), its file path
|
||||||
|
would be treated like CSV data.
|
||||||
|
- Currently, there is code to parse .php: <?...?> tags are removed
|
||||||
|
before the remaining file content is treated like a .csv file.
|
||||||
|
This rarely-used functionality will be removed in v2.0.0.
|
||||||
|
You are only affected if you use ParseCsv to parse .php files.
|
||||||
|
|
||||||
|
New features: none
|
||||||
|
Bug fixes: none
|
||||||
|
-----------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
ParseCSV 1.2.1
|
||||||
|
-----------------------------------
|
||||||
|
Date: 25-Apr-2020
|
||||||
|
|
||||||
|
Breaking changes: none
|
||||||
|
New features: none
|
||||||
|
Bug fixes: none
|
||||||
|
|
||||||
|
Code quality:
|
||||||
|
- Switched from PHPUnit 4 to 6 to get rid of
|
||||||
|
wrappers. This will reduce friction for PhpStorm users,
|
||||||
|
because it gets rid of the "Multiple definitions" error
|
||||||
|
See issue #188. Thanks to @SharkMachine for the hint.
|
||||||
|
-----------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
ParseCSV 1.2.0
|
||||||
|
-----------------------------------
|
||||||
|
Date: 07-Jan-2020
|
||||||
|
|
||||||
|
Breaking changes: none
|
||||||
|
|
||||||
|
New features:
|
||||||
|
- Compatible with PHP 7.4. Thanks to @andreybolonin
|
||||||
|
@morrislaptop @martijnengler and @fjf2002.
|
||||||
|
- unparse() now also understands $use_mb_convert_encoding.
|
||||||
|
- Verbal condition operators are now allowed to contain
|
||||||
|
upper case letters, for example:
|
||||||
|
$csv->conditions = 'rating IS GREATER THAN 4';
|
||||||
|
|
||||||
|
Bug fixes:
|
||||||
|
- All filter condition operators containing "is" or "equals"
|
||||||
|
were broken.
|
||||||
|
|
||||||
|
Code quality:
|
||||||
|
- Improved test coverage.
|
||||||
|
-----------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
ParseCSV 1.1.1
|
||||||
|
-----------------------------------
|
||||||
|
Date: 2-Feb-2019
|
||||||
|
|
||||||
|
Breaking changes: none
|
||||||
|
|
||||||
|
New features: none
|
||||||
|
|
||||||
|
Bug fixes:
|
||||||
|
- Function load_data: check length of input, prevents E_NOTICE
|
||||||
|
if too long.
|
||||||
|
- Fixed bugs in unparse().
|
||||||
|
|
||||||
|
Code quality:
|
||||||
|
- Improved test coverage.
|
||||||
|
-----------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
ParseCSV 1.1.0
|
||||||
|
-----------------------------------
|
||||||
|
Date: 9-Aug-2018
|
||||||
|
|
||||||
|
Breaking changes:
|
||||||
|
- Ignore entirely empty lines at the end of files
|
||||||
|
See https://github.com/parsecsv/parsecsv-for-php/pull/142
|
||||||
|
- Dropped support for PHP 5.4. Now, you need at leas PHP 5.5.
|
||||||
|
- Fixed parse()'s return value: return true only if $data is useful.
|
||||||
|
|
||||||
|
New features:
|
||||||
- Added support for Laravel-style collections via the
|
- Added support for Laravel-style collections via the
|
||||||
new getCollection() function - see
|
new getCollection() function - see
|
||||||
https://github.com/parsecsv/parsecsv-for-php/pull/134
|
https://github.com/parsecsv/parsecsv-for-php/pull/134
|
||||||
|
- New function getTotalDataRowCount() - useful if
|
||||||
|
$limit is set - see pull request #122.
|
||||||
|
- Added requires to keep Composer-free environments working.
|
||||||
|
|
||||||
|
Bug fixes:
|
||||||
|
- Better support for streams.
|
||||||
|
See https://github.com/parsecsv/parsecsv-for-php/pull/147
|
||||||
|
- Fixed output() with custom header.
|
||||||
|
See https://github.com/parsecsv/parsecsv-for-php/issues/132
|
||||||
|
- Fixed bug on _validate_fields_for_unparse() if titles property
|
||||||
|
is used instead of fields parameter for changing the titles for
|
||||||
|
unparsing.
|
||||||
|
- Fixed bug in unparse() that caused incorrect column order
|
||||||
|
(Issue #41).
|
||||||
|
|
||||||
|
|
||||||
|
Code quality:
|
||||||
|
- Improved test coverage.
|
||||||
-----------------------------------
|
-----------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
18
Makefile
18
Makefile
@@ -11,5 +11,21 @@ phpunit-dep:
|
|||||||
exit 1 \
|
exit 1 \
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Requires:
|
||||||
|
# - Docker: https://docker.com
|
||||||
|
# - act: https://github.com/nektos/act
|
||||||
|
local-ci:
|
||||||
|
ifeq (, $(shell which act))
|
||||||
|
define ACT_ERROR
|
||||||
|
Consider running the following to install 'act':
|
||||||
|
|
||||||
|
curl https://raw.githubusercontent.com/nektos/act/master/install.sh | sudo bash
|
||||||
|
|
||||||
|
The dependency 'act' was not found
|
||||||
|
endef
|
||||||
|
$(error ${ACT_ERROR})
|
||||||
|
endif
|
||||||
|
act -P ubuntu-latest=shivammathur/node:latest -W .github/workflows/ci.yml
|
||||||
|
|
||||||
.SILENT:
|
.SILENT:
|
||||||
.PHONY: test phpunit-dep
|
.PHONY: test phpunit-dep local-ci
|
||||||
|
|||||||
103
README.md
103
README.md
@@ -1,11 +1,12 @@
|
|||||||
# ParseCsv
|
# ParseCsv
|
||||||
|

|
||||||
|
|
||||||
ParseCsv is an easy-to-use PHP class that reads and writes CSV data properly. It
|
ParseCsv is an easy-to-use PHP class that reads and writes CSV data properly. It
|
||||||
fully conforms to the specifications outlined on the on the
|
fully conforms to the specifications outlined on the
|
||||||
[Wikipedia article][CSV] (and thus RFC 4180). It has many advanced features which help make your
|
[Wikipedia article][CSV] (and thus RFC 4180). It has many advanced features which help make your
|
||||||
life easier when dealing with CSV data.
|
life easier when dealing with CSV data.
|
||||||
|
|
||||||
You may not need a library at all: before using ParseCsv, please make sure if PHP's own `str_getcsv()`, ``fgetcvs()`` or `fputcsv()` meets your needs.
|
You may not need a library at all: before using ParseCsv, please make sure if PHP's own `str_getcsv()`, ``fgetcsv()`` or `fputcsv()` meets your needs.
|
||||||
|
|
||||||
This library was originally created in early 2007 by [jimeh](https://github.com/jimeh) due to the lack of built-in
|
This library was originally created in early 2007 by [jimeh](https://github.com/jimeh) due to the lack of built-in
|
||||||
and third-party support for handling CSV data in PHP.
|
and third-party support for handling CSV data in PHP.
|
||||||
@@ -27,7 +28,7 @@ and third-party support for handling CSV data in PHP.
|
|||||||
* Support for character encoding conversion using PHP's
|
* Support for character encoding conversion using PHP's
|
||||||
`iconv()` and `mb_convert_encoding()` functions.
|
`iconv()` and `mb_convert_encoding()` functions.
|
||||||
* Supports PHP 5.5 and higher.
|
* Supports PHP 5.5 and higher.
|
||||||
It certainly works with PHP 7.2 and all versions in between.
|
It certainly works with PHP 8.3 and all versions in between.
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
@@ -52,27 +53,20 @@ To use ParseCSV, you then have to add a `require 'parsecsv.lib.php';` line.
|
|||||||
|
|
||||||
## Example Usage
|
## Example Usage
|
||||||
|
|
||||||
**General**
|
**Parse a tab-delimited CSV file with encoding conversion**
|
||||||
|
|
||||||
```php
|
```php
|
||||||
$csv = new ParseCsv\Csv('data.csv');
|
$csv = new \ParseCsv\Csv();
|
||||||
print_r($csv->data);
|
|
||||||
```
|
|
||||||
|
|
||||||
**Tab delimited, and encoding conversion**
|
|
||||||
|
|
||||||
```php
|
|
||||||
$csv = new ParseCsv\Csv();
|
|
||||||
$csv->encoding('UTF-16', 'UTF-8');
|
$csv->encoding('UTF-16', 'UTF-8');
|
||||||
$csv->delimiter = "\t";
|
$csv->delimiter = "\t";
|
||||||
$csv->parse('data.tsv');
|
$csv->parseFile('data.tsv');
|
||||||
print_r($csv->data);
|
print_r($csv->data);
|
||||||
```
|
```
|
||||||
|
|
||||||
**Auto-detect delimiter character**
|
**Auto-detect field delimiter character**
|
||||||
|
|
||||||
```php
|
```php
|
||||||
$csv = new ParseCsv\Csv();
|
$csv = new \ParseCsv\Csv();
|
||||||
$csv->auto('data.csv');
|
$csv->auto('data.csv');
|
||||||
print_r($csv->data);
|
print_r($csv->data);
|
||||||
```
|
```
|
||||||
@@ -80,54 +74,63 @@ print_r($csv->data);
|
|||||||
**Parse data with offset**
|
**Parse data with offset**
|
||||||
* ignoring the first X (e.g. two) rows
|
* ignoring the first X (e.g. two) rows
|
||||||
```php
|
```php
|
||||||
$csv = new ParseCsv\Csv();
|
$csv = new \ParseCsv\Csv();
|
||||||
$csv->offset = 2;
|
$csv->offset = 2;
|
||||||
$csv->parse('data.csv');
|
$csv->parseFile('data.csv');
|
||||||
print_r($csv->data);
|
print_r($csv->data);
|
||||||
```
|
```
|
||||||
|
|
||||||
**Limit the number of returned data rows**
|
**Limit the number of returned data rows**
|
||||||
```php
|
```php
|
||||||
$csv = new ParseCsv\Csv();
|
$csv = new \ParseCsv\Csv();
|
||||||
$csv->limit = 5;
|
$csv->limit = 5;
|
||||||
$csv->parse('data.csv');
|
$csv->parseFile('data.csv');
|
||||||
print_r($csv->data);
|
print_r($csv->data);
|
||||||
```
|
```
|
||||||
|
|
||||||
**Get total number of data rows without parsing whole data**
|
**Get total number of data rows without parsing whole data**
|
||||||
* Excluding heading line if present (see $csv->header property)
|
* Excluding heading line if present (see $csv->header property)
|
||||||
```php
|
```php
|
||||||
$csv = new ParseCsv\Csv();
|
$csv = new \ParseCsv\Csv();
|
||||||
$csv->load_data('data.csv');
|
$csv->loadFile('data.csv');
|
||||||
$count = $csv->getTotalDataRowCount();
|
$count = $csv->getTotalDataRowCount();
|
||||||
print_r($count);
|
print_r($count);
|
||||||
```
|
```
|
||||||
|
|
||||||
**Get most common data type for each column (Requires PHP >= 5.5)**
|
**Get most common data type for each column**
|
||||||
|
|
||||||
```php
|
```php
|
||||||
$csv = new ParseCsv\Csv('data.csv');
|
$csv = new \ParseCsv\Csv('data.csv');
|
||||||
$csv->getDatatypes()
|
$csv->getDatatypes();
|
||||||
print_r($csv->data_types);
|
print_r($csv->data_types);
|
||||||
```
|
```
|
||||||
|
|
||||||
**Modify data in a CSV file**
|
**Modify data in a CSV file**
|
||||||
|
|
||||||
|
Change data values:
|
||||||
```php
|
```php
|
||||||
$csv = new ParseCsv\Csv();
|
$csv = new \ParseCsv\Csv();
|
||||||
$csv->sort_by = 'id';
|
$csv->sort_by = 'id';
|
||||||
$csv->parse('data.csv');
|
$csv->parseFile('data.csv');
|
||||||
# "4" is the value of the "id" column of the CSV row
|
# "4" is the value of the "id" column of the CSV row
|
||||||
$csv->data[4] = array('firstname' => 'John', 'lastname' => 'Doe', 'email' => 'john@doe.com');
|
$csv->data[4] = array('firstname' => 'John', 'lastname' => 'Doe', 'email' => 'john@doe.com');
|
||||||
$csv->save();
|
$csv->save();
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Enclose each data value by quotes:
|
||||||
|
```php
|
||||||
|
$csv = new \ParseCsv\Csv();
|
||||||
|
$csv->parseFile('data.csv');
|
||||||
|
$csv->enclose_all = true;
|
||||||
|
$csv->save();
|
||||||
|
```
|
||||||
|
|
||||||
**Replace field names or set ones if missing**
|
**Replace field names or set ones if missing**
|
||||||
|
|
||||||
```php
|
```php
|
||||||
$csv = new ParseCsv\Csv();
|
$csv = new \ParseCsv\Csv();
|
||||||
$csv->fields = ['id', 'name', 'category']
|
$csv->fields = ['id', 'name', 'category'];
|
||||||
$csv->parse('data.csv');
|
$csv->parseFile('data.csv');
|
||||||
```
|
```
|
||||||
|
|
||||||
**Add row/entry to end of CSV file**
|
**Add row/entry to end of CSV file**
|
||||||
@@ -135,19 +138,45 @@ $csv->parse('data.csv');
|
|||||||
_Only recommended when you know the exact structure of the file._
|
_Only recommended when you know the exact structure of the file._
|
||||||
|
|
||||||
```php
|
```php
|
||||||
$csv = new ParseCsv\Csv();
|
$csv = new \ParseCsv\Csv();
|
||||||
$csv->save('data.csv', array(array('1986', 'Home', 'Nowhere', '')), true);
|
$csv->save('data.csv', array(array('1986', 'Home', 'Nowhere', '')), /* append */ true);
|
||||||
```
|
```
|
||||||
|
|
||||||
**Convert 2D array to CSV data and send headers to browser to treat output as
|
**Convert 2D array to CSV data and send headers to browser to treat output as
|
||||||
a file and download it**
|
a file and download it**
|
||||||
|
|
||||||
|
Your web app users would call this an export.
|
||||||
|
|
||||||
```php
|
```php
|
||||||
$csv = new ParseCsv\Csv();
|
$csv = new \ParseCsv\Csv();
|
||||||
$csv->output('movies.csv', $array, array('field 1', 'field 2'), ',');
|
$csv->linefeed = "\n";
|
||||||
|
$header = array('field 1', 'field 2');
|
||||||
|
$csv->output('movies.csv', $data_array, $header, ',');
|
||||||
```
|
```
|
||||||
|
|
||||||
For more complex examples, see the ``tests`` and `examples` directories.
|
For more complex examples, see the ``tests`` and `examples` directories.
|
||||||
|
|
||||||
|
## Test coverage
|
||||||
|
|
||||||
|
All tests are located in the `tests` directory. To execute tests, run the following commands:
|
||||||
|
|
||||||
|
````bash
|
||||||
|
composer install
|
||||||
|
composer run test
|
||||||
|
````
|
||||||
|
|
||||||
|
Note that PHP 8.2 and newer allow PHPUnit versions that deprecate `@annotations`. The GitHub actions use Rector to
|
||||||
|
convert them to `#[attributes]`.
|
||||||
|
When pushing code to GitHub, tests will be executed using GitHub Actions. The relevant configuration is in the
|
||||||
|
file `.github/workflows/ci.yml`. To run the `test` action locally, you can execute the following command:
|
||||||
|
|
||||||
|
````bash
|
||||||
|
make local-ci
|
||||||
|
````
|
||||||
|
|
||||||
|
## Security
|
||||||
|
|
||||||
|
If you discover any security related issues, please email ParseCsv@blaeul.de instead of using GitHub issues.
|
||||||
|
|
||||||
## Credits
|
## Credits
|
||||||
|
|
||||||
@@ -160,12 +189,14 @@ For more complex examples, see the ``tests`` and `examples` directories.
|
|||||||
|
|
||||||
## Contributors
|
## Contributors
|
||||||
|
|
||||||
|
### Code Contributors
|
||||||
|
|
||||||
|
This project exists thanks to all the people who contribute.
|
||||||
|
|
||||||
Please find a complete list on the project's [contributors][] page.
|
Please find a complete list on the project's [contributors][] page.
|
||||||
|
|
||||||
[contributors]: https://github.com/parsecsv/parsecsv-for-php/graphs/contributors
|
[contributors]: https://github.com/parsecsv/parsecsv-for-php/graphs/contributors
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
(The MIT license)
|
(The MIT license)
|
||||||
|
|||||||
@@ -20,14 +20,13 @@
|
|||||||
"homepage": "https://github.com/Fonata"
|
"homepage": "https://github.com/Fonata"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"autoload":{
|
"autoload": {
|
||||||
"psr-4":{
|
"psr-4": {
|
||||||
"ParseCsv\\": "src",
|
"ParseCsv\\": "src"
|
||||||
"ParseCsv\\extensions\\": "src\\extensions"
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"autoload-dev":{
|
"autoload-dev": {
|
||||||
"psr-4":{
|
"psr-4": {
|
||||||
"ParseCsv\\tests\\": "tests"
|
"ParseCsv\\tests\\": "tests"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -35,11 +34,22 @@
|
|||||||
"php": ">=5.5"
|
"php": ">=5.5"
|
||||||
},
|
},
|
||||||
"require-dev": {
|
"require-dev": {
|
||||||
"phpunit/phpunit": "4.1.*"
|
"phpunit/phpunit": "8.5.52",
|
||||||
|
"squizlabs/php_codesniffer": "^3.5"
|
||||||
},
|
},
|
||||||
"suggest": {
|
"suggest": {
|
||||||
"illuminate/support": "Fluent array interface for map functions"
|
"illuminate/support": "Fluent array interface for map functions"
|
||||||
},
|
},
|
||||||
|
"extra": {
|
||||||
|
"branch-alias": {
|
||||||
|
"dev-master": "1.0.x-dev"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"test": [
|
||||||
|
"vendor/bin/phpunit -c tests tests --disallow-test-output --coverage-clover coverage_clover.xml --whitelist src"
|
||||||
|
]
|
||||||
|
},
|
||||||
"support": {
|
"support": {
|
||||||
"issues": "https://github.com/parsecsv/parsecsv-for-php/issues",
|
"issues": "https://github.com/parsecsv/parsecsv-for-php/issues",
|
||||||
"source": "https://github.com/parsecsv/parsecsv-for-php"
|
"source": "https://github.com/parsecsv/parsecsv-for-php"
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
|
|
||||||
# include parseCSV class.
|
# include parseCSV class.
|
||||||
require __DIR__ . '/../vendor/autoload.php';
|
require __DIR__ . '/../vendor/autoload.php';
|
||||||
|
|
||||||
use ParseCsv\Csv;
|
use ParseCsv\Csv;
|
||||||
|
|
||||||
|
|
||||||
@@ -17,8 +18,8 @@ $csv->auto('_books.csv');
|
|||||||
# if its not the default comma...
|
# if its not the default comma...
|
||||||
// $csv->delimiter = "\t"; # tab delimited
|
// $csv->delimiter = "\t"; # tab delimited
|
||||||
|
|
||||||
# ...and then use the parse() function.
|
# ...and then use the parseFile() function.
|
||||||
// $csv->parse('_books.csv');
|
// $csv->parseFile('_books.csv');
|
||||||
|
|
||||||
|
|
||||||
# Output result.
|
# Output result.
|
||||||
@@ -40,7 +41,7 @@ $csv->auto('_books.csv');
|
|||||||
background-color: #FFF;
|
background-color: #FFF;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
<table border="0" cellspacing="1" cellpadding="3">
|
<table>
|
||||||
<tr>
|
<tr>
|
||||||
<?php foreach ($csv->titles as $value): ?>
|
<?php foreach ($csv->titles as $value): ?>
|
||||||
<th><?php echo $value; ?></th>
|
<th><?php echo $value; ?></th>
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
# include parseCSV class.
|
# include parseCSV class.
|
||||||
require __DIR__ . '/../vendor/autoload.php';
|
require __DIR__ . '/../vendor/autoload.php';
|
||||||
|
|
||||||
use ParseCsv\Csv;
|
use ParseCsv\Csv;
|
||||||
|
|
||||||
|
|
||||||
@@ -16,6 +17,7 @@ $csv = new Csv();
|
|||||||
$csv->conditions = 'author does not contain dan brown';
|
$csv->conditions = 'author does not contain dan brown';
|
||||||
// $csv->conditions = 'rating < 4 OR author is John Twelve Hawks';
|
// $csv->conditions = 'rating < 4 OR author is John Twelve Hawks';
|
||||||
// $csv->conditions = 'rating > 4 AND author is Dan Brown';
|
// $csv->conditions = 'rating > 4 AND author is Dan Brown';
|
||||||
|
// $csv->conditions = 'rating is greater than 4';
|
||||||
|
|
||||||
|
|
||||||
# Parse '_books.csv' using automatic delimiter detection.
|
# Parse '_books.csv' using automatic delimiter detection.
|
||||||
@@ -41,7 +43,7 @@ $csv->auto('_books.csv');
|
|||||||
background-color: #FFF;
|
background-color: #FFF;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
<table border="0" cellspacing="1" cellpadding="3">
|
<table>
|
||||||
<tr>
|
<tr>
|
||||||
<?php foreach ($csv->titles as $value): ?>
|
<?php foreach ($csv->titles as $value): ?>
|
||||||
<th><?php echo $value; ?></th>
|
<th><?php echo $value; ?></th>
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
|
|
||||||
# include parseCSV class.
|
# include parseCSV class.
|
||||||
require __DIR__ . '/../vendor/autoload.php';
|
require __DIR__ . '/../vendor/autoload.php';
|
||||||
|
|
||||||
use ParseCsv\Csv;
|
use ParseCsv\Csv;
|
||||||
|
|
||||||
|
|
||||||
@@ -31,5 +32,3 @@ $csv->output('books.csv');
|
|||||||
# data to download the output as a CSV file. if it's not set
|
# data to download the output as a CSV file. if it's not set
|
||||||
# or is set to null, output will only return the generated CSV
|
# or is set to null, output will only return the generated CSV
|
||||||
# output data, and will not output to the browser itself.
|
# output data, and will not output to the browser itself.
|
||||||
|
|
||||||
?>
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
# include parseCSV class.
|
# include parseCSV class.
|
||||||
require __DIR__ . '/../vendor/autoload.php';
|
require __DIR__ . '/../vendor/autoload.php';
|
||||||
|
|
||||||
use ParseCsv\Csv;
|
use ParseCsv\Csv;
|
||||||
|
|
||||||
|
|
||||||
@@ -54,7 +55,7 @@ $csv->auto('_books.csv');
|
|||||||
background-color: #FFF;
|
background-color: #FFF;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
<table border="0" cellspacing="1" cellpadding="3">
|
<table>
|
||||||
<tr>
|
<tr>
|
||||||
<?php foreach ($csv->titles as $value): ?>
|
<?php foreach ($csv->titles as $value): ?>
|
||||||
<th><?php echo $value; ?></th>
|
<th><?php echo $value; ?></th>
|
||||||
|
|||||||
27
examples/save_to_file_without_header_row.php
Normal file
27
examples/save_to_file_without_header_row.php
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
|
||||||
|
# include parseCSV class.
|
||||||
|
require __DIR__ . '/../vendor/autoload.php';
|
||||||
|
|
||||||
|
use ParseCsv\Csv;
|
||||||
|
|
||||||
|
|
||||||
|
# Create new parseCSV object.
|
||||||
|
$csv = new Csv();
|
||||||
|
|
||||||
|
# When saving, don't write the header row:
|
||||||
|
$csv->heading = false;
|
||||||
|
|
||||||
|
# Specify which columns to write, and in which order.
|
||||||
|
# We won't output the 'Awesome' column this time.
|
||||||
|
$csv->titles = ['Age', 'Name'];
|
||||||
|
|
||||||
|
# Data to write:
|
||||||
|
$csv->data = [
|
||||||
|
0 => ['Name' => 'Anne', 'Age' => 45, 'Awesome' => true],
|
||||||
|
1 => ['Name' => 'John', 'Age' => 44, 'Awesome' => false],
|
||||||
|
];
|
||||||
|
|
||||||
|
# Then we save the file to the file system:
|
||||||
|
$csv->save('people.csv');
|
||||||
3
ruleset.xml
Normal file
3
ruleset.xml
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
<?xml version="1.0"?>
|
||||||
|
<ruleset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="ParseCSV" xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/squizlabs/PHP_CodeSniffer/master/phpcs.xsd">
|
||||||
|
</ruleset>
|
||||||
470
src/Csv.php
470
src/Csv.php
@@ -49,7 +49,7 @@ class Csv {
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Heading
|
* Header row:
|
||||||
* Use first line/entry as field names
|
* Use first line/entry as field names
|
||||||
*
|
*
|
||||||
* @var bool
|
* @var bool
|
||||||
@@ -57,7 +57,6 @@ class Csv {
|
|||||||
public $heading = true;
|
public $heading = true;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fields
|
|
||||||
* Override field names
|
* Override field names
|
||||||
*
|
*
|
||||||
* @var array
|
* @var array
|
||||||
@@ -65,7 +64,6 @@ class Csv {
|
|||||||
public $fields = array();
|
public $fields = array();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sort By
|
|
||||||
* Sort CSV by this field
|
* Sort CSV by this field
|
||||||
*
|
*
|
||||||
* @var string|null
|
* @var string|null
|
||||||
@@ -73,15 +71,13 @@ class Csv {
|
|||||||
public $sort_by = null;
|
public $sort_by = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sort Reverse
|
* Reverse the sort direction
|
||||||
* Reverse the sort function
|
|
||||||
*
|
*
|
||||||
* @var bool
|
* @var bool
|
||||||
*/
|
*/
|
||||||
public $sort_reverse = false;
|
public $sort_reverse = false;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sort Type
|
|
||||||
* Sort behavior passed to sort methods
|
* Sort behavior passed to sort methods
|
||||||
*
|
*
|
||||||
* regular = SORT_REGULAR
|
* regular = SORT_REGULAR
|
||||||
@@ -93,31 +89,34 @@ class Csv {
|
|||||||
public $sort_type = SortEnum::SORT_TYPE_REGULAR;
|
public $sort_type = SortEnum::SORT_TYPE_REGULAR;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Delimiter
|
* Field delimiter character
|
||||||
* Delimiter character
|
|
||||||
*
|
*
|
||||||
* @var string
|
* @var string
|
||||||
*/
|
*/
|
||||||
public $delimiter = ',';
|
public $delimiter = ',';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Enclosure
|
|
||||||
* Enclosure character
|
* Enclosure character
|
||||||
*
|
*
|
||||||
|
* This is useful for cell values that are either multi-line
|
||||||
|
* or contain the field delimiter character.
|
||||||
|
*
|
||||||
* @var string
|
* @var string
|
||||||
*/
|
*/
|
||||||
public $enclosure = '"';
|
public $enclosure = '"';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Enclose All
|
* Force enclosing all columns.
|
||||||
* Force enclosing all columns
|
*
|
||||||
|
* If false, only cells that are either multi-line or
|
||||||
|
* contain the field delimiter character are enclosed
|
||||||
|
* in the $enclosure char.
|
||||||
*
|
*
|
||||||
* @var bool
|
* @var bool
|
||||||
*/
|
*/
|
||||||
public $enclose_all = false;
|
public $enclose_all = false;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Conditions
|
|
||||||
* Basic SQL-Like conditions for row matching
|
* Basic SQL-Like conditions for row matching
|
||||||
*
|
*
|
||||||
* @var string|null
|
* @var string|null
|
||||||
@@ -125,7 +124,6 @@ class Csv {
|
|||||||
public $conditions = null;
|
public $conditions = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Offset
|
|
||||||
* Number of rows to ignore from beginning of data. If present, the heading
|
* Number of rows to ignore from beginning of data. If present, the heading
|
||||||
* row is also counted (if $this->heading == true). In other words,
|
* row is also counted (if $this->heading == true). In other words,
|
||||||
* $offset == 1 and $offset == 0 have the same meaning in that situation.
|
* $offset == 1 and $offset == 0 have the same meaning in that situation.
|
||||||
@@ -135,7 +133,6 @@ class Csv {
|
|||||||
public $offset = null;
|
public $offset = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Limit
|
|
||||||
* Limits the number of returned rows to the specified amount
|
* Limits the number of returned rows to the specified amount
|
||||||
*
|
*
|
||||||
* @var int|null
|
* @var int|null
|
||||||
@@ -143,7 +140,6 @@ class Csv {
|
|||||||
public $limit = null;
|
public $limit = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Auto Depth
|
|
||||||
* Number of rows to analyze when attempting to auto-detect delimiter
|
* Number of rows to analyze when attempting to auto-detect delimiter
|
||||||
*
|
*
|
||||||
* @var int
|
* @var int
|
||||||
@@ -151,7 +147,6 @@ class Csv {
|
|||||||
public $auto_depth = 15;
|
public $auto_depth = 15;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Auto Non Charts
|
|
||||||
* Characters that should be ignored when attempting to auto-detect delimiter
|
* Characters that should be ignored when attempting to auto-detect delimiter
|
||||||
*
|
*
|
||||||
* @var string
|
* @var string
|
||||||
@@ -159,7 +154,6 @@ class Csv {
|
|||||||
public $auto_non_chars = "a-zA-Z0-9\n\r";
|
public $auto_non_chars = "a-zA-Z0-9\n\r";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Auto Preferred
|
|
||||||
* preferred delimiter characters, only used when all filtering method
|
* preferred delimiter characters, only used when all filtering method
|
||||||
* returns multiple possible delimiters (happens very rarely)
|
* returns multiple possible delimiters (happens very rarely)
|
||||||
*
|
*
|
||||||
@@ -168,15 +162,14 @@ class Csv {
|
|||||||
public $auto_preferred = ",;\t.:|";
|
public $auto_preferred = ",;\t.:|";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Convert Encoding
|
* Should we convert the CSV character encoding?
|
||||||
* Should we convert the csv encoding?
|
* Used for both parse and unparse operations.
|
||||||
*
|
*
|
||||||
* @var bool
|
* @var bool
|
||||||
*/
|
*/
|
||||||
public $convert_encoding = false;
|
public $convert_encoding = false;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Input Encoding
|
|
||||||
* Set the input encoding
|
* Set the input encoding
|
||||||
*
|
*
|
||||||
* @var string
|
* @var string
|
||||||
@@ -184,7 +177,6 @@ class Csv {
|
|||||||
public $input_encoding = 'ISO-8859-1';
|
public $input_encoding = 'ISO-8859-1';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Output Encoding
|
|
||||||
* Set the output encoding
|
* Set the output encoding
|
||||||
*
|
*
|
||||||
* @var string
|
* @var string
|
||||||
@@ -202,15 +194,14 @@ class Csv {
|
|||||||
public $use_mb_convert_encoding = false;
|
public $use_mb_convert_encoding = false;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Linefeed
|
|
||||||
* Line feed characters used by unparse, save, and output methods
|
* Line feed characters used by unparse, save, and output methods
|
||||||
|
* Popular choices are "\r\n" and "\n".
|
||||||
*
|
*
|
||||||
* @var string
|
* @var string
|
||||||
*/
|
*/
|
||||||
public $linefeed = "\r";
|
public $linefeed = "\r";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Output Delimiter
|
|
||||||
* Sets the output delimiter used by the output method
|
* Sets the output delimiter used by the output method
|
||||||
*
|
*
|
||||||
* @var string
|
* @var string
|
||||||
@@ -218,7 +209,6 @@ class Csv {
|
|||||||
public $output_delimiter = ',';
|
public $output_delimiter = ',';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Output filename
|
|
||||||
* Sets the output filename
|
* Sets the output filename
|
||||||
*
|
*
|
||||||
* @var string
|
* @var string
|
||||||
@@ -226,7 +216,6 @@ class Csv {
|
|||||||
public $output_filename = 'data.csv';
|
public $output_filename = 'data.csv';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Keep File Data
|
|
||||||
* keep raw file data in memory after successful parsing (useful for debugging)
|
* keep raw file data in memory after successful parsing (useful for debugging)
|
||||||
*
|
*
|
||||||
* @var bool
|
* @var bool
|
||||||
@@ -270,7 +259,6 @@ class Csv {
|
|||||||
public $error = 0;
|
public $error = 0;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Error Information
|
|
||||||
* Detailed error information
|
* Detailed error information
|
||||||
*
|
*
|
||||||
* @var array
|
* @var array
|
||||||
@@ -278,54 +266,69 @@ class Csv {
|
|||||||
public $error_info = array();
|
public $error_info = array();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Titles
|
* $titles has 4 distinct tasks:
|
||||||
* CSV titles if they exists
|
* 1. After reading in CSV data, $titles will contain the column headers
|
||||||
|
* present in the data.
|
||||||
|
*
|
||||||
|
* 2. It defines which fields from the $data array to write e.g. when
|
||||||
|
* calling unparse(), and in which order. This lets you skip columns you
|
||||||
|
* don't want in your output, but are present in $data.
|
||||||
|
* See examples/save_to_file_without_header_row.php.
|
||||||
|
*
|
||||||
|
* 3. It lets you rename columns. See StreamTest::testWriteStream for an
|
||||||
|
* example.
|
||||||
|
*
|
||||||
|
* 4. When writing data and $header is true, then $titles is also used for
|
||||||
|
* the first row.
|
||||||
*
|
*
|
||||||
* @var array
|
* @var array
|
||||||
*/
|
*/
|
||||||
public $titles = array();
|
public $titles = array();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Data
|
* Two-dimensional array of CSV data.
|
||||||
* Two dimensional array of CSV data
|
* The first dimension are the line numbers. Each line is represented as an array with field names as keys.
|
||||||
*
|
*
|
||||||
* @var array
|
* @var array<array>
|
||||||
*/
|
*/
|
||||||
public $data = array();
|
public $data = array();
|
||||||
|
|
||||||
use DatatypeTrait;
|
use DatatypeTrait;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructor
|
|
||||||
* Class constructor
|
* Class constructor
|
||||||
*
|
*
|
||||||
* @param string|null $input The CSV string or a direct filepath
|
* @param string|null $data The CSV string or a direct file path.
|
||||||
* @param integer|null $offset Number of rows to ignore from the
|
*
|
||||||
* beginning of the data
|
* WARNING: Supplying file paths here is
|
||||||
* @param integer|null $limit Limits the number of returned rows
|
* deprecated. Use parseFile() instead.
|
||||||
* to specified amount
|
*
|
||||||
* @param string|null $conditions Basic SQL-like conditions for row
|
* @param int|null $offset Number of rows to ignore from the
|
||||||
* matching
|
* beginning of the data
|
||||||
* @param null|true $keep_file_data Keep raw file data in memory after
|
* @param int|null $limit Limits the number of returned rows
|
||||||
* successful parsing
|
* to specified amount
|
||||||
* (useful for debugging)
|
* @param string|null $conditions Basic SQL-like conditions for row
|
||||||
|
* matching
|
||||||
|
* @param null|true $keep_file_data Keep raw file data in memory after
|
||||||
|
* successful parsing
|
||||||
|
* (useful for debugging)
|
||||||
*/
|
*/
|
||||||
public function __construct($input = null, $offset = null, $limit = null, $conditions = null, $keep_file_data = null) {
|
public function __construct($data = null, $offset = null, $limit = null, $conditions = null, $keep_file_data = null) {
|
||||||
$this->init($offset, $limit, $conditions, $keep_file_data);
|
$this->init($offset, $limit, $conditions, $keep_file_data);
|
||||||
|
|
||||||
if (!empty($input)) {
|
if (!empty($data)) {
|
||||||
$this->parse($input);
|
$this->parse($data);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param integer|null $offset Number of rows to ignore from the
|
* @param int|null $offset Number of rows to ignore from the
|
||||||
* beginning of the data
|
* beginning of the data
|
||||||
* @param integer|null $limit Limits the number of returned rows
|
* @param int|null $limit Limits the number of returned rows
|
||||||
* to specified amount
|
* to specified amount
|
||||||
* @param string|null $conditions Basic SQL-like conditions for row
|
* @param string|null $conditions Basic SQL-like conditions for row
|
||||||
* matching
|
* matching
|
||||||
* @param null|true $keep_file_data Keep raw file data in memory after
|
* @param null|true $keep_file_data Keep raw file data in memory after
|
||||||
* successful parsing
|
* successful parsing
|
||||||
* (useful for debugging)
|
* (useful for debugging)
|
||||||
*/
|
*/
|
||||||
@@ -352,54 +355,63 @@ class Csv {
|
|||||||
// ==============================================
|
// ==============================================
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Parse
|
|
||||||
* Parse a CSV file or string
|
* Parse a CSV file or string
|
||||||
*
|
*
|
||||||
* @param string|null $input The CSV string or a direct filepath
|
* @param string|null $dataString The CSV string or a direct file path
|
||||||
* @param integer $offset Number of rows to ignore from the
|
* WARNING: Supplying file paths here is
|
||||||
|
* deprecated and will trigger an
|
||||||
|
* E_USER_DEPRECATED error.
|
||||||
|
* @param int|null $offset Number of rows to ignore from the
|
||||||
* beginning of the data
|
* beginning of the data
|
||||||
* @param integer $limit Limits the number of returned rows to
|
* @param int|null $limit Limits the number of returned rows to
|
||||||
* specified amount
|
* specified amount
|
||||||
* @param string $conditions Basic SQL-like conditions for row
|
* @param string|null $conditions Basic SQL-like conditions for row
|
||||||
* matching
|
* matching
|
||||||
*
|
*
|
||||||
* @return bool True on success
|
* @return bool True on success
|
||||||
*/
|
*/
|
||||||
public function parse($input = null, $offset = null, $limit = null, $conditions = null) {
|
public function parse($dataString = null, $offset = null, $limit = null, $conditions = null) {
|
||||||
if (is_null($input)) {
|
if (is_null($dataString)) {
|
||||||
$input = $this->file;
|
$this->data = $this->parseFile();
|
||||||
|
return $this->data !== false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (empty($input)) {
|
if (empty($dataString)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->init($offset, $limit, $conditions);
|
$this->init($offset, $limit, $conditions);
|
||||||
|
|
||||||
if (strlen($input) <= PHP_MAXPATHLEN && is_readable($input)) {
|
if (strlen($dataString) <= PHP_MAXPATHLEN && is_readable($dataString)) {
|
||||||
$this->file = $input;
|
$this->file = $dataString;
|
||||||
$this->data = $this->parse_file();
|
$this->data = $this->parseFile();
|
||||||
|
trigger_error(
|
||||||
|
'Supplying file paths to parse() will no longer ' .
|
||||||
|
'be supported in a future version of ParseCsv. ' .
|
||||||
|
'Use ->parseFile() instead.',
|
||||||
|
E_USER_DEPRECATED
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
$this->file = null;
|
$this->file = null;
|
||||||
$this->file_data = &$input;
|
$this->file_data = &$dataString;
|
||||||
$this->data = $this->parse_string();
|
$this->data = $this->_parse_string();
|
||||||
}
|
}
|
||||||
|
|
||||||
return $this->data !== false;
|
return $this->data !== false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Save
|
* Save changes, or write a new file and/or data.
|
||||||
* Save changes, or write a new file and/or data
|
|
||||||
*
|
*
|
||||||
* @param string $file File location to save to
|
* @param string $file File location to save to
|
||||||
* @param array $data 2D array of data
|
* @param array $data 2D array of data
|
||||||
* @param bool $append Append current data to end of target CSV, if file
|
* @param bool $append Append current data to end of target CSV, if file
|
||||||
* exists
|
* exists
|
||||||
* @param array $fields Field names. Sets the header. If it is not set
|
* @param array $fields Field names. Sets the header. If it is not set
|
||||||
* $this->titles would be used instead.
|
* $this->titles would be used instead.
|
||||||
*
|
*
|
||||||
* @return bool
|
* @return bool
|
||||||
|
* True on success
|
||||||
*/
|
*/
|
||||||
public function save($file = '', $data = array(), $append = FileProcessingModeEnum::MODE_FILE_OVERWRITE, $fields = array()) {
|
public function save($file = '', $data = array(), $append = FileProcessingModeEnum::MODE_FILE_OVERWRITE, $fields = array()) {
|
||||||
if (empty($file)) {
|
if (empty($file)) {
|
||||||
@@ -407,25 +419,26 @@ class Csv {
|
|||||||
}
|
}
|
||||||
|
|
||||||
$mode = FileProcessingModeEnum::getAppendMode($append);
|
$mode = FileProcessingModeEnum::getAppendMode($append);
|
||||||
$is_php = preg_match('/\.php$/i', $file) ? true : false;
|
$is_php = (bool) preg_match('/\.php$/i', $file);
|
||||||
|
|
||||||
return $this->_wfile($file, $this->unparse($data, $fields, $append, $is_php), $mode);
|
return $this->_wfile($file, $this->unparse($data, $fields, $append, $is_php), $mode);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Output
|
* Generate a CSV-based string for output.
|
||||||
* Generate a CSV based string for output.
|
|
||||||
*
|
*
|
||||||
* @param string|null $filename If a filename is specified here or in the
|
* Useful for exports in web applications.
|
||||||
|
*
|
||||||
|
* @param string|null $filename If a filename is specified here or in the
|
||||||
* object, headers and data will be output
|
* object, headers and data will be output
|
||||||
* directly to browser as a downloadable
|
* directly to browser as a downloadable
|
||||||
* file. This file doesn't have to exist on
|
* file. This file doesn't have to exist on
|
||||||
* the server; the parameter only affects
|
* the server; the parameter only affects
|
||||||
* how the download is called to the
|
* how the download is called to the
|
||||||
* browser.
|
* browser.
|
||||||
* @param array[] $data 2D array with data
|
* @param array[] $data 2D array with data
|
||||||
* @param array $fields Field names
|
* @param array $fields Field names
|
||||||
* @param string|null $delimiter character used to separate data
|
* @param string|null $delimiter character used to separate data
|
||||||
*
|
*
|
||||||
* @return string The resulting CSV string
|
* @return string The resulting CSV string
|
||||||
*/
|
*/
|
||||||
@@ -458,11 +471,17 @@ class Csv {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Encoding
|
|
||||||
* Convert character encoding
|
* Convert character encoding
|
||||||
*
|
*
|
||||||
* @param string $input Input character encoding, uses default if left blank
|
* Specify the encoding to use for the next parsing or unparsing.
|
||||||
* @param string $output Output character encoding, uses default if left blank
|
* Calling this function will not change the data held in the object immediately.
|
||||||
|
*
|
||||||
|
* @param string|null $input Input character encoding
|
||||||
|
* If the value null is passed, the existing input encoding remains set (default: ISO-8859-1).
|
||||||
|
* @param string|null $output Output character encoding, uses default if left blank
|
||||||
|
* If the value null is passed, the existing input encoding remains set (default: ISO-8859-1).
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
*/
|
*/
|
||||||
public function encoding($input = null, $output = null) {
|
public function encoding($input = null, $output = null) {
|
||||||
$this->convert_encoding = true;
|
$this->convert_encoding = true;
|
||||||
@@ -476,17 +495,19 @@ class Csv {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Auto
|
* Auto-detect delimiter: Find delimiter by analyzing a specific number of
|
||||||
* Auto-Detect Delimiter: Find delimiter by analyzing a specific number of
|
|
||||||
* rows to determine most probable delimiter character
|
* rows to determine most probable delimiter character
|
||||||
*
|
*
|
||||||
* @param string|null $file Local CSV file
|
* @param string|null $file Local CSV file
|
||||||
* @param bool $parse True/false parse file directly
|
* Supplying CSV data (file content) here is deprecated.
|
||||||
* @param int $search_depth Number of rows to analyze
|
* For CSV data, please use autoDetectionForDataString().
|
||||||
* @param string $preferred Preferred delimiter characters
|
* Support for CSV data will be removed in v2.0.0.
|
||||||
* @param string|null $enclosure Enclosure character, default is double quote (").
|
* @param bool $parse True/false parse file directly
|
||||||
|
* @param int|null $search_depth Number of rows to analyze
|
||||||
|
* @param string|null $preferred Preferred delimiter characters
|
||||||
|
* @param string|null $enclosure Enclosure character, default is double quote (").
|
||||||
*
|
*
|
||||||
* @return string The detected field delimiter
|
* @return string|false The detected field delimiter
|
||||||
*/
|
*/
|
||||||
public function auto($file = null, $parse = true, $search_depth = null, $preferred = null, $enclosure = null) {
|
public function auto($file = null, $parse = true, $search_depth = null, $preferred = null, $enclosure = null) {
|
||||||
if (is_null($file)) {
|
if (is_null($file)) {
|
||||||
@@ -517,13 +538,20 @@ class Csv {
|
|||||||
$data = &$this->file_data;
|
$data = &$this->file_data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$this->autoDetectionForDataString($data, $parse, $search_depth, $preferred, $enclosure);
|
||||||
|
|
||||||
|
return $this->delimiter;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function autoDetectionForDataString($data, $parse = true, $search_depth = null, $preferred = null, $enclosure = null) {
|
||||||
|
$this->file_data = &$data;
|
||||||
if (!$this->_detect_and_remove_sep_row_from_data($data)) {
|
if (!$this->_detect_and_remove_sep_row_from_data($data)) {
|
||||||
$this->_guess_delimiter($search_depth, $preferred, $enclosure, $data);
|
$this->_guess_delimiter($search_depth, $preferred, $enclosure, $data);
|
||||||
}
|
}
|
||||||
|
|
||||||
// parse data
|
// parse data
|
||||||
if ($parse) {
|
if ($parse) {
|
||||||
$this->data = $this->parse_string();
|
$this->data = $this->_parse_string();
|
||||||
}
|
}
|
||||||
|
|
||||||
return $this->delimiter;
|
return $this->delimiter;
|
||||||
@@ -559,12 +587,10 @@ class Csv {
|
|||||||
|
|
||||||
$headingRow = $this->heading ? 1 : 0;
|
$headingRow = $this->heading ? 1 : 0;
|
||||||
|
|
||||||
$count = substr_count($data, "\r")
|
return substr_count($data, "\r")
|
||||||
+ substr_count($data, "\n")
|
+ substr_count($data, "\n")
|
||||||
- substr_count($data, "\r\n")
|
- substr_count($data, "\r\n")
|
||||||
- $headingRow;
|
- $headingRow;
|
||||||
|
|
||||||
return $count;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ==============================================
|
// ==============================================
|
||||||
@@ -572,37 +598,50 @@ class Csv {
|
|||||||
// ==============================================
|
// ==============================================
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Parse File
|
* Read file to string and call _parse_string()
|
||||||
* Read file to string and call parse_string()
|
|
||||||
*
|
*
|
||||||
* @param string|null $file Local CSV file
|
* @param string|null $file Path to a CSV file.
|
||||||
|
* If configured in files such as php.ini,
|
||||||
|
* the path may also contain a protocol:
|
||||||
|
* https://example.org/some/file.csv
|
||||||
*
|
*
|
||||||
* @return array|bool
|
* @return array<array>|false
|
||||||
*/
|
*/
|
||||||
protected function parse_file($file = null) {
|
public function parseFile($file = null) {
|
||||||
if (is_null($file)) {
|
if (is_null($file)) {
|
||||||
$file = $this->file;
|
$file = $this->file;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (empty($this->file_data)) {
|
/**
|
||||||
$this->load_data($file);
|
* @see self::keep_file_data
|
||||||
|
* Usually, _parse_string will clean this
|
||||||
|
* Instead of leaving stale data for the next parseFile call behind.
|
||||||
|
*/
|
||||||
|
if (empty($this->file_data) && !$this->loadFile($file)) {
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
return !empty($this->file_data) ? $this->parse_string() : false;
|
if (empty($this->file_data)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return $this->data = $this->_parse_string();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Parse CSV strings to arrays. If you need BOM detection or character
|
* Internal function to parse CSV strings to arrays.
|
||||||
* encoding conversion, please call load_data() first, followed by a call to
|
*
|
||||||
* parse_string() with no parameters.
|
* If you need BOM detection or character encoding conversion, please call
|
||||||
|
* $csv->load_data($your_data_string) first, followed by a call to
|
||||||
|
* $csv->parse($csv->file_data).
|
||||||
*
|
*
|
||||||
* To detect field separators, please use auto() instead.
|
* To detect field separators, please use auto() instead.
|
||||||
*
|
*
|
||||||
* @param string $data CSV data
|
* @param string|null $data CSV data
|
||||||
*
|
*
|
||||||
* @return array|false - 2D array with CSV data, or false on failure
|
* @return array<array>|false
|
||||||
|
* 2D array with CSV data, or false on failure
|
||||||
*/
|
*/
|
||||||
protected function parse_string($data = null) {
|
protected function _parse_string($data = null) {
|
||||||
if (empty($data)) {
|
if (empty($data)) {
|
||||||
if ($this->_check_data()) {
|
if ($this->_check_data()) {
|
||||||
$data = &$this->file_data;
|
$data = &$this->file_data;
|
||||||
@@ -625,7 +664,7 @@ class Csv {
|
|||||||
|
|
||||||
// force the parser to process end of data as a character (false) when
|
// force the parser to process end of data as a character (false) when
|
||||||
// data does not end with a line feed or carriage return character.
|
// data does not end with a line feed or carriage return character.
|
||||||
$lch = $data{$strlen - 1};
|
$lch = $data[$strlen - 1];
|
||||||
if ($lch != "\n" && $lch != "\r") {
|
if ($lch != "\n" && $lch != "\r") {
|
||||||
$data .= "\n";
|
$data .= "\n";
|
||||||
$strlen++;
|
$strlen++;
|
||||||
@@ -633,8 +672,8 @@ class Csv {
|
|||||||
|
|
||||||
// walk through each character
|
// walk through each character
|
||||||
for ($i = 0; $i < $strlen; $i++) {
|
for ($i = 0; $i < $strlen; $i++) {
|
||||||
$ch = isset($data{$i}) ? $data{$i} : false;
|
$ch = isset($data[$i]) ? $data[$i] : false;
|
||||||
$nch = isset($data{$i + 1}) ? $data{$i + 1} : false;
|
$nch = isset($data[$i + 1]) ? $data[$i + 1] : false;
|
||||||
|
|
||||||
// open/close quotes, and inline quotes
|
// open/close quotes, and inline quotes
|
||||||
if ($ch == $this->enclosure) {
|
if ($ch == $this->enclosure) {
|
||||||
@@ -664,10 +703,10 @@ class Csv {
|
|||||||
$i++;
|
$i++;
|
||||||
} elseif ($nch != $this->delimiter && $nch != "\r" && $nch != "\n") {
|
} elseif ($nch != $this->delimiter && $nch != "\r" && $nch != "\n") {
|
||||||
$x = $i + 1;
|
$x = $i + 1;
|
||||||
while (isset($data{$x}) && ltrim($data{$x}, $white_spaces) == '') {
|
while (isset($data[$x]) && ltrim($data[$x], $white_spaces) == '') {
|
||||||
$x++;
|
$x++;
|
||||||
}
|
}
|
||||||
if ($data{$x} == $this->delimiter) {
|
if ($data[$x] == $this->delimiter) {
|
||||||
$enclosed = false;
|
$enclosed = false;
|
||||||
$i = $x;
|
$i = $x;
|
||||||
} else {
|
} else {
|
||||||
@@ -697,9 +736,8 @@ class Csv {
|
|||||||
} else {
|
} else {
|
||||||
$enclosed = false;
|
$enclosed = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// end of field/row/csv
|
// end of field/row/csv
|
||||||
} elseif (($ch === $this->delimiter || $ch == "\n" || $ch == "\r" || $ch === false) && !$enclosed) {
|
} elseif ((in_array($ch, [$this->delimiter, "\n", "\r", false], true)) && !$enclosed) {
|
||||||
$key = !empty($head[$col]) ? $head[$col] : $col;
|
$key = !empty($head[$col]) ? $head[$col] : $col;
|
||||||
$row[$key] = $was_enclosed ? $current : trim($current);
|
$row[$key] = $was_enclosed ? $current : trim($current);
|
||||||
$current = '';
|
$current = '';
|
||||||
@@ -707,7 +745,7 @@ class Csv {
|
|||||||
$col++;
|
$col++;
|
||||||
|
|
||||||
// end of row
|
// end of row
|
||||||
if ($ch == "\n" || $ch == "\r" || $ch === false) {
|
if (in_array($ch, ["\n", "\r", false], true)) {
|
||||||
if ($this->_validate_offset($row_count) && $this->_validate_row_conditions($row, $this->conditions)) {
|
if ($this->_validate_offset($row_count) && $this->_validate_row_conditions($row, $this->conditions)) {
|
||||||
if ($this->heading && empty($head)) {
|
if ($this->heading && empty($head)) {
|
||||||
$head = $row;
|
$head = $row;
|
||||||
@@ -817,9 +855,8 @@ class Csv {
|
|||||||
$string .= implode($delimiter, $entry) . $this->linefeed;
|
$string .= implode($delimiter, $entry) . $this->linefeed;
|
||||||
$entry = array();
|
$entry = array();
|
||||||
}
|
}
|
||||||
|
|
||||||
// create data
|
// create data
|
||||||
foreach ($data as $key => $row) {
|
foreach ($data as $row) {
|
||||||
foreach (array_keys($fieldOrder) as $index) {
|
foreach (array_keys($fieldOrder) as $index) {
|
||||||
$cell_value = $row[$index];
|
$cell_value = $row[$index];
|
||||||
$entry[] = $this->_enclose_value($cell_value, $delimiter);
|
$entry[] = $this->_enclose_value($cell_value, $delimiter);
|
||||||
@@ -830,13 +867,28 @@ class Csv {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if ($this->convert_encoding) {
|
if ($this->convert_encoding) {
|
||||||
$string = iconv($this->input_encoding, $this->output_encoding, $string);
|
/** @noinspection PhpComposerExtensionStubsInspection
|
||||||
|
*
|
||||||
|
* If you receive an error at the following 3 lines, you must enable
|
||||||
|
* the following PHP extension:
|
||||||
|
*
|
||||||
|
* - if $use_mb_convert_encoding is true: mbstring
|
||||||
|
* - if $use_mb_convert_encoding is false: iconv
|
||||||
|
*/
|
||||||
|
$string = $this->use_mb_convert_encoding ?
|
||||||
|
mb_convert_encoding($string, $this->output_encoding, $this->input_encoding) :
|
||||||
|
iconv($this->input_encoding, $this->output_encoding, $string);
|
||||||
}
|
}
|
||||||
|
|
||||||
return $string;
|
return $string;
|
||||||
}
|
}
|
||||||
|
|
||||||
private function _validate_fields_for_unparse($fields) {
|
/**
|
||||||
|
* @param array $fields
|
||||||
|
*
|
||||||
|
* @return array|false
|
||||||
|
*/
|
||||||
|
private function _validate_fields_for_unparse(array $fields) {
|
||||||
if (empty($fields)) {
|
if (empty($fields)) {
|
||||||
$fields = $this->titles;
|
$fields = $this->titles;
|
||||||
}
|
}
|
||||||
@@ -846,10 +898,10 @@ class Csv {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// this is needed because sometime titles property is overwritten instead of using fields parameter!
|
// this is needed because sometime titles property is overwritten instead of using fields parameter!
|
||||||
$titlesOnParse = !empty($this->data) ? array_keys($this->data[0]) : array();
|
$titlesOnParse = !empty($this->data) ? array_keys(reset($this->data)) : array();
|
||||||
|
|
||||||
// both are identical, also in ordering
|
// both are identical, also in ordering OR we have no data (only titles)
|
||||||
if (array_values($fields) === array_values($titlesOnParse)) {
|
if (empty($titlesOnParse) || array_values($fields) === array_values($titlesOnParse)) {
|
||||||
return array_combine($fields, $fields);
|
return array_combine($fields, $fields);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -877,33 +929,78 @@ class Csv {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Load local file or string
|
* Load local file or string.
|
||||||
*
|
*
|
||||||
* @param string|null $input local CSV file
|
* Only use this function if auto() and parse() don't handle your data well.
|
||||||
*
|
*
|
||||||
* @return true or false
|
* This function load_data() is able to handle BOMs and encodings. The data
|
||||||
|
* is stored within the $this->file_data class field.
|
||||||
|
*
|
||||||
|
* @param string|null $input CSV file path or CSV data as a string
|
||||||
|
*
|
||||||
|
* Supplying CSV data (file content) here is deprecated.
|
||||||
|
* For CSV data, please use loadDataString().
|
||||||
|
* Support for CSV data will be removed in v2.0.0.
|
||||||
|
*
|
||||||
|
* @return bool True on success
|
||||||
|
* @deprecated Use loadDataString() or loadFile() instead.
|
||||||
*/
|
*/
|
||||||
public function load_data($input = null) {
|
public function load_data($input = null) {
|
||||||
|
return $this->loadFile($input);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load a file, but don't parse it.
|
||||||
|
*
|
||||||
|
* Only use this function if auto() and parseFile() don't handle your data well.
|
||||||
|
*
|
||||||
|
* This function is able to handle BOMs and encodings. The data
|
||||||
|
* is stored within the $this->file_data class field.
|
||||||
|
*
|
||||||
|
* @param string|null $file CSV file path
|
||||||
|
*
|
||||||
|
* @return bool True on success
|
||||||
|
*/
|
||||||
|
public function loadFile($file = null) {
|
||||||
$data = null;
|
$data = null;
|
||||||
$file = null;
|
|
||||||
|
|
||||||
if (is_null($input)) {
|
if (is_null($file)) {
|
||||||
$file = $this->file;
|
$data = $this->_rfile($this->file);
|
||||||
} elseif (file_exists($input)) {
|
} elseif (\strlen($file) <= PHP_MAXPATHLEN && file_exists($file)) {
|
||||||
$file = $input;
|
$data = $this->_rfile($file);
|
||||||
} else {
|
|
||||||
$data = $input;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!empty($data) || $data = $this->_rfile($file)) {
|
|
||||||
if ($this->file != $file) {
|
if ($this->file != $file) {
|
||||||
$this->file = $file;
|
$this->file = $file;
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
// It is CSV data as a string.
|
||||||
|
|
||||||
if (preg_match('/\.php$/i', $file) && preg_match('/<\?.*?\?>(.*)/ms', $data, $strip)) {
|
// WARNING:
|
||||||
$data = ltrim($strip[1]);
|
// Supplying CSV data to load_data() will no longer
|
||||||
}
|
// be supported in a future version of ParseCsv.
|
||||||
|
// This function will return false for invalid paths from v2.0.0 onwards.
|
||||||
|
|
||||||
|
// Use ->loadDataString() instead.
|
||||||
|
|
||||||
|
$data = $file;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->loadDataString($data);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load a data string, but don't parse it.
|
||||||
|
*
|
||||||
|
* Only use this function if autoDetectionForDataString() and parse() don't handle your data well.
|
||||||
|
*
|
||||||
|
* This function is able to handle BOMs and encodings. The data
|
||||||
|
* is stored within the $this->file_data class field.
|
||||||
|
*
|
||||||
|
* @param string|null $file_path CSV file path
|
||||||
|
*
|
||||||
|
* @return bool True on success
|
||||||
|
*/
|
||||||
|
public function loadDataString($data) {
|
||||||
|
if (!empty($data)) {
|
||||||
if (strpos($data, "\xef\xbb\xbf") === 0) {
|
if (strpos($data, "\xef\xbb\xbf") === 0) {
|
||||||
// strip off BOM (UTF-8)
|
// strip off BOM (UTF-8)
|
||||||
$data = substr($data, 3);
|
$data = substr($data, 3);
|
||||||
@@ -919,6 +1016,14 @@ class Csv {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if ($this->convert_encoding && $this->input_encoding !== $this->output_encoding) {
|
if ($this->convert_encoding && $this->input_encoding !== $this->output_encoding) {
|
||||||
|
/** @noinspection PhpComposerExtensionStubsInspection
|
||||||
|
*
|
||||||
|
* If you receive an error at the following 3 lines, you must enable
|
||||||
|
* the following PHP extension:
|
||||||
|
*
|
||||||
|
* - if $use_mb_convert_encoding is true: mbstring
|
||||||
|
* - if $use_mb_convert_encoding is false: iconv
|
||||||
|
*/
|
||||||
$data = $this->use_mb_convert_encoding ?
|
$data = $this->use_mb_convert_encoding ?
|
||||||
mb_convert_encoding($data, $this->output_encoding, $this->input_encoding) :
|
mb_convert_encoding($data, $this->output_encoding, $this->input_encoding) :
|
||||||
iconv($this->input_encoding, $this->output_encoding, $data);
|
iconv($this->input_encoding, $this->output_encoding, $data);
|
||||||
@@ -945,7 +1050,7 @@ class Csv {
|
|||||||
* @param array $row array with values from a row
|
* @param array $row array with values from a row
|
||||||
* @param string|null $conditions specified conditions that the row must match
|
* @param string|null $conditions specified conditions that the row must match
|
||||||
*
|
*
|
||||||
* @return true of false
|
* @return bool
|
||||||
*/
|
*/
|
||||||
protected function _validate_row_conditions($row = array(), $conditions = null) {
|
protected function _validate_row_conditions($row = array(), $conditions = null) {
|
||||||
if (!empty($row)) {
|
if (!empty($row)) {
|
||||||
@@ -1003,6 +1108,8 @@ class Csv {
|
|||||||
'is greater than or equals',
|
'is greater than or equals',
|
||||||
'contains',
|
'contains',
|
||||||
'does not contain',
|
'does not contain',
|
||||||
|
'is number',
|
||||||
|
'is not number',
|
||||||
);
|
);
|
||||||
|
|
||||||
$operators_regex = array();
|
$operators_regex = array();
|
||||||
@@ -1015,10 +1122,22 @@ class Csv {
|
|||||||
|
|
||||||
if (preg_match('/^(.+) (' . $operators_regex . ') (.+)$/i', trim($condition), $capture)) {
|
if (preg_match('/^(.+) (' . $operators_regex . ') (.+)$/i', trim($condition), $capture)) {
|
||||||
$field = $capture[1];
|
$field = $capture[1];
|
||||||
$op = $capture[2];
|
$op = strtolower($capture[2]);
|
||||||
$value = $capture[3];
|
$value = $capture[3];
|
||||||
|
if ($op == 'equals' && preg_match('/^(.+) is (less|greater) than or$/i', $field, $m)) {
|
||||||
|
$field = $m[1];
|
||||||
|
$op = strtolower($m[2]) == 'less' ? '<=' : '>=';
|
||||||
|
}
|
||||||
|
if ($op == 'is' && preg_match('/^(less|greater) than (.+)$/i', $value, $m)) {
|
||||||
|
$value = $m[2];
|
||||||
|
$op = strtolower($m[1]) == 'less' ? '<' : '>';
|
||||||
|
}
|
||||||
|
if ($op == 'is' && preg_match('/^not (.+)$/i', $value, $m)) {
|
||||||
|
$value = $m[1];
|
||||||
|
$op = '!=';
|
||||||
|
}
|
||||||
|
|
||||||
if (preg_match('/^([\'\"]{1})(.*)([\'\"]{1})$/', $value, $capture) && $capture[1] == $capture[3]) {
|
if (preg_match('/^([\'"])(.*)([\'"])$/', $value, $capture) && $capture[1] == $capture[3]) {
|
||||||
$value = strtr($capture[2], array(
|
$value = strtr($capture[2], array(
|
||||||
"\\n" => "\n",
|
"\\n" => "\n",
|
||||||
"\\r" => "\r",
|
"\\r" => "\r",
|
||||||
@@ -1029,7 +1148,12 @@ class Csv {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (array_key_exists($field, $row)) {
|
if (array_key_exists($field, $row)) {
|
||||||
if (($op == '=' || $op == 'equals' || $op == 'is') && $row[$field] == $value) {
|
$op_equals = in_array($op, ['=', 'equals', 'is'], true);
|
||||||
|
if ($op_equals && $row[$field] == $value) {
|
||||||
|
return '1';
|
||||||
|
} elseif ($op_equals && $value == 'number' && is_numeric($row[$field])) {
|
||||||
|
return '1';
|
||||||
|
} elseif (($op == '!=' || $op == 'is not') && $value == 'number' && !is_numeric($row[$field])) {
|
||||||
return '1';
|
return '1';
|
||||||
} elseif (($op == '!=' || $op == 'is not') && $row[$field] != $value) {
|
} elseif (($op == '!=' || $op == 'is not') && $row[$field] != $value) {
|
||||||
return '1';
|
return '1';
|
||||||
@@ -1059,7 +1183,7 @@ class Csv {
|
|||||||
*
|
*
|
||||||
* @param int $current_row the current row number being processed
|
* @param int $current_row the current row number being processed
|
||||||
*
|
*
|
||||||
* @return true of false
|
* @return bool
|
||||||
*/
|
*/
|
||||||
protected function _validate_offset($current_row) {
|
protected function _validate_offset($current_row) {
|
||||||
return
|
return
|
||||||
@@ -1073,19 +1197,19 @@ class Csv {
|
|||||||
* Enclose values if needed
|
* Enclose values if needed
|
||||||
* - only used by unparse()
|
* - only used by unparse()
|
||||||
*
|
*
|
||||||
* @param string $value Cell value to process
|
* @param string|null $value Cell value to process
|
||||||
* @param string $delimiter Character to put between cells on the same row
|
* @param string $delimiter Character to put between cells on the same row
|
||||||
*
|
*
|
||||||
* @return string Processed value
|
* @return string Processed value
|
||||||
*/
|
*/
|
||||||
protected function _enclose_value($value = null, $delimiter) {
|
protected function _enclose_value($value, $delimiter) {
|
||||||
if ($value !== null && $value != '') {
|
if ($value !== null && $value != '') {
|
||||||
$delimiter_quoted = $delimiter ?
|
$delimiter_quoted = $delimiter ?
|
||||||
preg_quote($delimiter, '/') . "|"
|
preg_quote($delimiter, '/') . "|"
|
||||||
: '';
|
: '';
|
||||||
$enclosure_quoted = preg_quote($this->enclosure, '/');
|
$enclosure_quoted = preg_quote($this->enclosure, '/');
|
||||||
$pattern = "/" . $delimiter_quoted . $enclosure_quoted . "|\n|\r/i";
|
$pattern = "/" . $delimiter_quoted . $enclosure_quoted . "|\n|\r/i";
|
||||||
if ($this->enclose_all || preg_match($pattern, $value) || ($value{0} == ' ' || substr($value, -1) == ' ')) {
|
if ($this->enclose_all || preg_match($pattern, $value) || strpos($value, ' ') === 0 || substr($value, -1) == ' ') {
|
||||||
$value = str_replace($this->enclosure, $this->enclosure . $this->enclosure, $value);
|
$value = str_replace($this->enclosure, $this->enclosure . $this->enclosure, $value);
|
||||||
$value = $this->enclosure . $value . $this->enclosure;
|
$value = $this->enclosure . $value . $this->enclosure;
|
||||||
}
|
}
|
||||||
@@ -1097,7 +1221,7 @@ class Csv {
|
|||||||
/**
|
/**
|
||||||
* Check file data
|
* Check file data
|
||||||
*
|
*
|
||||||
* @param string|null $file local filename
|
* @param string|null $file local filename
|
||||||
*
|
*
|
||||||
* @return bool
|
* @return bool
|
||||||
*/
|
*/
|
||||||
@@ -1107,20 +1231,20 @@ class Csv {
|
|||||||
$file = $this->file;
|
$file = $this->file;
|
||||||
}
|
}
|
||||||
|
|
||||||
return $this->load_data($file);
|
return $this->loadFile($file);
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check if passed info might be delimiter
|
* Check if passed info might be delimiter.
|
||||||
* Only used by find_delimiter
|
* Only used by find_delimiter
|
||||||
*
|
*
|
||||||
* @param string $char Potential field separating character
|
* @param string $char Potential field separating character
|
||||||
* @param array $array Frequency
|
* @param array $array Frequency
|
||||||
* @param int $depth Number of analyzed rows
|
* @param int $depth Number of analyzed rows
|
||||||
* @param string $preferred Preferred delimiter characters
|
* @param string $preferred Preferred delimiter characters
|
||||||
*
|
*
|
||||||
* @return string|false special string used for delimiter selection, or false
|
* @return string|false special string used for delimiter selection, or false
|
||||||
*/
|
*/
|
||||||
@@ -1129,7 +1253,7 @@ class Csv {
|
|||||||
$first = null;
|
$first = null;
|
||||||
$equal = null;
|
$equal = null;
|
||||||
$almost = false;
|
$almost = false;
|
||||||
foreach ($array as $key => $value) {
|
foreach ($array as $value) {
|
||||||
if ($first == null) {
|
if ($first == null) {
|
||||||
$first = $value;
|
$first = $value;
|
||||||
} elseif ($value == $first && $equal !== false) {
|
} elseif ($value == $first && $equal !== false) {
|
||||||
@@ -1142,7 +1266,7 @@ class Csv {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($equal) {
|
if ($equal || $depth === 1) {
|
||||||
$match = $almost ? 2 : 1;
|
$match = $almost ? 2 : 1;
|
||||||
$pref = strpos($preferred, $char);
|
$pref = strpos($preferred, $char);
|
||||||
$pref = ($pref !== false) ? str_pad($pref, 3, '0', STR_PAD_LEFT) : '999';
|
$pref = ($pref !== false) ? str_pad($pref, 3, '0', STR_PAD_LEFT) : '999';
|
||||||
@@ -1158,16 +1282,23 @@ class Csv {
|
|||||||
/**
|
/**
|
||||||
* Read local file.
|
* Read local file.
|
||||||
*
|
*
|
||||||
* @param string $file local filename
|
* @param string $filePath local filename
|
||||||
*
|
*
|
||||||
* @return string|false Data from file, or false on failure
|
* @return string|false Data from file, or false on failure
|
||||||
*/
|
*/
|
||||||
protected function _rfile($file) {
|
protected function _rfile($filePath) {
|
||||||
if (is_readable($file)) {
|
if (is_readable($filePath)) {
|
||||||
$data = file_get_contents($file);
|
$data = file_get_contents($filePath);
|
||||||
if ($data === false) {
|
if ($data === false) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (preg_match('/\.php$/i', $filePath) && preg_match('/<\?.*?\?>(.*)/ms', $data, $strip)) {
|
||||||
|
// Return section behind closing tags.
|
||||||
|
// This parsing is deprecated and will be removed in v2.0.0.
|
||||||
|
$data = ltrim($strip[1]);
|
||||||
|
}
|
||||||
|
|
||||||
return rtrim($data, "\r\n");
|
return rtrim($data, "\r\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1177,12 +1308,14 @@ class Csv {
|
|||||||
/**
|
/**
|
||||||
* Write to local file
|
* Write to local file
|
||||||
*
|
*
|
||||||
* @param string $file local filename
|
* @param string $file local filename
|
||||||
* @param string $content data to write to file
|
* @param string $content data to write to file
|
||||||
* @param string $mode fopen() mode
|
* @param string $mode fopen() mode
|
||||||
* @param int $lock flock() mode
|
* @param int $lock flock() mode
|
||||||
|
*
|
||||||
|
* @return bool
|
||||||
|
* True on success
|
||||||
*
|
*
|
||||||
* @return true or false
|
|
||||||
*/
|
*/
|
||||||
protected function _wfile($file, $content = '', $mode = 'wb', $lock = LOCK_EX) {
|
protected function _wfile($file, $content = '', $mode = 'wb', $lock = LOCK_EX) {
|
||||||
if ($fp = fopen($file, $mode)) {
|
if ($fp = fopen($file, $mode)) {
|
||||||
@@ -1244,7 +1377,6 @@ class Csv {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// remove delimiter and its line-end (the data param is by-ref!)
|
// remove delimiter and its line-end (the data param is by-ref!)
|
||||||
/** @noinspection CallableParameterUseCaseInTypeContextInspection */
|
|
||||||
$data_string = substr($data_string, $pos);
|
$data_string = substr($data_string, $pos);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -1255,7 +1387,7 @@ class Csv {
|
|||||||
* @param string $enclosure Enclosure character, default is double quote
|
* @param string $enclosure Enclosure character, default is double quote
|
||||||
* @param string $data The file content
|
* @param string $data The file content
|
||||||
*/
|
*/
|
||||||
protected function _guess_delimiter($search_depth, $preferred, $enclosure, &$data) {
|
protected function _guess_delimiter($search_depth, $preferred, $enclosure, $data) {
|
||||||
$chars = [];
|
$chars = [];
|
||||||
$strlen = strlen($data);
|
$strlen = strlen($data);
|
||||||
$enclosed = false;
|
$enclosed = false;
|
||||||
@@ -1270,15 +1402,15 @@ class Csv {
|
|||||||
|
|
||||||
// walk specific depth finding possible delimiter characters
|
// walk specific depth finding possible delimiter characters
|
||||||
for ($i = 0; $i < $strlen; $i++) {
|
for ($i = 0; $i < $strlen; $i++) {
|
||||||
$ch = $data{$i};
|
$ch = $data[$i];
|
||||||
$nch = isset($data{$i + 1}) ? $data{$i + 1} : false;
|
$nch = isset($data[$i + 1]) ? $data[$i + 1] : false;
|
||||||
$pch = isset($data{$i - 1}) ? $data{$i - 1} : false;
|
$pch = isset($data[$i - 1]) ? $data[$i - 1] : false;
|
||||||
|
|
||||||
// open and closing quotes
|
// open and closing quotes
|
||||||
$is_newline = ($ch == "\n" && $pch != "\r") || $ch == "\r";
|
$is_newline = ($ch == "\n" && $pch != "\r") || $ch == "\r";
|
||||||
if ($ch == $enclosure) {
|
if ($ch == $enclosure) {
|
||||||
if (!$enclosed || $nch != $enclosure) {
|
if (!$enclosed || $nch != $enclosure) {
|
||||||
$enclosed = $enclosed ? false : true;
|
$enclosed = !$enclosed;
|
||||||
} elseif ($enclosed) {
|
} elseif ($enclosed) {
|
||||||
$i++;
|
$i++;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace ParseCsv\enums;
|
namespace ParseCsv\enums;
|
||||||
|
|
||||||
use ReflectionClass;
|
|
||||||
|
|
||||||
abstract class AbstractEnum {
|
abstract class AbstractEnum {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a new value of some type
|
* Creates a new value of some type
|
||||||
*
|
*
|
||||||
@@ -11,15 +11,14 @@ abstract class AbstractEnum {
|
|||||||
*
|
*
|
||||||
* @throws \UnexpectedValueException if incompatible type is given.
|
* @throws \UnexpectedValueException if incompatible type is given.
|
||||||
*/
|
*/
|
||||||
public function __construct($value)
|
public function __construct($value) {
|
||||||
{
|
|
||||||
if (!$this->isValid($value)) {
|
if (!$this->isValid($value)) {
|
||||||
throw new \UnexpectedValueException("Value '$value' is not part of the enum " . get_called_class());
|
throw new \UnexpectedValueException("Value '$value' is not part of the enum " . get_called_class());
|
||||||
}
|
}
|
||||||
$this->value = $value;
|
$this->value = $value;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function getConstants(){
|
public static function getConstants() {
|
||||||
$class = get_called_class();
|
$class = get_called_class();
|
||||||
$reflection = new \ReflectionClass($class);
|
$reflection = new \ReflectionClass($class);
|
||||||
|
|
||||||
@@ -33,8 +32,7 @@ abstract class AbstractEnum {
|
|||||||
*
|
*
|
||||||
* @return bool
|
* @return bool
|
||||||
*/
|
*/
|
||||||
public static function isValid($value)
|
public static function isValid($value) {
|
||||||
{
|
|
||||||
return in_array($value, static::getConstants(), true);
|
return in_array($value, static::getConstants(), true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ class FileProcessingModeEnum {
|
|||||||
const MODE_FILE_OVERWRITE = false;
|
const MODE_FILE_OVERWRITE = false;
|
||||||
|
|
||||||
public static function getAppendMode($mode) {
|
public static function getAppendMode($mode) {
|
||||||
if ($mode == self::MODE_FILE_APPEND){
|
if ($mode == self::MODE_FILE_APPEND) {
|
||||||
return 'ab';
|
return 'ab';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace ParseCsv\enums;
|
namespace ParseCsv\enums;
|
||||||
|
|
||||||
|
|
||||||
class SortEnum extends AbstractEnum {
|
class SortEnum extends AbstractEnum {
|
||||||
|
|
||||||
const __DEFAULT = self::SORT_TYPE_REGULAR;
|
const __DEFAULT = self::SORT_TYPE_REGULAR;
|
||||||
|
|
||||||
const SORT_TYPE_REGULAR = 'regular';
|
const SORT_TYPE_REGULAR = 'regular';
|
||||||
@@ -14,15 +16,14 @@ class SortEnum extends AbstractEnum {
|
|||||||
private static $sorting = array(
|
private static $sorting = array(
|
||||||
self::SORT_TYPE_REGULAR => SORT_REGULAR,
|
self::SORT_TYPE_REGULAR => SORT_REGULAR,
|
||||||
self::SORT_TYPE_STRING => SORT_STRING,
|
self::SORT_TYPE_STRING => SORT_STRING,
|
||||||
self::SORT_TYPE_NUMERIC => SORT_NUMERIC
|
self::SORT_TYPE_NUMERIC => SORT_NUMERIC,
|
||||||
);
|
);
|
||||||
|
|
||||||
public static function getSorting($type){
|
public static function getSorting($type) {
|
||||||
if (array_key_exists($type, self::$sorting)){
|
if (array_key_exists($type, self::$sorting)) {
|
||||||
return self::$sorting[$type];
|
return self::$sorting[$type];
|
||||||
}
|
}
|
||||||
|
|
||||||
return self::$sorting[self::__DEFAULT];
|
return self::$sorting[self::__DEFAULT];
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,10 +7,10 @@ use ParseCsv\enums\DatatypeEnum;
|
|||||||
trait DatatypeTrait {
|
trait DatatypeTrait {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Datatypes
|
* Data Types
|
||||||
* Datatypes of CSV data-columns
|
* Data types of CSV data-columns, keyed by the column name. Possible values
|
||||||
|
* are string, float, integer, boolean, date. See DatatypeEnum.
|
||||||
*
|
*
|
||||||
* @access public
|
|
||||||
* @var array
|
* @var array
|
||||||
*/
|
*/
|
||||||
public $data_types = [];
|
public $data_types = [];
|
||||||
@@ -19,9 +19,7 @@ trait DatatypeTrait {
|
|||||||
* Check data type for one column.
|
* Check data type for one column.
|
||||||
* Check for most commonly data type for one column.
|
* Check for most commonly data type for one column.
|
||||||
*
|
*
|
||||||
* @access private
|
* @param array $datatypes
|
||||||
*
|
|
||||||
* @param array $datatypes
|
|
||||||
*
|
*
|
||||||
* @return string|false
|
* @return string|false
|
||||||
*/
|
*/
|
||||||
@@ -38,7 +36,6 @@ trait DatatypeTrait {
|
|||||||
reset($typesFreq);
|
reset($typesFreq);
|
||||||
|
|
||||||
return key($typesFreq);
|
return key($typesFreq);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -47,15 +44,13 @@ trait DatatypeTrait {
|
|||||||
*
|
*
|
||||||
* Requires PHP >= 5.5
|
* Requires PHP >= 5.5
|
||||||
*
|
*
|
||||||
* @access public
|
|
||||||
*
|
|
||||||
* @uses DatatypeEnum::getValidTypeFromSample
|
* @uses DatatypeEnum::getValidTypeFromSample
|
||||||
*
|
*
|
||||||
* @return array|bool
|
* @return array|bool
|
||||||
*/
|
*/
|
||||||
public function getDatatypes() {
|
public function getDatatypes() {
|
||||||
if (empty($this->data)) {
|
if (empty($this->data)) {
|
||||||
$this->data = $this->parse_string();
|
$this->data = $this->_parse_string();
|
||||||
}
|
}
|
||||||
if (!is_array($this->data)) {
|
if (!is_array($this->data)) {
|
||||||
throw new \UnexpectedValueException('No data set yet.');
|
throw new \UnexpectedValueException('No data set yet.');
|
||||||
@@ -80,34 +75,28 @@ trait DatatypeTrait {
|
|||||||
*
|
*
|
||||||
* Requires PHP >= 5.5
|
* Requires PHP >= 5.5
|
||||||
*
|
*
|
||||||
* @access public
|
|
||||||
*
|
|
||||||
* @uses DatatypeEnum::getValidTypeFromSample
|
* @uses DatatypeEnum::getValidTypeFromSample
|
||||||
*
|
*
|
||||||
* @return bool
|
* @return bool
|
||||||
*/
|
*/
|
||||||
public function autoDetectFileHasHeading(){
|
public function autoDetectFileHasHeading() {
|
||||||
if (empty($this->data)){
|
if (empty($this->data)) {
|
||||||
throw new \UnexpectedValueException('No data set yet.');
|
throw new \UnexpectedValueException('No data set yet.');
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($this->heading){
|
if ($this->heading) {
|
||||||
$firstRow = $this->titles;
|
$firstRow = $this->titles;
|
||||||
} else {
|
} else {
|
||||||
$firstRow = $this->data[0];
|
$firstRow = $this->data[0];
|
||||||
}
|
}
|
||||||
|
|
||||||
$firstRow = array_filter($firstRow);
|
$firstRow = array_filter($firstRow);
|
||||||
if (empty($firstRow)){
|
if (empty($firstRow)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
$firstRowDatatype = array_map(DatatypeEnum::class . '::getValidTypeFromSample', $firstRow);
|
$firstRowDatatype = array_map(DatatypeEnum::class . '::getValidTypeFromSample', $firstRow);
|
||||||
|
|
||||||
if ($this->getMostFrequentDatatypeForColumn($firstRowDatatype) !== DatatypeEnum::TYPE_STRING){
|
return $this->getMostFrequentDatatypeForColumn($firstRowDatatype) === DatatypeEnum::TYPE_STRING;
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,8 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
chdir(__DIR__ . '/..');
|
chdir(__DIR__ . '/..');
|
||||||
if (!file_exists('vendor/autoload.php')) {
|
if (!file_exists('vendor/autoload.php')) {
|
||||||
`composer dump-autoload`;
|
`composer dump-autoload`;
|
||||||
}
|
}
|
||||||
|
|
||||||
require __DIR__ . '/../vendor/autoload.php';
|
require __DIR__ . '/../vendor/autoload.php';
|
||||||
|
|
||||||
if (!class_exists('PHPUnit\Framework\TestCase') && class_exists('PHPUnit_Framework_TestCase')) {
|
|
||||||
// we run on an older PHPUnit version without namespaces.
|
|
||||||
require_once __DIR__ . '/PHPUnit_Framework_TestCase.inc.php';
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace PHPUnit\Framework;
|
|
||||||
|
|
||||||
// Only needed to keep unit test code compatible with older PHPUnit versions
|
|
||||||
|
|
||||||
/** @noinspection PhpUndefinedClassInspection */
|
|
||||||
/** @noinspection AutoloadingIssuesInspection */
|
|
||||||
class TestCase extends \PHPUnit_Framework_TestCase {
|
|
||||||
|
|
||||||
}
|
|
||||||
1
tests/example_files/single_row.csv
Normal file
1
tests/example_files/single_row.csv
Normal file
@@ -0,0 +1 @@
|
|||||||
|
C1,C2,C3
|
||||||
|
@@ -59,8 +59,15 @@ class ConstructTest extends TestCase {
|
|||||||
/** @noinspection PhpIncludeInspection */
|
/** @noinspection PhpIncludeInspection */
|
||||||
require $script_file;
|
require $script_file;
|
||||||
$ob_get_clean = ob_get_clean();
|
$ob_get_clean = ob_get_clean();
|
||||||
if ($script_file != 'download.php') {
|
$verb = strtok($script_file, '_.');
|
||||||
$this->assertContains('<td>', $ob_get_clean);
|
|
||||||
|
if (!in_array($verb, ['download', 'save'], TRUE)) {
|
||||||
|
if (method_exists($this, 'assertStringContainsString')) {
|
||||||
|
$this->assertStringContainsString('<td>', $ob_get_clean);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
$this->assertContains('<td>', $ob_get_clean);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
chdir('..');
|
chdir('..');
|
||||||
|
|||||||
@@ -17,17 +17,11 @@ class DataRowCountTest extends TestCase {
|
|||||||
*/
|
*/
|
||||||
protected $csv;
|
protected $csv;
|
||||||
|
|
||||||
/**
|
protected function setUp(): void {
|
||||||
* Setup
|
|
||||||
* Setup our test environment objects
|
|
||||||
*
|
|
||||||
* @access public
|
|
||||||
*/
|
|
||||||
public function setUp() {
|
|
||||||
$this->csv = new Csv();
|
$this->csv = new Csv();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function countRowsProvider() {
|
public static function countRowsProvider() {
|
||||||
return [
|
return [
|
||||||
'auto-double-enclosure' => [
|
'auto-double-enclosure' => [
|
||||||
'auto-double-enclosure.csv',
|
'auto-double-enclosure.csv',
|
||||||
@@ -53,22 +47,22 @@ class DataRowCountTest extends TestCase {
|
|||||||
public function testGetTotalRowCountFromFile($file, $expectedRows) {
|
public function testGetTotalRowCountFromFile($file, $expectedRows) {
|
||||||
$this->csv->heading = true;
|
$this->csv->heading = true;
|
||||||
$this->csv->load_data(__DIR__ . '/fixtures/' . $file);
|
$this->csv->load_data(__DIR__ . '/fixtures/' . $file);
|
||||||
$this->assertEquals($expectedRows, $this->csv->getTotalDataRowCount());
|
self::assertEquals($expectedRows, $this->csv->getTotalDataRowCount());
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testGetTotalRowCountMissingEndingLineBreak() {
|
public function testGetTotalRowCountMissingEndingLineBreak() {
|
||||||
$this->csv->heading = false;
|
$this->csv->heading = false;
|
||||||
$this->csv->enclosure = '"';
|
$this->csv->enclosure = '"';
|
||||||
$sInput = "86545235689,a\r\n34365587654,b\r\n13469874576,\"c\r\nd\"";
|
$sInput = "86545235689,a\r\n34365587654,b\r\n13469874576,\"c\r\nd\"";
|
||||||
$this->csv->load_data($sInput);
|
$this->csv->loadDataString($sInput);
|
||||||
$this->assertEquals(3, $this->csv->getTotalDataRowCount());
|
self::assertEquals(3, $this->csv->getTotalDataRowCount());
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testGetTotalRowCountSingleEnclosure() {
|
public function testGetTotalRowCountSingleEnclosure() {
|
||||||
$this->csv->heading = false;
|
$this->csv->heading = false;
|
||||||
$this->csv->enclosure = "'";
|
$this->csv->enclosure = "'";
|
||||||
$sInput = "86545235689,a\r\n34365587654,b\r\n13469874576,\'c\r\nd\'";
|
$sInput = "86545235689,a\r\n34365587654,b\r\n13469874576,\'c\r\nd\'";
|
||||||
$this->csv->load_data($sInput);
|
$this->csv->loadDataString($sInput);
|
||||||
$this->assertEquals(3, $this->csv->getTotalDataRowCount());
|
$this->assertEquals(3, $this->csv->getTotalDataRowCount());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,7 +70,11 @@ class DataRowCountTest extends TestCase {
|
|||||||
$this->csv->heading = false;
|
$this->csv->heading = false;
|
||||||
$this->csv->enclosure = "'";
|
$this->csv->enclosure = "'";
|
||||||
$sInput = "86545235689";
|
$sInput = "86545235689";
|
||||||
$this->csv->load_data($sInput);
|
$this->csv->loadDataString($sInput);
|
||||||
$this->assertEquals(1, $this->csv->getTotalDataRowCount());
|
$this->assertEquals(1, $this->csv->getTotalDataRowCount());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function testGetTotalRowCountNoData() {
|
||||||
|
self::assertFalse($this->csv->getTotalDataRowCount());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,12 +8,12 @@
|
|||||||
|
|
||||||
namespace ParseCsv\tests\methods;
|
namespace ParseCsv\tests\methods;
|
||||||
|
|
||||||
use PHPUnit\Framework\TestCase;
|
|
||||||
use ParseCsv\enums\DatatypeEnum;
|
use ParseCsv\enums\DatatypeEnum;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
class DatatypeTest extends TestCase
|
class DatatypeTest extends TestCase {
|
||||||
{
|
|
||||||
public function testSampleIsValidInteger(){
|
public function testSampleIsValidInteger() {
|
||||||
$this->assertEquals(DatatypeEnum::TYPE_INT, DatatypeEnum::getValidTypeFromSample('1'));
|
$this->assertEquals(DatatypeEnum::TYPE_INT, DatatypeEnum::getValidTypeFromSample('1'));
|
||||||
$this->assertEquals(DatatypeEnum::TYPE_INT, DatatypeEnum::getValidTypeFromSample('+1'));
|
$this->assertEquals(DatatypeEnum::TYPE_INT, DatatypeEnum::getValidTypeFromSample('+1'));
|
||||||
$this->assertEquals(DatatypeEnum::TYPE_INT, DatatypeEnum::getValidTypeFromSample('-1'));
|
$this->assertEquals(DatatypeEnum::TYPE_INT, DatatypeEnum::getValidTypeFromSample('-1'));
|
||||||
@@ -27,7 +27,7 @@ class DatatypeTest extends TestCase
|
|||||||
$this->assertNotEquals(DatatypeEnum::TYPE_INT, DatatypeEnum::getValidTypeFromSample('2018-02-19'));
|
$this->assertNotEquals(DatatypeEnum::TYPE_INT, DatatypeEnum::getValidTypeFromSample('2018-02-19'));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testSampleIsValidBool(){
|
public function testSampleIsValidBool() {
|
||||||
$this->assertEquals(DatatypeEnum::TYPE_BOOL, DatatypeEnum::getValidTypeFromSample('true'));
|
$this->assertEquals(DatatypeEnum::TYPE_BOOL, DatatypeEnum::getValidTypeFromSample('true'));
|
||||||
$this->assertEquals(DatatypeEnum::TYPE_BOOL, DatatypeEnum::getValidTypeFromSample('TRUE'));
|
$this->assertEquals(DatatypeEnum::TYPE_BOOL, DatatypeEnum::getValidTypeFromSample('TRUE'));
|
||||||
$this->assertEquals(DatatypeEnum::TYPE_BOOL, DatatypeEnum::getValidTypeFromSample('false'));
|
$this->assertEquals(DatatypeEnum::TYPE_BOOL, DatatypeEnum::getValidTypeFromSample('false'));
|
||||||
@@ -39,7 +39,7 @@ class DatatypeTest extends TestCase
|
|||||||
$this->assertNotEquals(DatatypeEnum::TYPE_BOOL, DatatypeEnum::getValidTypeFromSample('0.1'));
|
$this->assertNotEquals(DatatypeEnum::TYPE_BOOL, DatatypeEnum::getValidTypeFromSample('0.1'));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testSampleIsValidFloat(){
|
public function testSampleIsValidFloat() {
|
||||||
$this->assertEquals(DatatypeEnum::TYPE_FLOAT, DatatypeEnum::getValidTypeFromSample('1.0'));
|
$this->assertEquals(DatatypeEnum::TYPE_FLOAT, DatatypeEnum::getValidTypeFromSample('1.0'));
|
||||||
$this->assertEquals(DatatypeEnum::TYPE_FLOAT, DatatypeEnum::getValidTypeFromSample('-1.1'));
|
$this->assertEquals(DatatypeEnum::TYPE_FLOAT, DatatypeEnum::getValidTypeFromSample('-1.1'));
|
||||||
$this->assertEquals(DatatypeEnum::TYPE_FLOAT, DatatypeEnum::getValidTypeFromSample('+1,1'));
|
$this->assertEquals(DatatypeEnum::TYPE_FLOAT, DatatypeEnum::getValidTypeFromSample('+1,1'));
|
||||||
@@ -54,7 +54,7 @@ class DatatypeTest extends TestCase
|
|||||||
$this->assertNotEquals(DatatypeEnum::TYPE_FLOAT, DatatypeEnum::getValidTypeFromSample('2018-02-19'));
|
$this->assertNotEquals(DatatypeEnum::TYPE_FLOAT, DatatypeEnum::getValidTypeFromSample('2018-02-19'));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testSampleIsValidDate(){
|
public function testSampleIsValidDate() {
|
||||||
$this->assertEquals(DatatypeEnum::TYPE_DATE, DatatypeEnum::getValidTypeFromSample('2018-02-19'));
|
$this->assertEquals(DatatypeEnum::TYPE_DATE, DatatypeEnum::getValidTypeFromSample('2018-02-19'));
|
||||||
$this->assertEquals(DatatypeEnum::TYPE_DATE, DatatypeEnum::getValidTypeFromSample('18-2-19'));
|
$this->assertEquals(DatatypeEnum::TYPE_DATE, DatatypeEnum::getValidTypeFromSample('18-2-19'));
|
||||||
$this->assertEquals(DatatypeEnum::TYPE_DATE, DatatypeEnum::getValidTypeFromSample('01.02.2018'));
|
$this->assertEquals(DatatypeEnum::TYPE_DATE, DatatypeEnum::getValidTypeFromSample('01.02.2018'));
|
||||||
|
|||||||
100
tests/methods/ExampleStream.php
Normal file
100
tests/methods/ExampleStream.php
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace ParseCsv\tests\methods;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This is a very simple implementation of a stream wrapper. All URLs are mapped
|
||||||
|
* to just one buffer. It exists to prove that ParseCsv can read and write
|
||||||
|
* streams.
|
||||||
|
*
|
||||||
|
* @see https://www.php.net/manual/en/class.streamwrapper.php
|
||||||
|
*/
|
||||||
|
class ExampleStream {
|
||||||
|
|
||||||
|
private static $position = 0;
|
||||||
|
|
||||||
|
private static $stream_content;
|
||||||
|
|
||||||
|
public function stream_open($uri, $mode) {
|
||||||
|
if (strpos($mode, 'a') === false) {
|
||||||
|
self::$position = 0;
|
||||||
|
}
|
||||||
|
if (strpos($mode, 'w') !== false) {
|
||||||
|
self::$stream_content = '';
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function stream_read($count) {
|
||||||
|
$ret = substr(self::$stream_content, self::$position, $count);
|
||||||
|
self::$position += strlen($ret);
|
||||||
|
return $ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function stream_write($data) {
|
||||||
|
$left = substr(self::$stream_content, 0, self::$position);
|
||||||
|
$right = substr(self::$stream_content, self::$position + strlen($data));
|
||||||
|
self::$stream_content = $left . $data . $right;
|
||||||
|
self::$position += strlen($data);
|
||||||
|
return strlen($data);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function stream_stat() {
|
||||||
|
return ['size' => strlen(self::$stream_content)];
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public function stream_tell() {
|
||||||
|
return self::$position;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function stream_eof() {
|
||||||
|
return self::$position >= strlen(self::$stream_content);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function url_stat() {
|
||||||
|
return ['size' => strlen(self::$stream_content)];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function stream_seek($offset, $whence) {
|
||||||
|
switch ($whence) {
|
||||||
|
case SEEK_SET:
|
||||||
|
if ($offset < strlen(self::$stream_content) && $offset >= 0) {
|
||||||
|
self::$position = $offset;
|
||||||
|
return true;
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case SEEK_CUR:
|
||||||
|
if ($offset >= 0) {
|
||||||
|
self::$position += $offset;
|
||||||
|
return true;
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case SEEK_END:
|
||||||
|
if (strlen(self::$stream_content) + $offset >= 0) {
|
||||||
|
self::$position = strlen(self::$stream_content) + $offset;
|
||||||
|
return true;
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function stream_lock($operation) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function stream_metadata() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
13
tests/methods/ObjectThatHasToStringMethod.php
Normal file
13
tests/methods/ObjectThatHasToStringMethod.php
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace ParseCsv\tests\methods;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class HasToString is just a helper to test if cells can be objects.
|
||||||
|
*/
|
||||||
|
class ObjectThatHasToStringMethod {
|
||||||
|
|
||||||
|
public function __toString() {
|
||||||
|
return 'some value';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,11 +11,11 @@ use PHPUnit\Framework\TestCase;
|
|||||||
*/
|
*/
|
||||||
class OldRequireTest extends TestCase {
|
class OldRequireTest extends TestCase {
|
||||||
|
|
||||||
protected function setUp() {
|
protected function setUp(): void {
|
||||||
rename('vendor/autoload.php', '__autoload');
|
rename('vendor/autoload.php', '__autoload');
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function tearDown() {
|
protected function tearDown(): void {
|
||||||
rename('__autoload', 'vendor/autoload.php');
|
rename('__autoload', 'vendor/autoload.php');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,7 +23,6 @@ class OldRequireTest extends TestCase {
|
|||||||
* @runInSeparateProcess so that disabled autoloading has an effect
|
* @runInSeparateProcess so that disabled autoloading has an effect
|
||||||
*/
|
*/
|
||||||
public function testOldLibWithoutComposer() {
|
public function testOldLibWithoutComposer() {
|
||||||
|
|
||||||
file_put_contents('__eval.php', '<?php require "parsecsv.lib.php"; new \ParseCsv\Csv;');
|
file_put_contents('__eval.php', '<?php require "parsecsv.lib.php"; new \ParseCsv\Csv;');
|
||||||
exec("php __eval.php", $output, $return_var);
|
exec("php __eval.php", $output, $return_var);
|
||||||
unlink('__eval.php');
|
unlink('__eval.php');
|
||||||
@@ -35,7 +34,6 @@ class OldRequireTest extends TestCase {
|
|||||||
* @runInSeparateProcess so that disabled autoloading has an effect
|
* @runInSeparateProcess so that disabled autoloading has an effect
|
||||||
*/
|
*/
|
||||||
public function testOldLibWithOldClassName() {
|
public function testOldLibWithOldClassName() {
|
||||||
|
|
||||||
file_put_contents('__eval.php', '<?php require "parsecsv.lib.php"; new parseCSV;');
|
file_put_contents('__eval.php', '<?php require "parsecsv.lib.php"; new parseCSV;');
|
||||||
exec("php __eval.php", $output, $return_var);
|
exec("php __eval.php", $output, $return_var);
|
||||||
unlink('__eval.php');
|
unlink('__eval.php');
|
||||||
|
|||||||
@@ -14,8 +14,10 @@ class OutputTest extends TestCase {
|
|||||||
$csv = new Csv();
|
$csv = new Csv();
|
||||||
$data = [0 => ['a', 'b', 'c'], 1 => ['d', 'e', 'f']];
|
$data = [0 => ['a', 'b', 'c'], 1 => ['d', 'e', 'f']];
|
||||||
$fields = ['col1', 'col2', 'col3'];
|
$fields = ['col1', 'col2', 'col3'];
|
||||||
|
ob_start();
|
||||||
$output = $csv->output('test.csv', $data, $fields, ',');
|
$output = $csv->output('test.csv', $data, $fields, ',');
|
||||||
$expected = "col1,col2,col3\ra,b,c\rd,e,f\r";
|
$expected = "col1,col2,col3\ra,b,c\rd,e,f\r";
|
||||||
|
self::assertEquals($expected, ob_get_clean());
|
||||||
self::assertEquals($expected, $output);
|
self::assertEquals($expected, $output);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ namespace ParseCsv\tests\methods;
|
|||||||
|
|
||||||
use ParseCsv\Csv;
|
use ParseCsv\Csv;
|
||||||
use PHPUnit\Framework\TestCase;
|
use PHPUnit\Framework\TestCase;
|
||||||
|
use ReflectionClass;
|
||||||
|
|
||||||
class ParseTest extends TestCase {
|
class ParseTest extends TestCase {
|
||||||
|
|
||||||
@@ -18,7 +19,7 @@ class ParseTest extends TestCase {
|
|||||||
*
|
*
|
||||||
* @access public
|
* @access public
|
||||||
*/
|
*/
|
||||||
public function setUp() {
|
protected function setUp(): void {
|
||||||
$this->csv = new Csv();
|
$this->csv = new Csv();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -28,16 +29,19 @@ class ParseTest extends TestCase {
|
|||||||
$this->parseRepetitiveString('http://looks/like/an/url');
|
$this->parseRepetitiveString('http://looks/like/an/url');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $content
|
||||||
|
*/
|
||||||
private function parseRepetitiveString($content) {
|
private function parseRepetitiveString($content) {
|
||||||
$this->csv->delimiter = ';';
|
$this->csv->delimiter = ';';
|
||||||
$this->csv->heading = false;
|
$this->csv->heading = false;
|
||||||
$success = $this->csv->parse(str_repeat($content . ';', 500));
|
$success = $this->csv->parse(str_repeat($content . ';', 500));
|
||||||
$this->assertEquals(true, $success);
|
self::assertEquals(true, $success);
|
||||||
|
|
||||||
$row = array_pop($this->csv->data);
|
$row = array_pop($this->csv->data);
|
||||||
$expected_data = array_fill(0, 500, $content);
|
$expected_data = array_fill(0, 500, $content);
|
||||||
$expected_data [] = '';
|
$expected_data[] = '';
|
||||||
$this->assertEquals($expected_data, $row);
|
self::assertEquals($expected_data, $row);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -53,10 +57,13 @@ class ParseTest extends TestCase {
|
|||||||
$this->csv->output_encoding = 'UTF-8';
|
$this->csv->output_encoding = 'UTF-8';
|
||||||
|
|
||||||
$this->csv->auto($file);
|
$this->csv->auto($file);
|
||||||
$this->assertEquals($this->_get_magazines_data(), $this->csv->data);
|
self::assertEquals($this->_get_magazines_data(), $this->csv->data);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function autoDetectionProvider() {
|
/**
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
public static function autoDetectionProvider() {
|
||||||
return [
|
return [
|
||||||
'UTF8_no_BOM' => [__DIR__ . '/../example_files/UTF-8_sep_row_but_no_BOM.csv'],
|
'UTF8_no_BOM' => [__DIR__ . '/../example_files/UTF-8_sep_row_but_no_BOM.csv'],
|
||||||
'UTF8' => [__DIR__ . '/../example_files/UTF-8_with_BOM_and_sep_row.csv'],
|
'UTF8' => [__DIR__ . '/../example_files/UTF-8_with_BOM_and_sep_row.csv'],
|
||||||
@@ -66,20 +73,24 @@ class ParseTest extends TestCase {
|
|||||||
|
|
||||||
public function testSingleColumnWithZeros() {
|
public function testSingleColumnWithZeros() {
|
||||||
$this->csv->delimiter = null;
|
$this->csv->delimiter = null;
|
||||||
$this->csv->parse("URL\nhttp://www.amazon.com/ROX-Ice-Ball-Maker-Original/dp/B00MX59NMQ/ref=sr_1_1?ie=UTF8&qid=1435604374&sr=8-1&keywords=rox,+ice+molds");
|
$this->csv->parse(
|
||||||
|
"URL\nhttp://www.amazon.com/ROX-Ice-Ball-Maker-Original/dp/B00MX59NMQ/ref=sr_1_1?ie=UTF8&qid=1435604374&sr=8-1&keywords=rox,+ice+molds"
|
||||||
|
);
|
||||||
$row = array_pop($this->csv->data);
|
$row = array_pop($this->csv->data);
|
||||||
$expected_data = ['URL' => 'http://www.amazon.com/ROX-Ice-Ball-Maker-Original/dp/B00MX59NMQ/ref=sr_1_1?ie=UTF8&qid=1435604374&sr=8-1&keywords=rox,+ice+molds'];
|
$expected_data = ['URL' => 'http://www.amazon.com/ROX-Ice-Ball-Maker-Original/dp/B00MX59NMQ/ref=sr_1_1?ie=UTF8&qid=1435604374&sr=8-1&keywords=rox,+ice+molds'];
|
||||||
$this->assertEquals($expected_data, $row);
|
self::assertEquals($expected_data, $row);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testAllNumericalCsv() {
|
public function testAllNumericalCsv() {
|
||||||
$this->csv->heading = false;
|
$this->csv->heading = false;
|
||||||
$sInput = "86545235689\r\n34365587654\r\n13469874576";
|
$sInput = "86545235689\r\n34365587654\r\n13469874576";
|
||||||
$this->assertEquals(false, $this->csv->auto($sInput));
|
self::assertEquals(false, $this->csv->autoDetectionForDataString($sInput));
|
||||||
$this->assertEquals(null, $this->csv->delimiter);
|
self::assertEquals(null, $this->csv->delimiter);
|
||||||
$expected_data = explode("\r\n", $sInput);
|
$expected_data = explode("\r\n", $sInput);
|
||||||
$actual_data = array_map('reset', $this->csv->data);
|
$actual_data = array_map(function ($k) {
|
||||||
$this->assertEquals($expected_data, $actual_data);
|
return reset($k);
|
||||||
|
}, $this->csv->data);
|
||||||
|
self::assertEquals($expected_data, $actual_data);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testMissingEndingLineBreak() {
|
public function testMissingEndingLineBreak() {
|
||||||
@@ -88,14 +99,21 @@ class ParseTest extends TestCase {
|
|||||||
$sInput = "86545235689,a\r\n34365587654,b\r\n13469874576,\"c\r\nd\"";
|
$sInput = "86545235689,a\r\n34365587654,b\r\n13469874576,\"c\r\nd\"";
|
||||||
$expected_data = [86545235689, 34365587654, 13469874576];
|
$expected_data = [86545235689, 34365587654, 13469874576];
|
||||||
|
|
||||||
$actual_data = $this->invokeMethod($this->csv, 'parse_string', array($sInput));
|
$actual_data = $this->invokeMethod($this->csv, '_parse_string', [$sInput]);
|
||||||
$actual_column = array_map('reset', $actual_data);
|
$actual_column = array_map(function ($k) {
|
||||||
$this->assertEquals($expected_data, $actual_column);
|
return reset($k);
|
||||||
$this->assertEquals([
|
}, $actual_data);
|
||||||
'a',
|
self::assertEquals($expected_data, $actual_column);
|
||||||
'b',
|
self::assertEquals(
|
||||||
"c\r\nd",
|
[
|
||||||
], array_map('next', $actual_data));
|
'a',
|
||||||
|
'b',
|
||||||
|
"c\r\nd",
|
||||||
|
],
|
||||||
|
array_map(function ($el) {
|
||||||
|
return next($el);
|
||||||
|
}, $actual_data)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testSingleColumn() {
|
public function testSingleColumn() {
|
||||||
@@ -106,7 +124,16 @@ class ParseTest extends TestCase {
|
|||||||
['SMS' => '6606'],
|
['SMS' => '6606'],
|
||||||
['SMS' => '7777'],
|
['SMS' => '7777'],
|
||||||
];
|
];
|
||||||
$this->assertEquals($expected, $this->csv->data);
|
self::assertEquals($expected, $this->csv->data);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testSingleRow() {
|
||||||
|
$this->csv->auto(__DIR__ . '/../example_files/single_row.csv');
|
||||||
|
self::assertEquals([], $this->csv->data, 'Single row is detected as header');
|
||||||
|
$this->csv->heading = false;
|
||||||
|
$this->csv->auto(__DIR__ . '/../example_files/single_row.csv');
|
||||||
|
$expected = [['C1', 'C2', 'C3']];
|
||||||
|
self::assertEquals($expected, $this->csv->data);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testMatomoData() {
|
public function testMatomoData() {
|
||||||
@@ -115,18 +142,61 @@ class ParseTest extends TestCase {
|
|||||||
$this->csv->output_encoding = 'UTF-8';
|
$this->csv->output_encoding = 'UTF-8';
|
||||||
$this->csv->auto(__DIR__ . '/../example_files/Piwik_API_download.csv');
|
$this->csv->auto(__DIR__ . '/../example_files/Piwik_API_download.csv');
|
||||||
$aAction27 = array_column($this->csv->data, 'url (actionDetails 27)');
|
$aAction27 = array_column($this->csv->data, 'url (actionDetails 27)');
|
||||||
$this->assertEquals([
|
self::assertEquals(
|
||||||
'http://application/_Main/_GraphicMeanSTD_MDI/btnConfBandOptions',
|
[
|
||||||
'',
|
'http://application/_Main/_GraphicMeanSTD_MDI/btnConfBandOptions',
|
||||||
'',
|
'',
|
||||||
], $aAction27);
|
'',
|
||||||
|
],
|
||||||
|
$aAction27
|
||||||
|
);
|
||||||
|
|
||||||
$aCity = array_column($this->csv->data, 'city');
|
$aCity = array_column($this->csv->data, 'city');
|
||||||
$this->assertEquals([
|
self::assertEquals(
|
||||||
'São Paulo',
|
[
|
||||||
'Johannesburg',
|
'São Paulo',
|
||||||
'',
|
'Johannesburg',
|
||||||
], $aCity);
|
'',
|
||||||
|
],
|
||||||
|
$aCity
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests if we can handle BOMs in string data, in contrast to loading files.
|
||||||
|
*/
|
||||||
|
public function testStringWithLeadingBOM() {
|
||||||
|
$string_with_bom = strtr(
|
||||||
|
file_get_contents(__DIR__ . '/../example_files/UTF-8_with_BOM_and_sep_row.csv'),
|
||||||
|
["sep=;\n" => '']
|
||||||
|
);
|
||||||
|
|
||||||
|
// Is the BOM still there?
|
||||||
|
self::assertSame(0xEF, ord($string_with_bom));
|
||||||
|
|
||||||
|
$this->csv->output_encoding = 'UTF-8';
|
||||||
|
$this->csv->delimiter = ';';
|
||||||
|
self::assertTrue($this->csv->loadDataString($string_with_bom));
|
||||||
|
self::assertTrue($this->csv->parse($this->csv->file_data));
|
||||||
|
|
||||||
|
// This also tests if ::load_data removed the BOM from the data;
|
||||||
|
// otherwise the 'title' column would have 3 extra bytes.
|
||||||
|
$this->assertEquals(
|
||||||
|
[
|
||||||
|
'title',
|
||||||
|
'isbn',
|
||||||
|
'publishedAt',
|
||||||
|
],
|
||||||
|
array_keys(reset($this->csv->data)));
|
||||||
|
|
||||||
|
$titles = array_column($this->csv->data, 'title');
|
||||||
|
$this->assertEquals(
|
||||||
|
[
|
||||||
|
'Красивая кулинария',
|
||||||
|
'The Wine Connoisseurs',
|
||||||
|
'Weißwein',
|
||||||
|
],
|
||||||
|
$titles);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testWithMultipleNewlines() {
|
public function testWithMultipleNewlines() {
|
||||||
@@ -134,18 +204,20 @@ class ParseTest extends TestCase {
|
|||||||
$aElse9 = array_column($this->csv->data, 'else9');
|
$aElse9 = array_column($this->csv->data, 'else9');
|
||||||
|
|
||||||
/** @noinspection SpellCheckingInspection */
|
/** @noinspection SpellCheckingInspection */
|
||||||
$this->assertEquals([
|
$this->assertEquals(
|
||||||
'Abweichung',
|
[
|
||||||
'Abweichung',
|
'Abweichung',
|
||||||
'Abweichung',
|
'Abweichung',
|
||||||
'Alt',
|
'Abweichung',
|
||||||
'Fehlt',
|
'Alt',
|
||||||
'Neu',
|
'Fehlt',
|
||||||
'OK',
|
'Neu',
|
||||||
'Fehlt',
|
'OK',
|
||||||
'Fehlt',
|
'Fehlt',
|
||||||
'Fehlt',
|
'Fehlt',
|
||||||
], $aElse9);
|
'Fehlt',
|
||||||
|
],
|
||||||
|
$aElse9);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -163,7 +235,7 @@ class ParseTest extends TestCase {
|
|||||||
'price' => 'float',
|
'price' => 'float',
|
||||||
];
|
];
|
||||||
|
|
||||||
$this->assertEquals($expected, $this->csv->data_types);
|
self::assertEquals($expected, $this->csv->data_types);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -171,23 +243,34 @@ class ParseTest extends TestCase {
|
|||||||
*/
|
*/
|
||||||
public function testAutoDetectFileHasHeading() {
|
public function testAutoDetectFileHasHeading() {
|
||||||
$this->csv->auto(__DIR__ . '/fixtures/datatype.csv');
|
$this->csv->auto(__DIR__ . '/fixtures/datatype.csv');
|
||||||
$this->assertTrue($this->csv->autoDetectFileHasHeading());
|
self::assertTrue($this->csv->autoDetectFileHasHeading());
|
||||||
|
|
||||||
$this->csv->heading = false;
|
$this->csv->heading = false;
|
||||||
$this->csv->auto(__DIR__ . '/fixtures/datatype.csv');
|
$this->csv->auto(__DIR__ . '/fixtures/datatype.csv');
|
||||||
$this->assertTrue($this->csv->autoDetectFileHasHeading());
|
self::assertTrue($this->csv->autoDetectFileHasHeading());
|
||||||
|
|
||||||
$this->csv->heading = false;
|
$this->csv->heading = false;
|
||||||
$sInput = "86545235689\r\n34365587654\r\n13469874576";
|
$sInput = "86545235689\r\n34365587654\r\n13469874576";
|
||||||
$this->csv->auto($sInput);
|
$this->csv->autoDetectionForDataString($sInput);
|
||||||
$this->assertFalse($this->csv->autoDetectFileHasHeading());
|
self::assertFalse($this->csv->autoDetectFileHasHeading());
|
||||||
|
|
||||||
$this->csv->heading = true;
|
$this->csv->heading = true;
|
||||||
$sInput = "86545235689\r\n34365587654\r\n13469874576";
|
$sInput = "86545235689\r\n34365587654\r\n13469874576";
|
||||||
$this->csv->auto($sInput);
|
$this->csv->autoDetectionForDataString($sInput);
|
||||||
$this->assertFalse($this->csv->autoDetectFileHasHeading());
|
self::assertFalse($this->csv->autoDetectFileHasHeading());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @doesNotPerformAssertions
|
||||||
|
*/
|
||||||
|
public function testVeryLongNonExistingFile() {
|
||||||
|
$this->csv->parse(str_repeat('long_string', PHP_MAXPATHLEN));
|
||||||
|
$this->csv->auto(str_repeat('long_string', PHP_MAXPATHLEN));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
protected function _get_magazines_data() {
|
protected function _get_magazines_data() {
|
||||||
return [
|
return [
|
||||||
[
|
[
|
||||||
@@ -208,7 +291,10 @@ class ParseTest extends TestCase {
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
public function autoQuotesDataProvider() {
|
/**
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
public static function autoQuotesDataProvider(): array {
|
||||||
return array(
|
return array(
|
||||||
array('auto-double-enclosure.csv', '"'),
|
array('auto-double-enclosure.csv', '"'),
|
||||||
array('auto-single-enclosure.csv', "'"),
|
array('auto-single-enclosure.csv', "'"),
|
||||||
@@ -226,21 +312,21 @@ class ParseTest extends TestCase {
|
|||||||
public function testAutoQuotes($file, $enclosure) {
|
public function testAutoQuotes($file, $enclosure) {
|
||||||
$csv = new Csv();
|
$csv = new Csv();
|
||||||
$csv->auto(__DIR__ . '/fixtures/' . $file, true, null, null, $enclosure);
|
$csv->auto(__DIR__ . '/fixtures/' . $file, true, null, null, $enclosure);
|
||||||
$this->assertArrayHasKey('column1', $csv->data[0], 'Data parsed incorrectly with enclosure ' . $enclosure);
|
self::assertArrayHasKey('column1', $csv->data[0], 'Data parsed incorrectly with enclosure ' . $enclosure);
|
||||||
$this->assertEquals('value1', $csv->data[0]['column1'], 'Data parsed incorrectly with enclosure ' . $enclosure);
|
self::assertEquals('value1', $csv->data[0]['column1'], 'Data parsed incorrectly with enclosure ' . $enclosure);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Call protected/private method of a class.
|
* Call protected/private method of a class.
|
||||||
*
|
*
|
||||||
* @param object &$object Instantiated object that we will run method on.
|
* @param object $object Instantiated object that we will run method on.
|
||||||
* @param string $methodName Method name to call
|
* @param string $methodName Method name to call
|
||||||
* @param array $parameters Array of parameters to pass into method.
|
* @param array $parameters Array of parameters to pass into method.
|
||||||
*
|
*
|
||||||
* @return mixed Method return.
|
* @return mixed Method return.
|
||||||
*/
|
*/
|
||||||
private function invokeMethod(&$object, $methodName, array $parameters = array()) {
|
private function invokeMethod($object, $methodName, $parameters = []) {
|
||||||
$reflection = new \ReflectionClass(get_class($object));
|
$reflection = new ReflectionClass(get_class($object));
|
||||||
$method = $reflection->getMethod($methodName);
|
$method = $reflection->getMethod($methodName);
|
||||||
$method->setAccessible(true);
|
$method->setAccessible(true);
|
||||||
|
|
||||||
@@ -248,7 +334,7 @@ class ParseTest extends TestCase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public function testWaiverFieldSeparator() {
|
public function testWaiverFieldSeparator() {
|
||||||
$this->assertSame(false, $this->csv->auto(__DIR__ . '/../example_files/waiver_field_separator.csv'));
|
self::assertFalse($this->csv->auto(__DIR__ . '/../example_files/waiver_field_separator.csv'));
|
||||||
$expected = [
|
$expected = [
|
||||||
'liability waiver',
|
'liability waiver',
|
||||||
'release of liability form',
|
'release of liability form',
|
||||||
@@ -257,6 +343,19 @@ class ParseTest extends TestCase {
|
|||||||
'sample waiver form',
|
'sample waiver form',
|
||||||
];
|
];
|
||||||
$actual = array_column($this->csv->data, 'keyword');
|
$actual = array_column($this->csv->data, 'keyword');
|
||||||
$this->assertSame($expected, $actual);
|
self::assertSame($expected, $actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testEmptyInput() {
|
||||||
|
self::assertFalse($this->csv->parse(''));
|
||||||
|
self::assertFalse($this->csv->parse(null));
|
||||||
|
self::assertFalse($this->csv->parseFile(''));
|
||||||
|
self::assertFalse($this->csv->parseFile(null));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testParseFile() {
|
||||||
|
$data = $this->csv->parseFile(__DIR__ . '/fixtures/auto-double-enclosure.csv');
|
||||||
|
self::assertCount(2, $data);
|
||||||
|
self::assertEquals($data, $this->csv->data);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace ParseCsv\tests\methods;
|
namespace ParseCsv\tests\methods;
|
||||||
|
|
||||||
use ParseCsv\Csv;
|
use ParseCsv\Csv;
|
||||||
use PHPUnit\Framework\TestCase;
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
class SaveTest extends TestCase
|
class SaveTest extends TestCase {
|
||||||
{
|
|
||||||
|
|
||||||
/** @var Csv */
|
/** @var Csv */
|
||||||
private $csv;
|
private $csv;
|
||||||
@@ -13,9 +13,9 @@ class SaveTest extends TestCase
|
|||||||
private $temp_filename;
|
private $temp_filename;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Setup our test environment objects; will be called before each test.
|
* Set up our test environment objects; will be called before each test.
|
||||||
*/
|
*/
|
||||||
public function setUp() {
|
protected function setUp(): void {
|
||||||
$this->csv = new Csv();
|
$this->csv = new Csv();
|
||||||
$this->csv->auto(__DIR__ . '/../example_files/single_column.csv');
|
$this->csv->auto(__DIR__ . '/../example_files/single_column.csv');
|
||||||
|
|
||||||
@@ -51,11 +51,39 @@ class SaveTest extends TestCase
|
|||||||
|
|
||||||
public function testSaveWithNewHeader() {
|
public function testSaveWithNewHeader() {
|
||||||
$this->csv->linefeed = "\n";
|
$this->csv->linefeed = "\n";
|
||||||
$this->csv->titles = array("NewTitle");
|
$this->csv->titles = ["NewTitle"];
|
||||||
$expected = "NewTitle\n0444\n5555\n";
|
$expected = "NewTitle\n0444\n5555\n";
|
||||||
$this->saveAndCompare($expected);
|
$this->saveAndCompare($expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function testSaveWithDelimiterOfComma() {
|
||||||
|
$this->csv = new Csv();
|
||||||
|
$this->csv->heading = false;
|
||||||
|
$this->csv->delimiter = ",";
|
||||||
|
$this->csv->linefeed = "\n";
|
||||||
|
$this->csv->data = [
|
||||||
|
[
|
||||||
|
'3,21',
|
||||||
|
'Twitter',
|
||||||
|
'Monsieur',
|
||||||
|
'eat more vegan food',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'"9,72"',
|
||||||
|
'newsletter',
|
||||||
|
'Madame',
|
||||||
|
'"free travel"',
|
||||||
|
],
|
||||||
|
];
|
||||||
|
|
||||||
|
// Yep, these double quotes are what Excel and Open Office understand.
|
||||||
|
$expected =
|
||||||
|
'"3,21",Twitter,Monsieur,eat more vegan food' . "\n" .
|
||||||
|
'"""9,72""",newsletter,Madame,"""free travel"""' . "\n";
|
||||||
|
$actual = $this->csv->unparse();
|
||||||
|
self::assertSame($expected, $actual);
|
||||||
|
}
|
||||||
|
|
||||||
public function testSaveWithoutHeader() {
|
public function testSaveWithoutHeader() {
|
||||||
$this->csv->linefeed = "\n";
|
$this->csv->linefeed = "\n";
|
||||||
$this->csv->heading = false;
|
$this->csv->heading = false;
|
||||||
@@ -63,9 +91,9 @@ class SaveTest extends TestCase
|
|||||||
$this->saveAndCompare($expected);
|
$this->saveAndCompare($expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testAllQuotes() {
|
public function testEncloseAllWithQuotes() {
|
||||||
$this->csv->enclose_all = true;
|
$this->csv->enclose_all = true;
|
||||||
$expected = "\"SMS\"\r\"0444\"\r\"5555\"\r";
|
$expected = '"SMS"'."\r".'"0444"'."\r".'"5555"'."\r";
|
||||||
$this->saveAndCompare($expected);
|
$this->saveAndCompare($expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
71
tests/methods/StreamTest.php
Normal file
71
tests/methods/StreamTest.php
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace ParseCsv\tests\methods;
|
||||||
|
|
||||||
|
use ParseCsv\Csv;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Writes roughly 1 MB of data. This is useful because of a limit of 8 KB
|
||||||
|
* encountered with stream operations in certain PHP versions.
|
||||||
|
*/
|
||||||
|
class StreamTest extends TestCase {
|
||||||
|
|
||||||
|
protected function setUp(): void {
|
||||||
|
static $done;
|
||||||
|
if ($done) {
|
||||||
|
// Make sure we register the stream just once - or PHP will scream.
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
stream_wrapper_register("example", ExampleStream::class)
|
||||||
|
or die("Failed to register protocol");
|
||||||
|
$done = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testReadStream() {
|
||||||
|
$csv = new Csv();
|
||||||
|
|
||||||
|
// Write data to our stream:
|
||||||
|
$filename = 'example://tmp';
|
||||||
|
copy(__DIR__ . '/fixtures/datatype.csv', $filename);
|
||||||
|
$many_dots = str_repeat('.', 1000 * 1000) . ";;;;;\n";
|
||||||
|
file_put_contents($filename, $many_dots, FILE_APPEND);
|
||||||
|
|
||||||
|
self::assertSame(';', $csv->auto(file_get_contents($filename)));
|
||||||
|
self::assertCount(4, $csv->data);
|
||||||
|
self::assertCount(6, reset($csv->data));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testWriteStream() {
|
||||||
|
$csv = new Csv();
|
||||||
|
$csv->linefeed = "\n";
|
||||||
|
$many_dots = str_repeat('.', 1000 * 1000);
|
||||||
|
$csv->data = [
|
||||||
|
[
|
||||||
|
'Name' => 'Rudolf',
|
||||||
|
'Question' => 'Which color is his nose?',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'Name' => 'Sponge Bob',
|
||||||
|
'Question' => 'Which shape are his pants?',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'Name' => $many_dots,
|
||||||
|
'Question' => 'Can you count one million dots?',
|
||||||
|
],
|
||||||
|
];
|
||||||
|
|
||||||
|
// Just export the first column, but with a new name
|
||||||
|
$csv->titles = ['Name' => 'Character'];
|
||||||
|
|
||||||
|
// Write data to our stream:
|
||||||
|
$filename = 'example://data';
|
||||||
|
copy(__DIR__ . '/fixtures/datatype.csv', $filename);
|
||||||
|
|
||||||
|
self::assertSame(true, $csv->save($filename));
|
||||||
|
$expected = "Character\nRudolf\nSponge Bob\n";
|
||||||
|
$expected .= $many_dots . "\n";
|
||||||
|
self::assertSame($expected, file_get_contents($filename));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,13 +14,13 @@ class UnparseTest extends Testcase {
|
|||||||
/**
|
/**
|
||||||
* Setup our test environment objects; will be called before each test.
|
* Setup our test environment objects; will be called before each test.
|
||||||
*/
|
*/
|
||||||
public function setUp() {
|
protected function setUp(): void {
|
||||||
$this->csv = new Csv();
|
$this->csv = new Csv();
|
||||||
$this->csv->auto(__DIR__ . '/fixtures/auto-double-enclosure.csv');
|
$this->csv->auto(__DIR__ . '/fixtures/auto-double-enclosure.csv');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testUnparseWithParameters() {
|
public function testUnparseWithParameters() {
|
||||||
$fields = array('a' => 'AA', 'b' => 'BB');
|
$fields = ['a' => 'AA', 'b' => 'BB'];
|
||||||
$data = [['a' => 'value1', 'b' => 'value2']];
|
$data = [['a' => 'value1', 'b' => 'value2']];
|
||||||
$csv_object = new Csv();
|
$csv_object = new Csv();
|
||||||
$csv_string = $csv_object->unparse($data, $fields);
|
$csv_string = $csv_object->unparse($data, $fields);
|
||||||
@@ -43,39 +43,63 @@ class UnparseTest extends Testcase {
|
|||||||
$this->unparseAndCompare($expected);
|
$this->unparseAndCompare($expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @doesNotPerformAssertions
|
||||||
|
*/
|
||||||
public function testUnparseDefaultWithoutHeading() {
|
public function testUnparseDefaultWithoutHeading() {
|
||||||
$this->csv->heading = false;
|
$this->csv->heading = false;
|
||||||
$this->csv->auto(__DIR__ . '/fixtures/auto-double-enclosure.csv');
|
$this->csv->auto(__DIR__ . '/fixtures/auto-double-enclosure.csv');
|
||||||
$expected = "column1,column2\rvalue1,value2\rvalue3,value4\r";
|
$expected = "column1,column2\rvalue1,value2\rvalue3,value4\r";
|
||||||
$this->unparseAndCompare($expected);
|
$this->unparseAndCompare($expected);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testUnparseRenameFields() {
|
public function testUnparseRenameFields() {
|
||||||
$expected = "C1,C2\rvalue1,value2\rvalue3,value4\r";
|
$expected = "C1,C2\rvalue1,value2\rvalue3,value4\r";
|
||||||
$this->unparseAndCompare($expected, array("C1", "C2"));
|
$this->unparseAndCompare($expected, ["C1", "C2"]);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testReorderFields() {
|
public function testReorderFields() {
|
||||||
$expected = "column2,column1\rvalue2,value1\rvalue4,value3\r";
|
$expected = "column2,column1\rvalue2,value1\rvalue4,value3\r";
|
||||||
$this->unparseAndCompare($expected, array("column2", "column1"));
|
$this->unparseAndCompare($expected, ["column2", "column1"]);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testSubsetFields() {
|
public function testSubsetFields() {
|
||||||
$expected = "column1\rvalue1\rvalue3\r";
|
$expected = "column1\rvalue1\rvalue3\r";
|
||||||
$this->unparseAndCompare($expected, array("column1"));
|
$this->unparseAndCompare($expected, ["column1"]);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testReorderAndRenameFields() {
|
public function testReorderAndRenameFields() {
|
||||||
$fields = array(
|
$fields = ['column2' => 'C2', 'column1' => 'C1'];
|
||||||
'column2' => 'C2',
|
|
||||||
'column1' => 'C1',
|
|
||||||
);
|
|
||||||
$expected = "C2,C1\rvalue2,value1\rvalue4,value3\r";
|
$expected = "C2,C1\rvalue2,value1\rvalue4,value3\r";
|
||||||
$this->unparseAndCompare($expected, $fields);
|
$this->unparseAndCompare($expected, $fields);
|
||||||
}
|
}
|
||||||
|
|
||||||
private function unparseAndCompare($expected, $fields = array()) {
|
public function testUnparseDefaultFirstRowMissing() {
|
||||||
|
unset($this->csv->data[0]);
|
||||||
|
$expected = "column1,column2\rvalue3,value4\r";
|
||||||
|
$this->unparseAndCompare($expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testUnparseDefaultWithoutData() {
|
||||||
|
unset($this->csv->data[0]);
|
||||||
|
unset($this->csv->data[1]);
|
||||||
|
$expected = "column1,column2\r";
|
||||||
|
$this->unparseAndCompare($expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testObjectCells() {
|
||||||
|
$this->csv->data = [
|
||||||
|
[
|
||||||
|
'column1' => new ObjectThatHasToStringMethod(),
|
||||||
|
'column2' => 'boring',
|
||||||
|
],
|
||||||
|
];
|
||||||
|
$this->csv->linefeed = "\n";
|
||||||
|
$expected = "column1,column2\nsome value,boring\n";
|
||||||
|
$this->unparseAndCompare($expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function unparseAndCompare($expected, $fields = []) {
|
||||||
$str = $this->csv->unparse($this->csv->data, $fields);
|
$str = $this->csv->unparse($this->csv->data, $fields);
|
||||||
$this->assertEquals($expected, $str);
|
$this->assertEquals($expected, $str);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ class BaseClass extends TestCase {
|
|||||||
* CSV
|
* CSV
|
||||||
* The parseCSV object
|
* The parseCSV object
|
||||||
*
|
*
|
||||||
* @access protected
|
|
||||||
* @var Csv
|
* @var Csv
|
||||||
*/
|
*/
|
||||||
protected $csv;
|
protected $csv;
|
||||||
@@ -19,10 +18,8 @@ class BaseClass extends TestCase {
|
|||||||
/**
|
/**
|
||||||
* Setup
|
* Setup
|
||||||
* Setup our test environment objects
|
* Setup our test environment objects
|
||||||
*
|
|
||||||
* @access public
|
|
||||||
*/
|
*/
|
||||||
public function setUp() {
|
protected function setUp(): void {
|
||||||
$this->csv = new Csv();
|
$this->csv = new Csv();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -21,21 +21,93 @@ class ConditionsTest extends BaseClass {
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testRating() {
|
public function testRatingEquals() {
|
||||||
$this->csv->conditions = 'rating < 3';
|
$rating_of_3 = [
|
||||||
$this->_compareWithExpected([
|
'The Last Templar',
|
||||||
|
'The Broker (Paperback)',
|
||||||
|
'Without Blood (Paperback)',
|
||||||
|
];
|
||||||
|
$this->csv->conditions = 'rating = 3';
|
||||||
|
$this->_compareWithExpected($rating_of_3);
|
||||||
|
$this->csv->conditions = 'rating is 3';
|
||||||
|
$this->_compareWithExpected($rating_of_3);
|
||||||
|
$this->csv->conditions = 'rating equals 3';
|
||||||
|
$this->_compareWithExpected($rating_of_3);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testRatingNotEquals() {
|
||||||
|
$rating_not_4 = [
|
||||||
'The Killing Kind',
|
'The Killing Kind',
|
||||||
'The Third Secret',
|
'The Third Secret',
|
||||||
]);
|
'The Last Templar',
|
||||||
|
'The Traveller',
|
||||||
|
'Prey',
|
||||||
|
'The Broker (Paperback)',
|
||||||
|
'Without Blood (Paperback)',
|
||||||
|
'State of Fear (Paperback)',
|
||||||
|
'Digital Fortress : A Thriller (Mass Market Paperback)',
|
||||||
|
'Angels & Demons (Mass Market Paperback)',
|
||||||
|
];
|
||||||
|
// $this->csv->conditions = 'rating != 4';
|
||||||
|
// $this->_compareWithExpected($rating_not_4);
|
||||||
|
$this->csv->conditions = 'rating is not 4';
|
||||||
|
$this->_compareWithExpected($rating_not_4);
|
||||||
|
// $this->csv->conditions = 'rating does not contain 4';
|
||||||
|
// $this->_compareWithExpected($rating_not_4);
|
||||||
|
}
|
||||||
|
|
||||||
$this->csv->conditions = 'rating >= 5';
|
public function testRatingLessThan() {
|
||||||
$this->_compareWithExpected([
|
$less_than_1 = [
|
||||||
|
'The Killing Kind',
|
||||||
|
'The Third Secret',
|
||||||
|
];
|
||||||
|
$this->csv->conditions = 'rating < 1';
|
||||||
|
$this->_compareWithExpected($less_than_1);
|
||||||
|
$this->csv->conditions = 'rating is less than 1';
|
||||||
|
$this->_compareWithExpected($less_than_1);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testRatingLessOrEquals() {
|
||||||
|
$less_or_equals_1 = [
|
||||||
|
'The Killing Kind',
|
||||||
|
'The Third Secret',
|
||||||
|
];
|
||||||
|
$this->csv->conditions = 'rating <= 1';
|
||||||
|
$this->_compareWithExpected($less_or_equals_1);
|
||||||
|
$this->csv->conditions = 'rating is less than or equals 1';
|
||||||
|
$this->_compareWithExpected($less_or_equals_1);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testRatingGreaterThan() {
|
||||||
|
$greater_4 = [
|
||||||
'The Traveller',
|
'The Traveller',
|
||||||
'Prey',
|
'Prey',
|
||||||
'State of Fear (Paperback)',
|
'State of Fear (Paperback)',
|
||||||
'Digital Fortress : A Thriller (Mass Market Paperback)',
|
'Digital Fortress : A Thriller (Mass Market Paperback)',
|
||||||
'Angels & Demons (Mass Market Paperback)',
|
'Angels & Demons (Mass Market Paperback)',
|
||||||
]);
|
];
|
||||||
|
$this->csv->conditions = 'rating > 4';
|
||||||
|
$this->_compareWithExpected($greater_4);
|
||||||
|
$this->csv->conditions = 'rating is greater than 4';
|
||||||
|
$this->_compareWithExpected($greater_4);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testRatingGreaterOrEquals() {
|
||||||
|
$greater_or_equal_4 = [
|
||||||
|
'The Traveller',
|
||||||
|
'Crisis Four',
|
||||||
|
'Prey',
|
||||||
|
'State of Fear (Paperback)',
|
||||||
|
'The Rule of Four (Paperback)',
|
||||||
|
'Deception Point (Paperback)',
|
||||||
|
'Digital Fortress : A Thriller (Mass Market Paperback)',
|
||||||
|
'Angels & Demons (Mass Market Paperback)',
|
||||||
|
'The Da Vinci Code (Hardcover)',
|
||||||
|
];
|
||||||
|
$this->csv->conditions = 'rating >= 4';
|
||||||
|
$this->_compareWithExpected($greater_or_equal_4);
|
||||||
|
$this->csv->conditions = 'rating is greater than or equals 4';
|
||||||
|
$this->_compareWithExpected($greater_or_equal_4);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testTitleContainsSecretOrCode() {
|
public function testTitleContainsSecretOrCode() {
|
||||||
|
|||||||
@@ -16,152 +16,135 @@ class DefaultValuesPropertiesTest extends TestCase {
|
|||||||
*/
|
*/
|
||||||
protected $csv = null;
|
protected $csv = null;
|
||||||
|
|
||||||
/**
|
protected function setUp(): void {
|
||||||
* Setup
|
|
||||||
* Setup our test environment objects
|
|
||||||
*
|
|
||||||
* @access public
|
|
||||||
*/
|
|
||||||
public function setUp() {
|
|
||||||
//setup parse CSV
|
|
||||||
$this->csv = new Csv();
|
$this->csv = new Csv();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Tear down
|
|
||||||
* Tear down our test environment objects
|
|
||||||
*
|
|
||||||
* @access public
|
|
||||||
*/
|
|
||||||
public function tearDown() {
|
|
||||||
$this->csv = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function test_heading_default() {
|
public function test_heading_default() {
|
||||||
$this->assertTrue(is_bool($this->csv->heading));
|
self::assertTrue(is_bool($this->csv->heading));
|
||||||
$this->assertTrue($this->csv->heading);
|
self::assertTrue($this->csv->heading);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_fields_default() {
|
public function test_fields_default() {
|
||||||
$this->assertTrue(is_array($this->csv->fields));
|
self::assertTrue(is_array($this->csv->fields));
|
||||||
$this->assertCount(0, $this->csv->fields);
|
self::assertCount(0, $this->csv->fields);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_sort_by_default() {
|
public function test_sort_by_default() {
|
||||||
$this->assertNull($this->csv->sort_by);
|
self::assertNull($this->csv->sort_by);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_sort_reverse_default() {
|
public function test_sort_reverse_default() {
|
||||||
$this->assertTrue(is_bool($this->csv->sort_reverse));
|
self::assertTrue(is_bool($this->csv->sort_reverse));
|
||||||
$this->assertFalse($this->csv->sort_reverse);
|
self::assertFalse($this->csv->sort_reverse);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_sort_type_default() {
|
public function test_sort_type_default() {
|
||||||
$this->assertEquals('regular', $this->csv->sort_type);
|
self::assertEquals('regular', $this->csv->sort_type);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_delimiter_default() {
|
public function test_delimiter_default() {
|
||||||
$this->assertTrue(is_string($this->csv->delimiter));
|
self::assertTrue(is_string($this->csv->delimiter));
|
||||||
$this->assertEquals(',', $this->csv->delimiter);
|
self::assertEquals(',', $this->csv->delimiter);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_enclosure_default() {
|
public function test_enclosure_default() {
|
||||||
$this->assertTrue(is_string($this->csv->enclosure));
|
self::assertTrue(is_string($this->csv->enclosure));
|
||||||
$this->assertEquals('"', $this->csv->enclosure);
|
self::assertEquals('"', $this->csv->enclosure);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_enclose_all_default() {
|
public function test_enclose_all_default() {
|
||||||
$this->assertTrue(is_bool($this->csv->enclose_all));
|
self::assertTrue(is_bool($this->csv->enclose_all));
|
||||||
$this->assertFalse($this->csv->enclose_all);
|
self::assertFalse($this->csv->enclose_all);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_conditions_default() {
|
public function test_conditions_default() {
|
||||||
$this->assertNull($this->csv->conditions);
|
self::assertNull($this->csv->conditions);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_offset_default() {
|
public function test_offset_default() {
|
||||||
$this->assertNull($this->csv->offset);
|
self::assertNull($this->csv->offset);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_limit_default() {
|
public function test_limit_default() {
|
||||||
$this->assertNull($this->csv->limit);
|
self::assertNull($this->csv->limit);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_auto_depth_default() {
|
public function test_auto_depth_default() {
|
||||||
$this->assertTrue(is_numeric($this->csv->auto_depth));
|
self::assertTrue(is_numeric($this->csv->auto_depth));
|
||||||
$this->assertEquals(15, $this->csv->auto_depth);
|
self::assertEquals(15, $this->csv->auto_depth);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_auto_non_chars_default() {
|
public function test_auto_non_chars_default() {
|
||||||
$this->assertTrue(is_string($this->csv->auto_non_chars));
|
self::assertTrue(is_string($this->csv->auto_non_chars));
|
||||||
$this->assertEquals("a-zA-Z0-9\n\r", $this->csv->auto_non_chars);
|
self::assertEquals("a-zA-Z0-9\n\r", $this->csv->auto_non_chars);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_auto_preferred_default() {
|
public function test_auto_preferred_default() {
|
||||||
$this->assertTrue(is_string($this->csv->auto_preferred));
|
self::assertTrue(is_string($this->csv->auto_preferred));
|
||||||
$this->assertEquals(",;\t.:|", $this->csv->auto_preferred);
|
self::assertEquals(",;\t.:|", $this->csv->auto_preferred);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_convert_encoding_default() {
|
public function test_convert_encoding_default() {
|
||||||
$this->assertTrue(is_bool($this->csv->convert_encoding));
|
self::assertTrue(is_bool($this->csv->convert_encoding));
|
||||||
$this->assertFalse($this->csv->convert_encoding);
|
self::assertFalse($this->csv->convert_encoding);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_input_encoding_default() {
|
public function test_input_encoding_default() {
|
||||||
$this->assertTrue(is_string($this->csv->input_encoding));
|
self::assertTrue(is_string($this->csv->input_encoding));
|
||||||
$this->assertEquals('ISO-8859-1', $this->csv->input_encoding);
|
self::assertEquals('ISO-8859-1', $this->csv->input_encoding);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_output_encoding_default() {
|
public function test_output_encoding_default() {
|
||||||
$this->assertTrue(is_string($this->csv->output_encoding));
|
self::assertTrue(is_string($this->csv->output_encoding));
|
||||||
$this->assertEquals('ISO-8859-1', $this->csv->output_encoding);
|
self::assertEquals('ISO-8859-1', $this->csv->output_encoding);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_linefeed_default() {
|
public function test_linefeed_default() {
|
||||||
$this->assertTrue(is_string($this->csv->linefeed));
|
self::assertTrue(is_string($this->csv->linefeed));
|
||||||
$this->assertEquals("\r", $this->csv->linefeed);
|
self::assertEquals("\r", $this->csv->linefeed);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_output_delimiter_default() {
|
public function test_output_delimiter_default() {
|
||||||
$this->assertTrue(is_string($this->csv->output_delimiter));
|
self::assertTrue(is_string($this->csv->output_delimiter));
|
||||||
$this->assertEquals(',', $this->csv->output_delimiter);
|
self::assertEquals(',', $this->csv->output_delimiter);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_output_filename_default() {
|
public function test_output_filename_default() {
|
||||||
$this->assertTrue(is_string($this->csv->output_filename));
|
self::assertTrue(is_string($this->csv->output_filename));
|
||||||
$this->assertEquals('data.csv', $this->csv->output_filename);
|
self::assertEquals('data.csv', $this->csv->output_filename);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_keep_file_data_default() {
|
public function test_keep_file_data_default() {
|
||||||
$this->assertTrue(is_bool($this->csv->keep_file_data));
|
self::assertTrue(is_bool($this->csv->keep_file_data));
|
||||||
$this->assertFalse($this->csv->keep_file_data);
|
self::assertFalse($this->csv->keep_file_data);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_file_default() {
|
public function test_file_default() {
|
||||||
$this->assertNull($this->csv->file);
|
self::assertNull($this->csv->file);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_file_data_default() {
|
public function test_file_data_default() {
|
||||||
$this->assertNull($this->csv->file_data);
|
self::assertNull($this->csv->file_data);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_error_default() {
|
public function test_error_default() {
|
||||||
$this->assertTrue(is_numeric($this->csv->error));
|
self::assertTrue(is_numeric($this->csv->error));
|
||||||
$this->assertEquals(0, $this->csv->error);
|
self::assertEquals(0, $this->csv->error);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_error_info_default() {
|
public function test_error_info_default() {
|
||||||
$this->assertTrue(is_array($this->csv->error_info));
|
self::assertTrue(is_array($this->csv->error_info));
|
||||||
$this->assertCount(0, $this->csv->error_info);
|
self::assertCount(0, $this->csv->error_info);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_titles_default() {
|
public function test_titles_default() {
|
||||||
$this->assertTrue(is_array($this->csv->titles));
|
self::assertTrue(is_array($this->csv->titles));
|
||||||
$this->assertCount(0, $this->csv->titles);
|
self::assertCount(0, $this->csv->titles);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_data_default() {
|
public function test_data_default() {
|
||||||
$this->assertTrue(is_array($this->csv->data));
|
self::assertTrue(is_array($this->csv->data));
|
||||||
$this->assertCount(0, $this->csv->data);
|
self::assertCount(0, $this->csv->data);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ namespace ParseCsv\tests\properties;
|
|||||||
* Tests related to the $offset property
|
* Tests related to the $offset property
|
||||||
*/
|
*/
|
||||||
class OffsetTest extends BaseClass {
|
class OffsetTest extends BaseClass {
|
||||||
|
|
||||||
public function testOffsetOfOne() {
|
public function testOffsetOfOne() {
|
||||||
$this->csv->offset = 1;
|
$this->csv->offset = 1;
|
||||||
$this->csv->auto(__DIR__ . '/../methods/fixtures/datatype.csv');
|
$this->csv->auto(__DIR__ . '/../methods/fixtures/datatype.csv');
|
||||||
@@ -24,7 +25,7 @@ class OffsetTest extends BaseClass {
|
|||||||
$this->assertEquals($expected, $actual);
|
$this->assertEquals($expected, $actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function numberRangeZeroToFourProvider() {
|
public static function numberRangeZeroToFourProvider() {
|
||||||
return array_map(function ($number) {
|
return array_map(function ($number) {
|
||||||
return [$number];
|
return [$number];
|
||||||
}, range(0, 4));
|
}, range(0, 4));
|
||||||
@@ -33,7 +34,7 @@ class OffsetTest extends BaseClass {
|
|||||||
/**
|
/**
|
||||||
* @dataProvider numberRangeZeroToFourProvider
|
* @dataProvider numberRangeZeroToFourProvider
|
||||||
*
|
*
|
||||||
* @param integer $offset
|
* @param int $offset
|
||||||
*/
|
*/
|
||||||
public function testOffsetOfOneNoHeader($offset) {
|
public function testOffsetOfOneNoHeader($offset) {
|
||||||
$this->csv->offset = $offset;
|
$this->csv->offset = $offset;
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ class PublicPropertiesTest extends TestCase {
|
|||||||
*
|
*
|
||||||
* @access public
|
* @access public
|
||||||
*/
|
*/
|
||||||
public function setUp() {
|
protected function setUp(): void {
|
||||||
//setup parse CSV
|
//setup parse CSV
|
||||||
$this->csv = new Csv();
|
$this->csv = new Csv();
|
||||||
|
|
||||||
@@ -58,7 +58,7 @@ class PublicPropertiesTest extends TestCase {
|
|||||||
*
|
*
|
||||||
* @access public
|
* @access public
|
||||||
*/
|
*/
|
||||||
public function tearDown() {
|
protected function tearDown(): void {
|
||||||
$this->csv = null;
|
$this->csv = null;
|
||||||
$this->reflection = null;
|
$this->reflection = null;
|
||||||
$this->properties = null;
|
$this->properties = null;
|
||||||
@@ -147,25 +147,25 @@ class PublicPropertiesTest extends TestCase {
|
|||||||
$this->assertCount($counter, $this->properties);
|
$this->assertCount($counter, $this->properties);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testDefaultSortTypeIsRegular(){
|
public function testDefaultSortTypeIsRegular() {
|
||||||
$this->assertEquals(SortEnum::SORT_TYPE_REGULAR, $this->csv->sort_type);
|
$this->assertEquals(SortEnum::SORT_TYPE_REGULAR, $this->csv->sort_type);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testSetSortType(){
|
public function testSetSortType() {
|
||||||
$this->csv->sort_type = 'numeric';
|
$this->csv->sort_type = 'numeric';
|
||||||
$this->assertEquals(SortEnum::SORT_TYPE_NUMERIC, $this->csv->sort_type);
|
$this->assertEquals(SortEnum::SORT_TYPE_NUMERIC, $this->csv->sort_type);
|
||||||
|
|
||||||
$this->csv->sort_type = 'string';
|
$this->csv->sort_type = 'string';
|
||||||
$this->assertEquals(SortEnum::SORT_TYPE_STRING, $this->csv->sort_type);
|
$this->assertEquals(SortEnum::SORT_TYPE_STRING, $this->csv->sort_type);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testGetSorting(){
|
public function testGetSorting() {
|
||||||
$this->csv->sort_type = 'numeric';
|
$this->csv->sort_type = 'numeric';
|
||||||
$sorting = SortEnum::getSorting($this->csv->sort_type);
|
$sorting = SortEnum::getSorting($this->csv->sort_type);
|
||||||
$this->assertEquals(SORT_NUMERIC, $sorting);
|
$this->assertEquals(SORT_NUMERIC, $sorting);
|
||||||
|
|
||||||
$this->csv->sort_type = 'string';
|
$this->csv->sort_type = 'string';
|
||||||
$sorting = SortEnum::getSorting($this->csv->sort_type);
|
$sorting = SortEnum::getSorting($this->csv->sort_type);
|
||||||
$this->assertEquals(SORT_STRING, $sorting);
|
$this->assertEquals(SORT_STRING, $sorting);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,26 +7,48 @@ class SortByTest extends BaseClass {
|
|||||||
public function testSortByRating() {
|
public function testSortByRating() {
|
||||||
$this->csv->sort_by = 'rating';
|
$this->csv->sort_by = 'rating';
|
||||||
$this->csv->conditions = 'title does not contain Blood';
|
$this->csv->conditions = 'title does not contain Blood';
|
||||||
$this->_compareWithExpected([
|
if (!preg_match('/^8\.2\./', phpversion()) && !preg_match('/^8\.3\./', phpversion()))
|
||||||
// Rating 0
|
$this->_compareWithExpected([
|
||||||
'The Killing Kind',
|
// Rating 0
|
||||||
'The Third Secret',
|
'The Killing Kind',
|
||||||
|
'The Third Secret',
|
||||||
|
|
||||||
// Rating 3
|
// Rating 3
|
||||||
'The Last Templar',
|
'The Last Templar',
|
||||||
'The Broker (Paperback)',
|
'The Broker (Paperback)',
|
||||||
|
|
||||||
// Rating 4
|
// Rating 4
|
||||||
'Deception Point (Paperback)',
|
'Deception Point (Paperback)',
|
||||||
'The Rule of Four (Paperback)',
|
'The Rule of Four (Paperback)',
|
||||||
'The Da Vinci Code (Hardcover)',
|
'The Da Vinci Code (Hardcover)',
|
||||||
|
|
||||||
// Rating 5
|
// Rating 5
|
||||||
'State of Fear (Paperback)',
|
'State of Fear (Paperback)',
|
||||||
'Prey',
|
'Prey',
|
||||||
'Digital Fortress : A Thriller (Mass Market Paperback)',
|
'Digital Fortress : A Thriller (Mass Market Paperback)',
|
||||||
'Angels & Demons (Mass Market Paperback)',
|
'Angels & Demons (Mass Market Paperback)',
|
||||||
]);
|
]);
|
||||||
|
else
|
||||||
|
$this->_compareWithExpected([
|
||||||
|
// Rating 0
|
||||||
|
'The Killing Kind',
|
||||||
|
'The Third Secret',
|
||||||
|
|
||||||
|
// Rating 3
|
||||||
|
'The Last Templar',
|
||||||
|
'The Broker (Paperback)',
|
||||||
|
|
||||||
|
// Rating 4
|
||||||
|
'Deception Point (Paperback)',
|
||||||
|
'The Rule of Four (Paperback)',
|
||||||
|
'The Da Vinci Code (Hardcover)',
|
||||||
|
|
||||||
|
// Rating 5
|
||||||
|
'Angels & Demons (Mass Market Paperback)',
|
||||||
|
'State of Fear (Paperback)',
|
||||||
|
'Prey',
|
||||||
|
'Digital Fortress : A Thriller (Mass Market Paperback)',
|
||||||
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testReverseSortByRating() {
|
public function testReverseSortByRating() {
|
||||||
|
|||||||
18
tests/rector.php
Normal file
18
tests/rector.php
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
use Rector\Config\RectorConfig;
|
||||||
|
use Rector\PHPUnit\AnnotationsToAttributes\Rector\ClassMethod\DataProviderAnnotationToAttributeRector;
|
||||||
|
use Rector\PHPUnit\AnnotationsToAttributes\Rector\ClassMethod\DependsAnnotationWithValueToAttributeRector;
|
||||||
|
use Rector\PHPUnit\CodeQuality\Rector\Class_\AddCoversClassAttributeRector;
|
||||||
|
use Rector\PHPUnit\PHPUnit60\Rector\ClassMethod\AddDoesNotPerformAssertionToNonAssertingTestRector;
|
||||||
|
|
||||||
|
return static function(RectorConfig $rectorConfig): void {
|
||||||
|
if (class_exists(AddCoversClassAttributeRector::class)) {
|
||||||
|
$rectorConfig->rule(AddCoversClassAttributeRector::class);
|
||||||
|
}
|
||||||
|
$rectorConfig->rule(DataProviderAnnotationToAttributeRector::class);
|
||||||
|
$rectorConfig->rule(AddDoesNotPerformAssertionToNonAssertingTestRector::class);
|
||||||
|
$rectorConfig->rule(DependsAnnotationWithValueToAttributeRector::class);
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user