Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cast empty headers to int #3646

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ All notable changes to this project will be documented in this file.

### Changed
- Support `WithValidation` concern to allow validations with `Excel::toArray()` and `Excel::toCollection()`
- Cast empty headings to indexed integer

### Fixed

Expand Down
4 changes: 4 additions & 0 deletions src/Imports/HeadingRowFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,10 @@ protected static function callFormatter($value, $key=null)
return $formatter($value, $key);
}

if (empty($value)) {
return $key;
}

if (static::$formatter === self::FORMATTER_SLUG) {
return Str::slug($value, '_');
}
Expand Down
30 changes: 30 additions & 0 deletions tests/Concerns/WithHeadingRowTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
namespace Maatwebsite\Excel\Tests\Concerns;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
Expand Down Expand Up @@ -180,4 +182,32 @@ public function model(array $row): Model
$import->import('import-empty-users-with-headings.xlsx');
$this->assertEmpty(User::all());
}

/**
* @test
*/
public function can_cast_empty_headers_to_indexed_int()
{
$import = new class() implements ToCollection, WithHeadingRow
{
use Importable;

public $called = false;

public function collection(Collection $collection)
{
$this->called = true;

Assert::assertEquals([
0 => 0,
1 => 'email',
2 => 'status',
3 => 3,
], $collection->first()->keys()->toArray());
}
};

$import->import('import-users-with-mixed-headings.xlsx');
$this->assertTrue($import->called);
}
}
3 changes: 2 additions & 1 deletion tests/Data/Disks/Local/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,5 @@
!csv-with-html-tags.csv
!import-external-reference.xls
!csv-with-comma.csv
!import-users-with-grouped-headers.xlsx
!import-users-with-grouped-headers.xlsx
!import-users-with-mixed-headings.xlsx
Binary file not shown.