Skip to content

Commit

Permalink
Exclude heading row when limiting imported rows
Browse files Browse the repository at this point in the history
  • Loading branch information
jivanf committed Oct 13, 2024
1 parent e848f23 commit 453803b
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/Factories/ReaderFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Maatwebsite\Excel\Concerns\MapsCsvSettings;
use Maatwebsite\Excel\Concerns\WithCustomCsvSettings;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithLimit;
use Maatwebsite\Excel\Concerns\WithReadFilter;
use Maatwebsite\Excel\Concerns\WithStartRow;
Expand Down Expand Up @@ -61,8 +62,14 @@ public static function make($import, TemporaryFile $file, string $readerType = n
if ($import instanceof WithReadFilter) {
$reader->setReadFilter($import->readFilter());
} elseif ($import instanceof WithLimit) {
$startRow = match (true) {
$import instanceof WithStartRow => $import->startRow(),
$import instanceof WithHeadingRow => 2,
default => 1,
};

$reader->setReadFilter(new LimitFilter(
$import instanceof WithStartRow ? $import->startRow() : 1,
$startRow,
$import->limit()
));
}
Expand Down
27 changes: 27 additions & 0 deletions tests/Concerns/WithLimitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithLimit;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
Expand Down Expand Up @@ -104,6 +105,32 @@ public function limit(): int
$import->import('import-users.xlsx');
}

public function test_can_import_with_heading_row()
{
$import = new class implements ToArray, WithLimit, WithHeadingRow
{
use Importable;

/**
* @param array $array
*/
public function array(array $array)
{
Assert::assertCount(1, $array);
}

/**
* @return int
*/
public function limit(): int
{
return 1;
}
};

$import->import('import-users-with-headings.xlsx');
}

public function test_can_set_limit_bigger_than_row_size()
{
$import = new class implements ToArray, WithLimit
Expand Down

0 comments on commit 453803b

Please sign in to comment.