repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/ExcelServiceProviderTest.php | tests/ExcelServiceProviderTest.php | <?php
namespace Maatwebsite\Excel\Tests;
use Composer\InstalledVersions;
use Composer\Semver\VersionParser;
use Illuminate\Contracts\Console\Kernel;
use Maatwebsite\Excel\Cache\MemoryCache;
use Maatwebsite\Excel\Cache\MemoryCacheDeprecated;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Tests\Data\Stubs\CustomTransactionHandler;
use Maatwebsite\Excel\Transactions\TransactionManager;
use PhpOffice\PhpSpreadsheet\Settings;
class ExcelServiceProviderTest extends TestCase
{
public function test_custom_transaction_handler_is_bound()
{
$this->app->make(TransactionManager::class)->extend('handler', function () {
return new CustomTransactionHandler;
});
$this->assertInstanceOf(CustomTransactionHandler::class, $this->app->make(TransactionManager::class)->driver('handler'));
}
public function test_is_bound()
{
$this->assertTrue($this->app->bound('excel'));
}
public function test_has_aliased()
{
$this->assertTrue($this->app->isAlias(Excel::class));
$this->assertEquals('excel', $this->app->getAlias(Excel::class));
}
public function test_registers_console_commands()
{
/** @var Kernel $kernel */
$kernel = $this->app->make(Kernel::class);
$commands = $kernel->all();
$this->assertArrayHasKey('make:export', $commands);
$this->assertArrayHasKey('make:import', $commands);
}
public function test_sets_php_spreadsheet_settings()
{
$driver = config('excel.cache.driver');
$this->assertEquals('memory', $driver);
if (InstalledVersions::satisfies(new VersionParser, 'psr/simple-cache', '^3.0')) {
$this->assertInstanceOf(
MemoryCache::class,
Settings::getCache()
);
} else {
$this->assertInstanceOf(
MemoryCacheDeprecated::class,
Settings::getCache()
);
}
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/InteractsWithQueueTest.php | tests/InteractsWithQueueTest.php | <?php
namespace Maatwebsite\Excel\Tests;
use Illuminate\Queue\InteractsWithQueue;
use Maatwebsite\Excel\Jobs\AppendDataToSheet;
use Maatwebsite\Excel\Jobs\AppendQueryToSheet;
use Maatwebsite\Excel\Jobs\AppendViewToSheet;
use Maatwebsite\Excel\Jobs\QueueExport;
use Maatwebsite\Excel\Jobs\ReadChunk;
class InteractsWithQueueTest extends TestCase
{
/**
* Setup the test environment.
*/
protected function setUp(): void
{
parent::setUp();
}
public function test_read_chunk_job_can_interact_with_queue()
{
$this->assertContains(InteractsWithQueue::class, class_uses(ReadChunk::class));
}
public function test_append_data_to_sheet_job_can_interact_with_queue()
{
$this->assertContains(InteractsWithQueue::class, class_uses(AppendDataToSheet::class));
}
public function test_append_query_to_sheet_job_can_interact_with_queue()
{
$this->assertContains(InteractsWithQueue::class, class_uses(AppendQueryToSheet::class));
}
public function test_append_view_to_sheet_job_can_interact_with_queue()
{
$this->assertContains(InteractsWithQueue::class, class_uses(AppendViewToSheet::class));
}
public function test_queue_export_job_can_interact_with_queue()
{
$this->assertContains(InteractsWithQueue::class, class_uses(QueueExport::class));
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/TemporaryFileTest.php | tests/TemporaryFileTest.php | <?php
namespace Maatwebsite\Excel\Tests;
use Maatwebsite\Excel\Files\TemporaryFileFactory;
use Maatwebsite\Excel\Tests\Helpers\FileHelper;
class TemporaryFileTest extends TestCase
{
private $defaultDirectoryPermissions;
private $defaultFilePermissions;
/**
* Setup the test environment.
*/
protected function setUp(): void
{
parent::setUp();
$path = FileHelper::absolutePath('rights-test-permissions', 'local');
mkdir($path);
$this->defaultDirectoryPermissions = substr(sprintf('%o', fileperms($path)), -4);
$filePath = $path . DIRECTORY_SEPARATOR . 'file-permissions';
touch($filePath);
$this->defaultFilePermissions = substr(sprintf('%o', fileperms($filePath)), -4);
@unlink($filePath);
@rmdir($path);
}
public function test_can_use_default_rights()
{
$path = FileHelper::absolutePath('rights-test', 'local');
FileHelper::recursiveDelete($path);
config()->set('excel.temporary_files.local_path', $path);
$temporaryFileFactory = app(TemporaryFileFactory::class);
$temporaryFile = $temporaryFileFactory->makeLocal(null, 'txt');
$temporaryFile->put('data-set');
$this->assertFileExists($temporaryFile->getLocalPath());
$this->assertEquals($this->defaultDirectoryPermissions, substr(sprintf('%o', fileperms(dirname($temporaryFile->getLocalPath()))), -4));
$this->assertEquals($this->defaultFilePermissions, substr(sprintf('%o', fileperms($temporaryFile->getLocalPath())), -4));
}
public function test_can_use_dir_rights()
{
$path = FileHelper::absolutePath('rights-test', 'local');
FileHelper::recursiveDelete($path);
config()->set('excel.temporary_files.local_path', $path);
config()->set('excel.temporary_files.local_permissions.dir', 0700);
$temporaryFileFactory = app(TemporaryFileFactory::class);
$temporaryFile = $temporaryFileFactory->makeLocal(null, 'txt');
$temporaryFile->put('data-set');
$this->assertFileExists($temporaryFile->getLocalPath());
$this->assertEquals('0700', substr(sprintf('%o', fileperms(dirname($temporaryFile->getLocalPath()))), -4));
$this->assertEquals($this->defaultFilePermissions, substr(sprintf('%o', fileperms($temporaryFile->getLocalPath())), -4));
}
public function test_can_use_file_rights()
{
$path = FileHelper::absolutePath('rights-test', 'local');
FileHelper::recursiveDelete($path);
config()->set('excel.temporary_files.local_path', $path);
config()->set('excel.temporary_files.local_permissions.file', 0600);
$temporaryFileFactory = app(TemporaryFileFactory::class);
$temporaryFile = $temporaryFileFactory->makeLocal(null, 'txt');
$temporaryFile->put('data-set');
$this->assertFileExists($temporaryFile->getLocalPath());
$this->assertEquals($this->defaultDirectoryPermissions, substr(sprintf('%o', fileperms(dirname($temporaryFile->getLocalPath()))), -4));
$this->assertEquals('0600', substr(sprintf('%o', fileperms($temporaryFile->getLocalPath())), -4));
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/QueuedImportTest.php | tests/QueuedImportTest.php | <?php
namespace Maatwebsite\Excel\Tests;
use Illuminate\Foundation\Bus\PendingDispatch;
use Illuminate\Queue\Events\JobExceptionOccurred;
use Illuminate\Queue\Events\JobProcessed;
use Illuminate\Queue\Events\JobProcessing;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Queue;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Files\RemoteTemporaryFile;
use Maatwebsite\Excel\Files\TemporaryFile;
use Maatwebsite\Excel\Jobs\AfterImportJob;
use Maatwebsite\Excel\Jobs\ReadChunk;
use Maatwebsite\Excel\SettingsProvider;
use Maatwebsite\Excel\Tests\Data\Stubs\AfterQueueImportJob;
use Maatwebsite\Excel\Tests\Data\Stubs\QueuedImport;
use Maatwebsite\Excel\Tests\Data\Stubs\QueuedImportWithFailure;
use Maatwebsite\Excel\Tests\Data\Stubs\QueuedImportWithMiddleware;
use Maatwebsite\Excel\Tests\Data\Stubs\QueuedImportWithRetryUntil;
use Throwable;
class QueuedImportTest extends TestCase
{
/**
* Setup the test environment.
*/
protected function setUp(): void
{
parent::setUp();
$this->loadLaravelMigrations(['--database' => 'testing']);
$this->loadMigrationsFrom(__DIR__ . '/Data/Stubs/Database/Migrations');
}
public function test_cannot_queue_import_that_does_not_implement_should_queue()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Importable should implement ShouldQueue to be queued.');
$import = new class
{
use Importable;
};
$import->queue('import-batches.xlsx');
}
public function test_can_queue_an_import()
{
$import = new QueuedImport();
$chain = $import->queue('import-batches.xlsx')->chain([
new AfterQueueImportJob(5000),
]);
$this->assertInstanceOf(PendingDispatch::class, $chain);
}
public function test_can_queue_an_import_with_batch_cache_and_file_store()
{
config()->set('queue.default', 'sync');
config()->set('excel.cache.driver', 'batch');
config()->set('excel.cache.illuminate.store', 'file');
config()->set('excel.cache.batch.memory_limit', 80);
// Reset the cache settings
$this->app->make(SettingsProvider::class)->provide();
$import = new QueuedImport();
$chain = $import->queue('import-batches.xlsx');
$this->assertInstanceOf(PendingDispatch::class, $chain);
}
public function test_can_queue_import_with_remote_temp_disk()
{
config()->set('excel.temporary_files.remote_disk', 'test');
// Delete the local temp file before each read chunk job
// to simulate using a shared remote disk, without
// having a dependency on a local temp file.
Queue::before(function (JobProcessing $event) {
if ($event->job->resolveName() === ReadChunk::class) {
/** @var TemporaryFile $tempFile */
$tempFile = $this->inspectJobProperty($event->job, 'temporaryFile');
$this->assertInstanceOf(RemoteTemporaryFile::class, $tempFile);
// Should exist remote
$this->assertTrue(
$tempFile->exists()
);
$this->assertTrue(
unlink($tempFile->getLocalPath())
);
}
});
$import = new QueuedImport();
$chain = $import->queue('import-batches.xlsx')->chain([
new AfterQueueImportJob(5000),
]);
$this->assertInstanceOf(PendingDispatch::class, $chain);
}
public function test_can_keep_extension_for_temp_file_on_remote_disk()
{
config()->set('excel.temporary_files.remote_disk', 'test');
Queue::before(function (JobProcessing $event) {
if ($event->job->resolveName() === ReadChunk::class) {
/** @var TemporaryFile $tempFile */
$tempFile = $this->inspectJobProperty($event->job, 'temporaryFile');
$this->assertStringContains('.xlsx', $tempFile->getLocalPath());
}
});
(new QueuedImport())->queue('import-batches.xlsx');
}
public function test_can_queue_import_with_remote_temp_disk_and_prefix()
{
config()->set('excel.temporary_files.remote_disk', 'test');
config()->set('excel.temporary_files.remote_prefix', 'tmp/');
$import = new QueuedImport();
$chain = $import->queue('import-batches.xlsx')->chain([
new AfterQueueImportJob(5000),
]);
$this->assertInstanceOf(PendingDispatch::class, $chain);
}
public function test_can_automatically_delete_temp_file_on_failure_when_using_remote_disk()
{
config()->set('excel.temporary_files.remote_disk', 'test');
$tempFile = '';
Queue::exceptionOccurred(function (JobExceptionOccurred $event) use (&$tempFile) {
if ($event->job->resolveName() === ReadChunk::class) {
$tempFile = $this->inspectJobProperty($event->job, 'temporaryFile');
}
});
try {
(new QueuedImportWithFailure())->queue('import-batches.xlsx');
} catch (Throwable $e) {
$this->assertEquals('Something went wrong in the chunk', $e->getMessage());
}
$this->assertFalse($tempFile->existsLocally());
$this->assertTrue($tempFile->exists());
}
public function test_cannot_automatically_delete_temp_file_on_failure_when_using_local_disk()
{
$tempFile = '';
Queue::exceptionOccurred(function (JobExceptionOccurred $event) use (&$tempFile) {
if ($event->job->resolveName() === ReadChunk::class) {
$tempFile = $this->inspectJobProperty($event->job, 'temporaryFile');
}
});
try {
(new QueuedImportWithFailure())->queue('import-batches.xlsx');
} catch (Throwable $e) {
$this->assertEquals('Something went wrong in the chunk', $e->getMessage());
}
$this->assertTrue($tempFile->exists());
}
public function test_can_force_remote_download_and_deletion_for_each_chunk_on_queue()
{
config()->set('excel.temporary_files.remote_disk', 'test');
config()->set('excel.temporary_files.force_resync_remote', true);
Bus::fake([AfterImportJob::class]);
Queue::after(function (JobProcessed $event) {
if ($event->job->resolveName() === ReadChunk::class) {
$tempFile = $this->inspectJobProperty($event->job, 'temporaryFile');
// Should not exist locally after each chunk
$this->assertFalse(
$tempFile->existsLocally()
);
}
});
(new QueuedImport())->queue('import-batches.xlsx');
}
public function test_can_define_middleware_method_on_queued_import()
{
try {
(new QueuedImportWithMiddleware())->queue('import-batches.xlsx');
} catch (Throwable $e) {
$this->assertEquals('Job reached middleware method', $e->getMessage());
}
}
public function test_can_define_retry_until_method_on_queued_import()
{
try {
(new QueuedImportWithRetryUntil())->queue('import-batches.xlsx');
} catch (Throwable $e) {
$this->assertEquals('Job reached retryUntil method', $e->getMessage());
}
}
public function test_can_define_max_exceptions_property_on_queued_import()
{
$maxExceptionsCount = 0;
Queue::exceptionOccurred(function (JobExceptionOccurred $event) use (&$maxExceptionsCount) {
if ($event->job->resolveName() === ReadChunk::class) {
$maxExceptionsCount = $this->inspectJobProperty($event->job, 'maxExceptions');
}
});
try {
$import = new QueuedImportWithFailure();
$import->maxExceptions = 3;
$import->queue('import-batches.xlsx');
} catch (Throwable $e) {
$this->assertEquals('Something went wrong in the chunk', $e->getMessage());
}
$this->assertEquals(3, $maxExceptionsCount);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/QueuedQueryExportTest.php | tests/QueuedQueryExportTest.php | <?php
namespace Maatwebsite\Excel\Tests;
use Maatwebsite\Excel\SettingsProvider;
use Maatwebsite\Excel\Tests\Data\Stubs\AfterQueueExportJob;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
use Maatwebsite\Excel\Tests\Data\Stubs\FromUsersQueryExport;
use Maatwebsite\Excel\Tests\Data\Stubs\FromUsersQueryExportWithMapping;
use Maatwebsite\Excel\Tests\Data\Stubs\FromUsersScoutExport;
class QueuedQueryExportTest extends TestCase
{
/**
* Setup the test environment.
*/
protected function setUp(): void
{
parent::setUp();
$this->loadLaravelMigrations(['--database' => 'testing']);
$this->withFactories(__DIR__ . '/Data/Stubs/Database/Factories');
factory(User::class)->times(100)->create([]);
}
public function test_can_queue_an_export()
{
$export = new FromUsersQueryExport();
$export->queue('queued-query-export.xlsx')->chain([
new AfterQueueExportJob(__DIR__ . '/Data/Disks/Local/queued-query-export.xlsx'),
]);
$actual = $this->readAsArray(__DIR__ . '/Data/Disks/Local/queued-query-export.xlsx', 'Xlsx');
$this->assertCount(100, $actual);
// 6 of the 7 columns in export, excluding the "hidden" password column.
$this->assertCount(6, $actual[0]);
}
public function test_can_queue_an_export_with_batch_cache_and_file_store()
{
config()->set('queue.default', 'sync');
config()->set('excel.cache.driver', 'batch');
config()->set('excel.cache.illuminate.store', 'file');
config()->set('excel.cache.batch.memory_limit', 80);
// Reset the cache settings
$this->app->make(SettingsProvider::class)->provide();
$export = new FromUsersQueryExport();
$export->queue('queued-query-export.xlsx')->chain([
new AfterQueueExportJob(__DIR__ . '/Data/Disks/Local/queued-query-export.xlsx'),
]);
$actual = $this->readAsArray(__DIR__ . '/Data/Disks/Local/queued-query-export.xlsx', 'Xlsx');
$this->assertCount(100, $actual);
}
public function test_can_queue_an_export_with_mapping()
{
$export = new FromUsersQueryExportWithMapping();
$export->queue('queued-query-export-with-mapping.xlsx')->chain([
new AfterQueueExportJob(__DIR__ . '/Data/Disks/Local/queued-query-export-with-mapping.xlsx'),
]);
$actual = $this->readAsArray(__DIR__ . '/Data/Disks/Local/queued-query-export-with-mapping.xlsx', 'Xlsx');
$this->assertCount(100, $actual);
// Only 1 column when using map()
$this->assertCount(1, $actual[0]);
$this->assertEquals(User::value('name'), $actual[0][0]);
}
public function test_can_queue_scout_export()
{
if (!class_exists('\Laravel\Scout\Engines\DatabaseEngine')) {
$this->markTestSkipped('Laravel Scout is too old');
return;
}
$export = new FromUsersScoutExport();
$export->queue('queued-scout-export.xlsx')->chain([
new AfterQueueExportJob(__DIR__ . '/Data/Disks/Local/queued-scout-export.xlsx'),
]);
$actual = $this->readAsArray(__DIR__ . '/Data/Disks/Local/queued-scout-export.xlsx', 'Xlsx');
$this->assertCount(100, $actual);
// 6 of the 7 columns in export, excluding the "hidden" password column.
$this->assertCount(6, $actual[0]);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/ExcelTest.php | tests/ExcelTest.php | <?php
namespace Maatwebsite\Excel\Tests;
use Illuminate\Contracts\View\View;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\FromView;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\RegistersEventListeners;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\WithCustomCsvSettings;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Facades\Excel as ExcelFacade;
use Maatwebsite\Excel\Importer;
use Maatwebsite\Excel\Tests\Data\Stubs\EmptyExport;
use Maatwebsite\Excel\Tests\Helpers\FileHelper;
use PHPUnit\Framework\Assert;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
class ExcelTest extends TestCase
{
/**
* @var Excel
*/
protected $SUT;
protected function setUp(): void
{
parent::setUp();
$this->SUT = $this->app->make(Excel::class);
}
public function test_can_download_an_export_object_with_facade()
{
$export = new EmptyExport();
$response = ExcelFacade::download($export, 'filename.xlsx');
$this->assertInstanceOf(BinaryFileResponse::class, $response);
$this->assertEquals('attachment; filename=filename.xlsx', str_replace('"', '', $response->headers->get('Content-Disposition')));
}
public function test_can_download_an_export_object()
{
$export = new EmptyExport();
$response = $this->SUT->download($export, 'filename.xlsx');
$this->assertInstanceOf(BinaryFileResponse::class, $response);
$this->assertEquals('attachment; filename=filename.xlsx', str_replace('"', '', $response->headers->get('Content-Disposition')));
}
public function test_can_store_an_export_object_on_default_disk()
{
$export = new EmptyExport;
$name = 'filename.xlsx';
$path = FileHelper::absolutePath($name, 'local');
@unlink($path);
$this->assertFileMissing($path);
$response = $this->SUT->store($export, $name);
$this->assertTrue($response);
$this->assertFileExists($path);
}
public function test_can_store_an_export_object_on_another_disk()
{
$export = new EmptyExport;
$name = 'filename.xlsx';
$path = FileHelper::absolutePath($name, 'test');
@unlink($path);
$this->assertFileMissing($path);
$response = $this->SUT->store($export, $name, 'test');
$this->assertTrue($response);
$this->assertFileExists($path);
}
public function test_can_store_csv_export_with_default_settings()
{
$export = new EmptyExport;
$name = 'filename.csv';
$path = FileHelper::absolutePath($name, 'local');
@unlink($path);
$this->assertFileMissing($path);
$response = $this->SUT->store($export, $name);
$this->assertTrue($response);
$this->assertFileExists($path);
}
public function test_can_get_raw_export_contents()
{
$export = new EmptyExport;
$response = $this->SUT->raw($export, Excel::XLSX);
$this->assertNotEmpty($response);
}
public function test_can_store_tsv_export_with_default_settings()
{
$export = new EmptyExport;
$name = 'filename.tsv';
$path = FileHelper::absolutePath($name, 'local');
@unlink($path);
$this->assertFileMissing($path);
$response = $this->SUT->store($export, $name);
$this->assertTrue($response);
$this->assertFileExists($path);
}
public function test_can_store_csv_export_with_custom_settings()
{
$export = new class implements WithEvents, FromCollection, WithCustomCsvSettings
{
use RegistersEventListeners;
/**
* @return Collection
*/
public function collection()
{
return collect([
['A1', 'B1'],
['A2', 'B2'],
]);
}
/**
* @return array
*/
public function getCsvSettings(): array
{
return [
'line_ending' => PHP_EOL,
'enclosure' => '"',
'delimiter' => ';',
'include_separator_line' => true,
'excel_compatibility' => false,
];
}
};
$this->SUT->store($export, 'filename.csv');
$contents = file_get_contents(__DIR__ . '/Data/Disks/Local/filename.csv');
$this->assertStringContains('sep=;', $contents);
$this->assertStringContains('"A1";"B1"', $contents);
$this->assertStringContains('"A2";"B2"', $contents);
}
public function test_cannot_use_from_collection_and_from_view_on_same_export()
{
$this->expectException(\Maatwebsite\Excel\Exceptions\ConcernConflictException::class);
$this->expectExceptionMessage('Cannot use FromQuery, FromArray or FromCollection and FromView on the same sheet');
$export = new class implements FromCollection, FromView
{
use Exportable;
/**
* @return Collection
*/
public function collection()
{
return collect();
}
/**
* @return View
*/
public function view(): View
{
return view('users');
}
};
$export->download('filename.csv');
}
public function test_can_import_a_simple_xlsx_file_to_array()
{
$import = new class
{
use Importable;
};
$this->assertEquals([
[
['test', 'test'],
['test', 'test'],
],
], $import->toArray('import.xlsx'));
}
public function test_can_import_a_simple_xlsx_file_to_collection()
{
$import = new class
{
use Importable;
};
$this->assertEquals(new Collection([
new Collection([
new Collection(['test', 'test']),
new Collection(['test', 'test']),
]),
]), $import->toCollection('import.xlsx'));
}
public function test_can_import_a_simple_xlsx_file_to_collection_without_import_object()
{
$this->assertEquals(new Collection([
new Collection([
new Collection(['test', 'test']),
new Collection(['test', 'test']),
]),
]), ExcelFacade::toCollection(null, 'import.xlsx'));
}
public function test_can_import_a_simple_xlsx_file()
{
$import = new class implements ToArray
{
/**
* @param array $array
*/
public function array(array $array)
{
Assert::assertEquals([
['test', 'test'],
['test', 'test'],
], $array);
}
};
$imported = $this->SUT->import($import, 'import.xlsx');
$this->assertInstanceOf(Importer::class, $imported);
}
public function test_can_import_a_tsv_file()
{
$import = new class implements ToArray, WithCustomCsvSettings
{
/**
* @param array $array
*/
public function array(array $array)
{
Assert::assertEquals([
'tconst',
'titleType',
'primaryTitle',
'originalTitle',
'isAdult',
'startYear',
'endYear',
'runtimeMinutes',
'genres',
], $array[0]);
}
/**
* @return array
*/
public function getCsvSettings(): array
{
return [
'delimiter' => "\t",
];
}
};
$imported = $this->SUT->import($import, 'import-titles.tsv');
$this->assertInstanceOf(Importer::class, $imported);
}
public function test_can_chain_imports()
{
$import1 = new class implements ToArray
{
/**
* @param array $array
*/
public function array(array $array)
{
Assert::assertEquals([
['test', 'test'],
['test', 'test'],
], $array);
}
};
$import2 = new class implements ToArray
{
/**
* @param array $array
*/
public function array(array $array)
{
Assert::assertEquals([
['test', 'test'],
['test', 'test'],
], $array);
}
};
$imported = $this->SUT
->import($import1, 'import.xlsx')
->import($import2, 'import.xlsx');
$this->assertInstanceOf(Importer::class, $imported);
}
public function test_can_import_a_simple_xlsx_file_from_uploaded_file()
{
$import = new class implements ToArray
{
/**
* @param array $array
*/
public function array(array $array)
{
Assert::assertEquals([
['test', 'test'],
['test', 'test'],
], $array);
}
};
$this->SUT->import($import, $this->givenUploadedFile(__DIR__ . '/Data/Disks/Local/import.xlsx'));
}
public function test_can_import_a_simple_xlsx_file_from_real_path()
{
$import = new class implements ToArray
{
/**
* @param array $array
*/
public function array(array $array)
{
Assert::assertEquals([
['test', 'test'],
['test', 'test'],
], $array);
}
};
$this->SUT->import($import, __DIR__ . '/Data/Disks/Local/import.xlsx');
}
public function test_import_will_throw_error_when_no_reader_type_could_be_detected_when_no_extension()
{
$this->expectException(\Maatwebsite\Excel\Exceptions\NoTypeDetectedException::class);
$import = new class implements ToArray
{
/**
* @param array $array
*/
public function array(array $array)
{
Assert::assertEquals([
['test', 'test'],
['test', 'test'],
], $array);
}
};
$this->SUT->import($import, UploadedFile::fake()->create('import'));
}
public function test_import_will_throw_error_when_no_reader_type_could_be_detected_with_unknown_extension()
{
$this->expectException(\Maatwebsite\Excel\Exceptions\NoTypeDetectedException::class);
$import = new class implements ToArray
{
/**
* @param array $array
*/
public function array(array $array)
{
//
}
};
$this->SUT->import($import, 'unknown-reader-type.zip');
}
public function test_can_import_without_extension_with_explicit_reader_type()
{
$import = new class implements ToArray
{
/**
* @param array $array
*/
public function array(array $array)
{
Assert::assertEquals([
['test', 'test'],
['test', 'test'],
], $array);
}
};
$this->SUT->import(
$import,
$this->givenUploadedFile(__DIR__ . '/Data/Disks/Local/import.xlsx', 'import'),
null,
Excel::XLSX
);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/QueuedExportTest.php | tests/QueuedExportTest.php | <?php
namespace Maatwebsite\Excel\Tests;
use Illuminate\Queue\Events\JobProcessing;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Queue;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Files\RemoteTemporaryFile;
use Maatwebsite\Excel\Files\TemporaryFile;
use Maatwebsite\Excel\Jobs\AppendDataToSheet;
use Maatwebsite\Excel\Tests\Data\Stubs\AfterQueueExportJob;
use Maatwebsite\Excel\Tests\Data\Stubs\EloquentCollectionWithMappingExport;
use Maatwebsite\Excel\Tests\Data\Stubs\QueuedExport;
use Maatwebsite\Excel\Tests\Data\Stubs\QueuedExportWithFailedEvents;
use Maatwebsite\Excel\Tests\Data\Stubs\QueuedExportWithFailedHook;
use Maatwebsite\Excel\Tests\Data\Stubs\QueuedExportWithLocalePreferences;
use Maatwebsite\Excel\Tests\Data\Stubs\ShouldQueueExport;
use Throwable;
class QueuedExportTest extends TestCase
{
public function test_can_queue_an_export()
{
$export = new QueuedExport();
$export->queue('queued-export.xlsx')->chain([
new AfterQueueExportJob(__DIR__ . '/Data/Disks/Local/queued-export.xlsx'),
]);
}
public function test_can_queue_an_export_and_store_on_different_disk()
{
$export = new QueuedExport();
$export->queue('queued-export.xlsx', 'test')->chain([
new AfterQueueExportJob(__DIR__ . '/Data/Disks/Test/queued-export.xlsx'),
]);
}
public function test_can_queue_export_with_remote_temp_disk()
{
config()->set('excel.temporary_files.remote_disk', 'test');
// Delete the local temp file before each append job
// to simulate using a shared remote disk, without
// having a dependency on a local temp file.
$jobs = 0;
Queue::before(function (JobProcessing $event) use (&$jobs) {
if ($event->job->resolveName() === AppendDataToSheet::class) {
/** @var TemporaryFile $tempFile */
$tempFile = $this->inspectJobProperty($event->job, 'temporaryFile');
$this->assertInstanceOf(RemoteTemporaryFile::class, $tempFile);
// Should exist remote
$this->assertTrue(
$tempFile->exists()
);
// File was deleted locally
$this->assertFalse(
file_exists($tempFile->getLocalPath())
);
$jobs++;
}
});
$export = new QueuedExport();
$export->queue('queued-export.xlsx')->chain([
new AfterQueueExportJob(__DIR__ . '/Data/Disks/Local/queued-export.xlsx'),
]);
$array = $this->readAsArray(__DIR__ . '/Data/Disks/Local/queued-export.xlsx', Excel::XLSX);
$this->assertCount(100, $array);
$this->assertEquals(3, $jobs);
}
public function test_can_queue_export_with_remote_temp_disk_and_prefix()
{
config()->set('excel.temporary_files.remote_disk', 'test');
config()->set('excel.temporary_files.remote_prefix', 'tmp/');
$export = new QueuedExport();
$export->queue('queued-export.xlsx')->chain([
new AfterQueueExportJob(__DIR__ . '/Data/Disks/Local/queued-export.xlsx'),
]);
}
public function test_can_implicitly_queue_an_export()
{
$export = new ShouldQueueExport();
$export->store('queued-export.xlsx', 'test')->chain([
new AfterQueueExportJob(__DIR__ . '/Data/Disks/Test/queued-export.xlsx'),
]);
}
public function test_can_queue_export_with_mapping_on_eloquent_models()
{
$export = new EloquentCollectionWithMappingExport();
$export->queue('queued-export.xlsx')->chain([
new AfterQueueExportJob(__DIR__ . '/Data/Disks/Local/queued-export.xlsx'),
]);
$actual = $this->readAsArray(__DIR__ . '/Data/Disks/Local/queued-export.xlsx', 'Xlsx');
$this->assertEquals([
['Patrick', 'Brouwers'],
], $actual);
}
public function test_can_catch_failures()
{
$export = new QueuedExportWithFailedHook();
try {
$export->queue('queued-export.xlsx');
} catch (Throwable $e) {
}
$this->assertTrue(app('queue-has-failed'));
}
public function test_can_catch_failures_on_queue_export_job()
{
$export = new QueuedExportWithFailedEvents();
try {
$export->queue('queued-export.xlsx');
} catch (Throwable $e) {
}
$this->assertTrue(app('queue-has-failed-from-queue-export-job'));
}
public function test_can_set_locale_on_queue_export_job()
{
$currentLocale = app()->getLocale();
$export = new QueuedExportWithLocalePreferences('ru');
$export->queue('queued-export.xlsx');
$this->assertTrue(app('queue-has-correct-locale'));
$this->assertEquals($currentLocale, app()->getLocale());
}
public function test_can_queue_export_not_flushing_the_cache()
{
config()->set('excel.cache.driver', 'illuminate');
Cache::put('test', 'test');
$export = new QueuedExport();
$export->queue('queued-export.xlsx')->chain([
new AfterQueueExportJob(__DIR__ . '/Data/Disks/Local/queued-export.xlsx'),
]);
$array = $this->readAsArray(__DIR__ . '/Data/Disks/Local/queued-export.xlsx', Excel::XLSX);
$this->assertCount(100, $array);
$this->assertEquals('test', Cache::get('test'));
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Helpers/FileHelper.php | tests/Helpers/FileHelper.php | <?php
namespace Maatwebsite\Excel\Tests\Helpers;
class FileHelper
{
public static function absolutePath($fileName, $diskName)
{
return config('filesystems.disks.' . $diskName . '.root') . DIRECTORY_SEPARATOR . $fileName;
}
public static function recursiveDelete($fileName)
{
if (is_file($fileName)) {
return @unlink($fileName);
}
if (is_dir($fileName)) {
$scan = glob(rtrim($fileName, '/') . '/*');
foreach ($scan as $path) {
self::recursiveDelete($path);
}
return @rmdir($fileName);
}
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Mixins/StoreCollectionTest.php | tests/Mixins/StoreCollectionTest.php | <?php
namespace Maatwebsite\Excel\Tests\Mixins;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
use Maatwebsite\Excel\Tests\TestCase;
class StoreCollectionTest extends TestCase
{
public function test_can_store_a_collection_as_excel()
{
$collection = new Collection([
['test', 'test'],
['test', 'test'],
]);
$response = $collection->storeExcel('collection-store.xlsx');
$this->assertTrue($response);
$this->assertFileExists(__DIR__ . '/../Data/Disks/Local/collection-store.xlsx');
}
public function test_can_store_a_collection_as_excel_on_non_default_disk()
{
$collection = new Collection([
['column_1' => 'test', 'column_2' => 'test'],
['column_1' => 'test2', 'column_2' => 'test2'],
]);
$response = $collection->storeExcel('collection-store.xlsx', null, Excel::XLSX);
$file = __DIR__ . '/../Data/Disks/Local/collection-store.xlsx';
$this->assertTrue($response);
$this->assertFileExists($file);
$array = $this->readAsArray($file, Excel::XLSX);
// First row are not headings
$firstRow = collect($array)->first();
$this->assertEquals(['test', 'test'], $firstRow);
$this->assertEquals([
['test', 'test'],
['test2', 'test2'],
], collect($array)->values()->all());
}
public function test_can_store_a_collection_with_headings_as_excel()
{
$collection = new Collection([
['column_1' => 'test', 'column_2' => 'test'],
['column_1' => 'test', 'column_2' => 'test'],
]);
$response = $collection->storeExcel('collection-headers-store.xlsx', null, Excel::XLSX, true);
$file = __DIR__ . '/../Data/Disks/Local/collection-headers-store.xlsx';
$this->assertTrue($response);
$this->assertFileExists($file);
$array = $this->readAsArray($file, Excel::XLSX);
$this->assertEquals(['column_1', 'column_2'], collect($array)->first());
$this->assertEquals([
['test', 'test'],
['test', 'test'],
], collect($array)->except(0)->values()->all());
}
public function test_can_store_a_model_collection_with_headings_as_excel()
{
$this->withFactories(__DIR__ . '/../Data/Stubs/Database/Factories');
$collection = factory(User::class, 2)->make();
$response = $collection->storeExcel('model-collection-headers-store.xlsx', null, Excel::XLSX, true);
$file = __DIR__ . '/../Data/Disks/Local/model-collection-headers-store.xlsx';
$this->assertTrue($response);
$this->assertFileExists($file);
$array = $this->readAsArray($file, Excel::XLSX);
$this->assertEquals(['name', 'email', 'remember_token'], collect($array)->first());
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Mixins/DownloadCollectionTest.php | tests/Mixins/DownloadCollectionTest.php | <?php
namespace Maatwebsite\Excel\Tests\Mixins;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
use Maatwebsite\Excel\Tests\TestCase;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
class DownloadCollectionTest extends TestCase
{
public function test_can_download_a_collection_as_excel()
{
$collection = new Collection([
['column_1' => 'test', 'column_2' => 'test'],
['column_1' => 'test2', 'column_2' => 'test2'],
]);
$response = $collection->downloadExcel('collection-download.xlsx', Excel::XLSX);
$array = $this->readAsArray($response->getFile()->getPathName(), Excel::XLSX);
// First row are not headings
$firstRow = collect($array)->first();
$this->assertEquals(['test', 'test'], $firstRow);
$this->assertInstanceOf(BinaryFileResponse::class, $response);
$this->assertEquals(
'attachment; filename=collection-download.xlsx',
str_replace('"', '', $response->headers->get('Content-Disposition'))
);
}
public function test_can_download_a_collection_with_headers_as_excel()
{
$collection = new Collection([
['column_1' => 'test', 'column_2' => 'test'],
['column_1' => 'test', 'column_2' => 'test'],
]);
$response = $collection->downloadExcel('collection-headers-download.xlsx', Excel::XLSX, true);
$array = $this->readAsArray($response->getFile()->getPathName(), Excel::XLSX);
$this->assertEquals(['column_1', 'column_2'], collect($array)->first());
}
public function test_can_download_collection_with_headers_with_hidden_eloquent_attributes()
{
$collection = new Collection([
new User(['name' => 'Patrick', 'password' => 'my_password']),
]);
$response = $collection->downloadExcel('collection-headers-download.xlsx', Excel::XLSX, true);
$array = $this->readAsArray($response->getFile()->getPathName(), Excel::XLSX);
$this->assertEquals(['name'], collect($array)->first());
}
public function test_can_download_collection_with_headers_when_making_attributes_visible()
{
$user = new User(['name' => 'Patrick', 'password' => 'my_password']);
$user->makeVisible(['password']);
$collection = new Collection([
$user,
]);
$response = $collection->downloadExcel('collection-headers-download.xlsx', Excel::XLSX, true);
$array = $this->readAsArray($response->getFile()->getPathName(), Excel::XLSX);
$this->assertEquals(['name', 'password'], collect($array)->first());
}
public function test_can_set_custom_response_headers()
{
$collection = new Collection([
['column_1' => 'test', 'column_2' => 'test'],
['column_1' => 'test2', 'column_2' => 'test2'],
]);
$responseHeaders = [
'CUSTOMER-HEADER-1' => 'CUSTOMER-HEADER1-VAL',
'CUSTOMER-HEADER-2' => 'CUSTOMER-HEADER2-VAL',
];
/** @var BinaryFileResponse $response */
$response = $collection->downloadExcel('collection-download.xlsx', Excel::XLSX, false, $responseHeaders);
$this->assertTrue($response->headers->contains('CUSTOMER-HEADER-1', 'CUSTOMER-HEADER1-VAL'));
$this->assertTrue($response->headers->contains('CUSTOMER-HEADER-2', 'CUSTOMER-HEADER2-VAL'));
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Mixins/ImportAsMacroTest.php | tests/Mixins/ImportAsMacroTest.php | <?php
namespace Maatwebsite\Excel\Tests\Mixins;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
use Maatwebsite\Excel\Tests\TestCase;
class ImportAsMacroTest extends TestCase
{
/**
* Setup the test environment.
*/
protected function setUp(): void
{
parent::setUp();
$this->loadLaravelMigrations(['--database' => 'testing']);
}
public function test_can_import_directly_into_a_model_with_mapping()
{
User::query()->truncate();
User::importAs('import-users.xlsx', function (array $row) {
return [
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
];
});
$this->assertCount(2, User::all());
$this->assertEquals([
'patrick@maatwebsite.nl',
'taylor@laravel.com',
], User::query()->pluck('email')->all());
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Mixins/DownloadQueryMacroTest.php | tests/Mixins/DownloadQueryMacroTest.php | <?php
namespace Maatwebsite\Excel\Tests\Mixins;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
use Maatwebsite\Excel\Tests\TestCase;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
class DownloadQueryMacroTest extends TestCase
{
/**
* Setup the test environment.
*/
protected function setUp(): void
{
parent::setUp();
$this->loadLaravelMigrations(['--database' => 'testing']);
$this->withFactories(__DIR__ . '/../Data/Stubs/Database/Factories');
factory(User::class)->times(100)->create();
}
public function test_can_download_a_query_as_excel()
{
$response = User::downloadExcel('query-download.xlsx', Excel::XLSX);
$array = $this->readAsArray($response->getFile()->getPathName(), Excel::XLSX);
$this->assertCount(100, $array);
$this->assertInstanceOf(BinaryFileResponse::class, $response);
$this->assertEquals(
'attachment; filename=query-download.xlsx',
str_replace('"', '', $response->headers->get('Content-Disposition'))
);
}
public function test_can_download_a_collection_with_headers_as_excel()
{
$response = User::downloadExcel('collection-headers-download.xlsx', Excel::XLSX, true);
$array = $this->readAsArray($response->getFile()->getPathName(), Excel::XLSX);
$this->assertCount(101, $array);
$this->assertEquals(['id', 'name', 'email', 'remember_token', 'created_at', 'updated_at'], collect($array)->first());
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Mixins/ImportMacroTest.php | tests/Mixins/ImportMacroTest.php | <?php
namespace Maatwebsite\Excel\Tests\Mixins;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
use Maatwebsite\Excel\Tests\TestCase;
class ImportMacroTest extends TestCase
{
/**
* Setup the test environment.
*/
protected function setUp(): void
{
parent::setUp();
$this->loadLaravelMigrations(['--database' => 'testing']);
}
public function test_can_import_directly_into_a_model()
{
User::query()->truncate();
User::creating(function ($user) {
$user->password = 'secret';
});
User::import('import-users-with-headings.xlsx');
$this->assertCount(2, User::all());
$this->assertEquals([
'patrick@maatwebsite.nl',
'taylor@laravel.com',
], User::query()->pluck('email')->all());
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Mixins/StoreQueryMacroTest.php | tests/Mixins/StoreQueryMacroTest.php | <?php
namespace Maatwebsite\Excel\Tests\Mixins;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
use Maatwebsite\Excel\Tests\TestCase;
class StoreQueryMacroTest extends TestCase
{
/**
* Setup the test environment.
*/
protected function setUp(): void
{
parent::setUp();
$this->loadLaravelMigrations(['--database' => 'testing']);
$this->withFactories(__DIR__ . '/../Data/Stubs/Database/Factories');
factory(User::class)->times(100)->create();
}
public function test_can_download_a_query_as_excel()
{
$response = User::storeExcel('query-store.xlsx', null, Excel::XLSX);
$this->assertTrue($response);
$this->assertFileExists(__DIR__ . '/../Data/Disks/Local/query-store.xlsx');
$array = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/query-store.xlsx', Excel::XLSX);
$this->assertCount(100, $array);
}
public function test_can_download_a_query_as_excel_on_different_disk()
{
$response = User::storeExcel('query-store.xlsx', 'test', Excel::XLSX);
$this->assertTrue($response);
$this->assertFileExists(__DIR__ . '/../Data/Disks/Test/query-store.xlsx');
$array = $this->readAsArray(__DIR__ . '/../Data/Disks/Test/query-store.xlsx', Excel::XLSX);
$this->assertCount(100, $array);
}
public function test_can_store_a_query_with_headers_as_excel()
{
$response = User::storeExcel('query-headers-store.xlsx', null, Excel::XLSX, true);
$this->assertTrue($response);
$this->assertFileExists(__DIR__ . '/../Data/Disks/Local/query-headers-store.xlsx');
$array = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/query-headers-store.xlsx', Excel::XLSX);
$this->assertCount(101, $array);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Cache/BatchCacheTest.php | tests/Cache/BatchCacheTest.php | <?php
namespace Maatwebsite\Excel\Tests\Cache;
use Composer\InstalledVersions;
use Composer\Semver\VersionParser;
use DateInterval;
use Illuminate\Cache\ArrayStore;
use Illuminate\Cache\Events\KeyWritten;
use Illuminate\Cache\Repository;
use Illuminate\Support\Facades\Event;
use Maatwebsite\Excel\Cache\BatchCache;
use Maatwebsite\Excel\Cache\BatchCacheDeprecated;
use Maatwebsite\Excel\Cache\CacheManager;
use Maatwebsite\Excel\Cache\MemoryCache;
use Maatwebsite\Excel\Tests\TestCase;
use PHPUnit\Framework\Attributes\DataProvider;
use Psr\SimpleCache\CacheInterface;
class BatchCacheTest extends TestCase
{
/**
* @var Repository
*/
private $cache;
/**
* @var MemoryCache
*/
private $memory;
public function test_will_get_multiple_from_memory_if_cells_hold_in_memory()
{
$inMemory = [
'A1' => 'A1-value',
'A2' => 'A2-value',
'A3' => 'A3-value',
];
$cache = $this->givenCache($inMemory);
$this->assertEquals(
$inMemory,
$cache->getMultiple(['A1', 'A2', 'A3'])
);
$this->assertEquals('A3-value', $cache->get('A3'));
}
public function test_will_get_multiple_from_cache_if_cells_are_persisted()
{
$inMemory = [];
$persisted = [
'A1' => 'A1-value',
'A2' => 'A2-value',
'A3' => 'A3-value',
];
$cache = $this->givenCache($inMemory, $persisted);
$this->assertEquals(
$persisted,
$cache->getMultiple(['A1', 'A2', 'A3'])
);
$this->assertEquals('A3-value', $cache->get('A3'));
}
public function test_will_get_multiple_from_cache_and_persisted()
{
$inMemory = [
'A1' => 'A1-value',
'A2' => 'A2-value',
'A3' => 'A3-value',
];
$persisted = [
'A4' => 'A4-value',
'A5' => 'A5-value',
'A6' => 'A6-value',
];
$cache = $this->givenCache($inMemory, $persisted);
$this->assertEquals(
array_merge($inMemory, $persisted),
$cache->getMultiple(['A1', 'A2', 'A3', 'A4', 'A5', 'A6'])
);
$this->assertEquals('A3-value', $cache->get('A3'));
$this->assertEquals('A6-value', $cache->get('A6'));
}
public function test_it_persists_to_cache_when_memory_limit_reached_on_setting_a_value()
{
$memoryLimit = 3;
$persisted = [];
$inMemory = [
'A1' => 'A1-value',
'A2' => 'A2-value',
'A3' => 'A3-value',
];
$cache = $this->givenCache($inMemory, $persisted, $memoryLimit);
// Setting a 4th value will reach the memory limit
$cache->set('A4', 'A4-value', 10000);
// Nothing in memory anymore
$this->assertEquals([], array_filter($this->memory->getMultiple(['A1', 'A2', 'A3', 'A4'])));
// All 4 cells show be persisted
$this->assertEquals([
'A1' => 'A1-value',
'A2' => 'A2-value',
'A3' => 'A3-value',
'A4' => 'A4-value',
], $this->cache->getMultiple(['A1', 'A2', 'A3', 'A4']));
// Batch cache should return all 4 cells
$this->assertEquals([
'A1' => 'A1-value',
'A2' => 'A2-value',
'A3' => 'A3-value',
'A4' => 'A4-value',
], $cache->getMultiple(['A1', 'A2', 'A3', 'A4']));
}
public function test_it_persists_to_cache_when_memory_limit_reached_on_setting_multiple_values()
{
$memoryLimit = 3;
$persisted = [];
$inMemory = [
'A1' => 'A1-value',
'A2' => 'A2-value',
'A3' => 'A3-value',
];
$cache = $this->givenCache($inMemory, $persisted, $memoryLimit);
// Setting a 4th value will reach the memory limit
$cache->setMultiple([
'A4' => 'A4-value',
'A5' => 'A5-value',
], 10000);
// Nothing in memory anymore
$this->assertEquals([], array_filter($this->memory->getMultiple(['A1', 'A2', 'A3', 'A4', 'A5'])));
// All 4 cells show be persisted
$this->assertEquals([
'A1' => 'A1-value',
'A2' => 'A2-value',
'A3' => 'A3-value',
'A4' => 'A4-value',
'A5' => 'A5-value',
], $this->cache->getMultiple(['A1', 'A2', 'A3', 'A4', 'A5']));
// Batch cache should return all 4 cells
$this->assertEquals([
'A1' => 'A1-value',
'A2' => 'A2-value',
'A3' => 'A3-value',
'A4' => 'A4-value',
'A5' => 'A5-value',
], $cache->getMultiple(['A1', 'A2', 'A3', 'A4', 'A5']));
}
/**
* @dataProvider defaultTTLDataProvider
*/
#[DataProvider('defaultTTLDataProvider')]
public function test_it_writes_to_cache_with_default_ttl($defaultTTL, $receivedAs)
{
config()->set('excel.cache.default_ttl', $defaultTTL);
$cache = $this->givenCache(['A1' => 'A1-value'], [], 1);
$this->cache->setEventDispatcher(Event::fake());
$cache->set('A2', 'A2-value');
$expectedTTL = value($receivedAs);
$dispatchedCollection = Event::dispatched(
KeyWritten::class,
function (KeyWritten $event) use ($expectedTTL) {
return $event->seconds === $expectedTTL;
});
$this->assertCount(2, $dispatchedCollection);
}
public function test_it_writes_to_cache_with_a_dateinterval_ttl()
{
// DateInterval is 1 minute
config()->set('excel.cache.default_ttl', new DateInterval('PT1M'));
$cache = $this->givenCache(['A1' => 'A1-value'], [], 1);
$this->cache->setEventDispatcher(Event::fake());
$cache->set('A2', 'A2-value');
$dispatchedCollection = Event::dispatched(
KeyWritten::class,
function (KeyWritten $event) {
return $event->seconds >= 59 && $event->seconds <= 60;
});
$this->assertCount(2, $dispatchedCollection);
}
public function test_it_can_override_default_ttl()
{
config()->set('excel.cache.default_ttl', 1);
$cache = $this->givenCache(['A1' => 'A1-value'], [], 1);
$this->cache->setEventDispatcher(Event::fake());
$cache->set('A2', 'A2-value', null);
$dispatchedCollection = Event::dispatched(
KeyWritten::class,
function (KeyWritten $event) {
return $event->seconds === null;
});
$this->assertCount(2, $dispatchedCollection);
}
public static function defaultTTLDataProvider(): array
{
return [
'null (forever)' => [null, null],
'int value' => [$value = rand(1, 100), $value],
'callable' => [$closure = function () {
return 199;
}, $closure],
];
}
/**
* Construct a BatchCache with a in memory store
* and an array cache, pretending to be a persistence store.
*
* @param array $memory
* @param array $persisted
* @param int|null $memoryLimit
* @return CacheInterface
*/
private function givenCache(array $memory = [], array $persisted = [], $memoryLimit = null): CacheInterface
{
config()->set('excel.cache.batch.memory_limit', $memoryLimit ?: 60000);
$this->memory = $this->app->make(CacheManager::class)->createMemoryDriver();
$this->memory->setMultiple($memory);
$store = new ArrayStore();
$store->putMany($persisted, 10000);
$this->cache = new Repository($store);
if (!InstalledVersions::satisfies(new VersionParser, 'psr/simple-cache', '^3.0')) {
return new BatchCacheDeprecated(
$this->cache,
$this->memory,
config('excel.cache.default_ttl')
);
}
return new BatchCache(
$this->cache,
$this->memory,
config('excel.cache.default_ttl')
);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/WithLimitTest.php | tests/Concerns/WithLimitTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Illuminate\Database\Eloquent\Model;
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;
use Maatwebsite\Excel\Tests\TestCase;
use PHPUnit\Framework\Assert;
class WithLimitTest extends TestCase
{
/**
* Setup the test environment.
*/
protected function setUp(): void
{
parent::setUp();
$this->loadLaravelMigrations(['--database' => 'testing']);
}
public function test_can_import_a_limited_section_of_rows_to_model_with_different_start_row()
{
$import = new class implements ToModel, WithStartRow, WithLimit
{
use Importable;
/**
* @param array $row
* @return Model
*/
public function model(array $row): Model
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
/**
* @return int
*/
public function startRow(): int
{
return 5;
}
/**
* @return int
*/
public function limit(): int
{
return 1;
}
};
$import->import('import-users-with-different-heading-row.xlsx');
$this->assertDatabaseHas('users', [
'name' => 'Patrick Brouwers',
'email' => 'patrick@maatwebsite.nl',
]);
$this->assertDatabaseMissing('users', [
'name' => 'Taylor Otwell',
'email' => 'taylor@laravel.com',
]);
}
public function test_can_import_to_array_with_limit()
{
$import = new class implements ToArray, WithLimit
{
use Importable;
/**
* @param array $array
*/
public function array(array $array)
{
Assert::assertEquals([
[
'Patrick Brouwers',
'patrick@maatwebsite.nl',
],
], $array);
}
/**
* @return int
*/
public function limit(): int
{
return 1;
}
};
$import->import('import-users.xlsx');
}
public function test_can_import_single_with_heading_row()
{
$import = new class implements ToArray, WithLimit, WithHeadingRow
{
use Importable;
/**
* @param array $array
*/
public function array(array $array)
{
Assert::assertEquals([
[
'name' => 'Patrick Brouwers',
'email' => 'patrick@maatwebsite.nl',
],
], $array);
}
/**
* @return int
*/
public function limit(): int
{
return 1;
}
};
$import->import('import-users-with-headings.xlsx');
}
public function test_can_import_multiple_with_heading_row()
{
$import = new class implements ToArray, WithLimit, WithHeadingRow
{
use Importable;
/**
* @param array $array
*/
public function array(array $array)
{
Assert::assertEquals([
[
'name' => 'Patrick Brouwers',
'email' => 'patrick@maatwebsite.nl',
],
[
'name' => 'Taylor Otwell',
'email' => 'taylor@laravel.com',
],
], $array);
}
/**
* @return int
*/
public function limit(): int
{
return 2;
}
};
$import->import('import-users-with-headings.xlsx');
}
public function test_can_set_limit_bigger_than_row_size()
{
$import = new class implements ToArray, WithLimit
{
use Importable;
/**
* @param array $array
*/
public function array(array $array)
{
Assert::assertCount(2, $array);
}
/**
* @return int
*/
public function limit(): int
{
return 10;
}
};
$import->import('import-users.xlsx');
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/WithColumnFormattingTest.php | tests/Concerns/WithColumnFormattingTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Carbon\Carbon;
use Composer\InstalledVersions;
use Composer\Semver\VersionParser;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Tests\TestCase;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
class WithColumnFormattingTest extends TestCase
{
public function test_can_export_with_column_formatting()
{
$export = new class() implements FromCollection, WithMapping, WithColumnFormatting
{
use Exportable;
/**
* @return Collection
*/
public function collection()
{
return collect([
[Carbon::createFromDate(2018, 3, 6)],
[Carbon::createFromDate(2018, 3, 7)],
[Carbon::createFromDate(2018, 3, 8)],
[Carbon::createFromDate(2021, 12, 6), 100],
]);
}
/**
* @param mixed $row
* @return array
*/
public function map($row): array
{
return [
Date::dateTimeToExcel($row[0]),
isset($row[1]) ? $row[1] : null,
];
}
/**
* @return array
*/
public function columnFormats(): array
{
return [
'A' => NumberFormat::FORMAT_DATE_DDMMYYYY,
'B4:B4' => NumberFormat::FORMAT_CURRENCY_EUR,
];
}
};
$response = $export->store('with-column-formatting-store.xlsx');
$this->assertTrue($response);
$actual = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/with-column-formatting-store.xlsx', 'Xlsx');
$legacyPhpSpreadsheet = !InstalledVersions::satisfies(new VersionParser, 'phpoffice/phpspreadsheet', '^1.28');
$expected = [
['06/03/2018', null],
['07/03/2018', null],
['08/03/2018', null],
['06/12/2021', $legacyPhpSpreadsheet ? '100 €' : '100.00 €'],
];
$this->assertEquals($expected, $actual);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/WithPropertiesTest.php | tests/Concerns/WithPropertiesTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithProperties;
use Maatwebsite\Excel\Tests\TestCase;
class WithPropertiesTest extends TestCase
{
public function test_can_set_custom_document_properties()
{
$export = new class implements WithProperties
{
use Exportable;
public function properties(): array
{
return [
'creator' => 'A',
'lastModifiedBy' => 'B',
'title' => 'C',
'description' => 'D',
'subject' => 'E',
'keywords' => 'F',
'category' => 'G',
'manager' => 'H',
'company' => 'I',
];
}
};
$export->store('with-properties.xlsx');
$spreadsheet = $this->read(__DIR__ . '/../Data/Disks/Local/with-properties.xlsx', 'Xlsx');
$props = $spreadsheet->getProperties();
$this->assertEquals('A', $props->getCreator());
$this->assertEquals('B', $props->getLastModifiedBy());
$this->assertEquals('C', $props->getTitle());
$this->assertEquals('D', $props->getDescription());
$this->assertEquals('E', $props->getSubject());
$this->assertEquals('F', $props->getKeywords());
$this->assertEquals('G', $props->getCategory());
$this->assertEquals('H', $props->getManager());
$this->assertEquals('I', $props->getCompany());
}
public function test_it_merges_with_default_properties()
{
config()->set('excel.exports.properties.title', 'Default Title');
config()->set('excel.exports.properties.description', 'Default Description');
$export = new class implements WithProperties
{
use Exportable;
public function properties(): array
{
return [
'description' => 'Custom Description',
];
}
};
$export->store('with-properties.xlsx');
$spreadsheet = $this->read(__DIR__ . '/../Data/Disks/Local/with-properties.xlsx', 'Xlsx');
$props = $spreadsheet->getProperties();
$this->assertEquals('Default Title', $props->getTitle());
$this->assertEquals('Custom Description', $props->getDescription());
}
public function test_it_ignores_empty_properties()
{
$export = new class implements WithProperties
{
use Exportable;
public function properties(): array
{
return [
'description' => '',
];
}
};
$export->store('with-properties.xlsx');
$spreadsheet = $this->read(__DIR__ . '/../Data/Disks/Local/with-properties.xlsx', 'Xlsx');
$props = $spreadsheet->getProperties();
$this->assertSame('Unknown Creator', $props->getCreator());
$this->assertSame('Untitled Spreadsheet', $props->getTitle());
$this->assertSame('', $props->getDescription());
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/WithStylesTest.php | tests/Concerns/WithStylesTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\WithStyles;
use Maatwebsite\Excel\Tests\TestCase;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class WithStylesTest extends TestCase
{
public function test_can_configure_styles()
{
$export = new class implements FromArray, WithStyles
{
use Exportable;
public function styles(Worksheet $sheet)
{
return [
1 => ['font' => ['italic' => true]],
'B2' => ['font' => ['bold' => true]],
'C' => ['font' => ['size' => 16]],
];
}
public function array(): array
{
return [
['A1', 'B1', 'C1'],
['A2', 'B2', 'C2'],
];
}
};
$export->store('with-styles.xlsx');
$spreadsheet = $this->read(__DIR__ . '/../Data/Disks/Local/with-styles.xlsx', 'Xlsx');
$sheet = $spreadsheet->getActiveSheet();
$this->assertTrue($sheet->getStyle('A1')->getFont()->getItalic());
$this->assertTrue($sheet->getStyle('B1')->getFont()->getItalic());
$this->assertTrue($sheet->getStyle('B2')->getFont()->getBold());
$this->assertFalse($sheet->getStyle('A2')->getFont()->getBold());
$this->assertEquals(16, $sheet->getStyle('C2')->getFont()->getSize());
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/WithConditionalSheetsTest.php | tests/Concerns/WithConditionalSheetsTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\WithConditionalSheets;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Maatwebsite\Excel\Tests\TestCase;
class WithConditionalSheetsTest extends TestCase
{
/**
* Setup the test environment.
*/
protected function setUp(): void
{
parent::setUp();
$this->withFactories(__DIR__ . '/../Data/Stubs/Database/Factories');
}
public function test_can_select_which_sheets_will_be_imported()
{
$import = new class implements WithMultipleSheets
{
use Importable, WithConditionalSheets;
public $sheets = [];
public function __construct()
{
$this->init();
}
public function init()
{
$this->sheets = [
'Sheet1' => new class implements ToArray
{
public $called = false;
public function array(array $array)
{
$this->called = true;
}
},
'Sheet2' => new class implements ToArray
{
public $called = false;
public function array(array $array)
{
$this->called = true;
}
},
];
}
/**
* @return array
*/
public function conditionalSheets(): array
{
return $this->sheets;
}
};
$import->onlySheets('Sheet1')->import('import-multiple-sheets.xlsx');
$this->assertTrue($import->sheets['Sheet1']->called);
$this->assertFalse($import->sheets['Sheet2']->called);
$import->init();
$import->onlySheets('Sheet2')->import('import-multiple-sheets.xlsx');
$this->assertTrue($import->sheets['Sheet2']->called);
$this->assertFalse($import->sheets['Sheet1']->called);
$import->init();
$import->onlySheets(['Sheet1', 'Sheet2'])->import('import-multiple-sheets.xlsx');
$this->assertTrue($import->sheets['Sheet1']->called);
$this->assertTrue($import->sheets['Sheet2']->called);
$import->init();
$import->onlySheets('Sheet1', 'Sheet2')->import('import-multiple-sheets.xlsx');
$this->assertTrue($import->sheets['Sheet1']->called);
$this->assertTrue($import->sheets['Sheet2']->called);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/WithDefaultStylesTest.php | tests/Concerns/WithDefaultStylesTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\WithDefaultStyles;
use Maatwebsite\Excel\Tests\TestCase;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Style;
class WithDefaultStylesTest extends TestCase
{
public function test_can_configure_default_styles()
{
$export = new class implements FromArray, WithDefaultStyles
{
use Exportable;
public function defaultStyles(Style $defaultStyle)
{
return [
'fill' => [
'fillType' => Fill::FILL_SOLID,
'startColor' => ['argb' => 'fff2f2f2'],
],
];
}
public function array(): array
{
return [
['A1', 'B1', 'C1'],
['A2', 'B2', 'C2'],
];
}
};
$export->store('with-default-styles.xlsx');
$spreadsheet = $this->read(__DIR__ . '/../Data/Disks/Local/with-default-styles.xlsx', 'Xlsx');
$sheet = $spreadsheet->getDefaultStyle();
$this->assertEquals(Fill::FILL_SOLID, $sheet->getFill()->getFillType());
$this->assertEquals('fff2f2f2', $sheet->getFill()->getStartColor()->getARGB());
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/WithCalculatedFormulasTest.php | tests/Concerns/WithCalculatedFormulasTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Illuminate\Database\Eloquent\Model;
use Maatwebsite\Excel\Concerns\HasReferencesToOtherSheets;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithCalculatedFormulas;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Maatwebsite\Excel\Tests\TestCase;
use PHPUnit\Framework\Assert;
class WithCalculatedFormulasTest extends TestCase
{
public function test_by_default_does_not_calculate_formulas()
{
$import = new class implements ToArray
{
use Importable;
public $called = false;
/**
* @param array $array
*/
public function array(array $array)
{
$this->called = true;
Assert::assertSame('=1+1', $array[0][0]);
}
};
$import->import('import-formulas.xlsx');
$this->assertTrue($import->called);
}
public function test_can_import_to_array_with_calculated_formulas()
{
$import = new class implements ToArray, WithCalculatedFormulas
{
use Importable;
public $called = false;
/**
* @param array $array
*/
public function array(array $array)
{
$this->called = true;
Assert::assertSame(2, $array[0][0]);
}
};
$import->import('import-formulas.xlsx');
$this->assertTrue($import->called);
}
public function test_can_import_to_model_with_calculated_formulas()
{
$import = new class implements ToModel, WithCalculatedFormulas
{
use Importable;
public $called = false;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
$this->called = true;
Assert::assertSame(2, $row[0]);
return null;
}
};
$import->import('import-formulas.xlsx');
$this->assertTrue($import->called);
}
public function can_import_with_formulas_and_reference()
{
$import = new class implements ToModel, WithCalculatedFormulas, WithStartRow
{
use Importable;
public $called = false;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
$this->called = true;
Assert::assertSame('julien', $row[1]);
return null;
}
public function startRow(): int
{
return 2;
}
};
$import->import('import-external-reference.xls');
$this->assertTrue($import->called);
}
public function test_can_import_to_array_with_calculated_formulas_and_multi_sheet_references()
{
$import = new class implements WithMultipleSheets, HasReferencesToOtherSheets
{
use Importable;
public $test = 'test1';
public function sheets(): array
{
return [
new class implements ToArray, HasReferencesToOtherSheets
{
public $test = 'test2';
public function array(array $array)
{
Assert::assertEquals([
['1', '1'],
], $array);
}
},
new class implements ToArray, WithCalculatedFormulas, HasReferencesToOtherSheets
{
public $test = 'test2';
public function array(array $array)
{
Assert::assertEquals([
['2'],
], $array);
}
},
];
}
};
$import->import('import-formulas-multiple-sheets.xlsx');
}
public function test_can_import_to_array_with_calculated_formulas_and_skips_empty()
{
$import = new class implements ToArray, WithCalculatedFormulas, SkipsEmptyRows
{
use Importable;
public $called = false;
/**
* @param array $array
*/
public function array(array $array)
{
$this->called = true;
Assert::assertSame(2, $array[0][0]);
}
};
$import->import('import-formulas.xlsx');
$this->assertTrue($import->called);
}
public function test_can_import_to_model_with_calculated_formulas_and_skips_empty()
{
$import = new class implements ToModel, WithCalculatedFormulas, SkipsEmptyRows
{
use Importable;
public $called = false;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
$this->called = true;
Assert::assertSame(2, $row[0]);
return null;
}
};
$import->import('import-formulas.xlsx');
$this->assertTrue($import->called);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/WithFormatDataTest.php | tests/Concerns/WithFormatDataTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithFormatData;
use Maatwebsite\Excel\Tests\TestCase;
use PHPUnit\Framework\Assert;
class WithFormatDataTest extends TestCase
{
public function test_by_default_import_to_array()
{
$import = new class implements ToArray
{
use Importable;
public $called = false;
/**
* @param array $array
*/
public function array(array $array)
{
$this->called = true;
Assert::assertSame(44328, $array[0][0]);
}
};
$import->import('import-format-data.xlsx');
$this->assertTrue($import->called);
}
public function test_can_import_to_array_with_format_data()
{
config()->set('excel.imports.read_only', false);
$import = new class implements ToArray, WithFormatData
{
use Importable;
public $called = false;
/**
* @param array $array
*/
public function array(array $array)
{
$this->called = true;
Assert::assertSame('5/12/2021', $array[0][0]);
}
};
$import->import('import-format-data.xlsx');
$this->assertTrue($import->called);
}
public function test_can_import_to_array_with_format_data_and_skips_empty_rows()
{
config()->set('excel.imports.read_only', false);
$import = new class implements ToArray, WithFormatData, SkipsEmptyRows
{
use Importable;
public $called = false;
/**
* @param array $array
*/
public function array(array $array)
{
$this->called = true;
Assert::assertSame('5/12/2021', $array[0][0]);
}
};
$import->import('import-format-data.xlsx');
$this->assertTrue($import->called);
}
public function test_by_default_import_to_collection()
{
$import = new class implements ToCollection
{
use Importable;
public $called = false;
/**
* @param array $row
* @return Model|null
*/
public function collection(collection $collection)
{
$this->called = true;
Assert::assertSame(44328, $collection[0][0]);
return null;
}
};
$import->import('import-format-data.xlsx');
$this->assertTrue($import->called);
}
public function test_can_import_to_collection_with_format_data()
{
config()->set('excel.imports.read_only', false);
$import = new class implements ToCollection, WithFormatData
{
use Importable;
public $called = false;
/**
* @param array $row
* @return Model|null
*/
public function collection(collection $collection)
{
$this->called = true;
Assert::assertSame('5/12/2021', $collection[0][0]);
return null;
}
};
$import->import('import-format-data.xlsx');
$this->assertTrue($import->called);
}
public function test_by_default_import_to_model()
{
$import = new class implements ToModel
{
use Importable;
public $called = false;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
$this->called = true;
Assert::assertSame(44328, $row[0]);
return null;
}
};
$import->import('import-format-data.xlsx');
$this->assertTrue($import->called);
}
public function test_can_import_to_model_with_format_data()
{
config()->set('excel.imports.read_only', false);
$import = new class implements ToModel, WithFormatData
{
use Importable;
public $called = false;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
$this->called = true;
Assert::assertSame('5/12/2021', $row[0]);
return null;
}
};
$import->import('import-format-data.xlsx');
$this->assertTrue($import->called);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/WithColumnWidthsTest.php | tests/Concerns/WithColumnWidthsTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\WithColumnWidths;
use Maatwebsite\Excel\Tests\TestCase;
class WithColumnWidthsTest extends TestCase
{
public function test_can_set_column_width()
{
$export = new class implements FromArray, WithColumnWidths
{
use Exportable;
public function columnWidths(): array
{
return [
'A' => 55,
];
}
public function array(): array
{
return [
['AA'],
['BB'],
];
}
};
$export->store('with-column-widths.xlsx');
$spreadsheet = $this->read(__DIR__ . '/../Data/Disks/Local/with-column-widths.xlsx', 'Xlsx');
$this->assertEquals(55, $spreadsheet->getActiveSheet()->getColumnDimension('A')->getWidth());
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/WithTitleTest.php | tests/Concerns/WithTitleTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Maatwebsite\Excel\Concerns\WithTitle;
use Maatwebsite\Excel\Tests\Data\Stubs\WithTitleExport;
use Maatwebsite\Excel\Tests\TestCase;
class WithTitleTest extends TestCase
{
public function test_can_export_with_title()
{
$export = new WithTitleExport();
$response = $export->store('with-title-store.xlsx');
$this->assertTrue($response);
$spreadsheet = $this->read(__DIR__ . '/../Data/Disks/Local/with-title-store.xlsx', 'Xlsx');
$this->assertEquals('given-title', $spreadsheet->getProperties()->getTitle());
$this->assertEquals('given-title', $spreadsheet->getActiveSheet()->getTitle());
}
public function test_can_export_sheet_title_when_longer_than_max_length()
{
$export = new class implements WithTitle, WithMultipleSheets
{
use Exportable;
/**
* @return string
*/
public function title(): string
{
return '12/3456789123/45678912345/678912345/6789';
}
public function sheets(): array
{
return [$this];
}
};
$response = $export->store('with-title-store.xlsx');
$this->assertTrue($response);
$spreadsheet = $this->read(__DIR__ . '/../Data/Disks/Local/with-title-store.xlsx', 'Xlsx');
$this->assertEquals('12/3456789123/45678912345/678912345/6789', $spreadsheet->getProperties()->getTitle());
$this->assertEquals('1234567891234567891234567891234', $spreadsheet->getActiveSheet()->getTitle());
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/RemembersChunkOffsetTest.php | tests/Concerns/RemembersChunkOffsetTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\RemembersChunkOffset;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Tests\TestCase;
class RemembersChunkOffsetTest extends TestCase
{
public function test_can_set_and_get_chunk_offset()
{
$import = new class
{
use Importable;
use RemembersChunkOffset;
};
$import->setChunkOffset(50);
$this->assertEquals(50, $import->getChunkOffset());
}
public function test_can_access_chunk_offset_on_import_to_array_in_chunks()
{
$import = new class implements ToArray, WithChunkReading
{
use Importable;
use RemembersChunkOffset;
public $offsets = [];
public function array(array $array)
{
$this->offsets[] = $this->getChunkOffset();
}
public function chunkSize(): int
{
return 2000;
}
};
$import->import('import-batches.xlsx');
$this->assertEquals([1, 2001, 4001], $import->offsets);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/FromArrayTest.php | tests/Concerns/FromArrayTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Tests\TestCase;
class FromArrayTest extends TestCase
{
public function test_can_export_from_array()
{
$export = new class implements FromArray
{
use Exportable;
/**
* @return array
*/
public function array(): array
{
return [
['test', 'test'],
['test', 'test'],
];
}
};
$response = $export->store('from-array-store.xlsx');
$this->assertTrue($response);
$contents = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/from-array-store.xlsx', 'Xlsx');
$this->assertEquals($export->array(), $contents);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/WithSkipDuplicatesTest.php | tests/Concerns/WithSkipDuplicatesTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Maatwebsite\Excel\Concerns\WithSkipDuplicates;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
use Maatwebsite\Excel\Tests\TestCase;
class WithSkipDuplicatesTest extends TestCase
{
/**
* Setup the test environment.
*/
protected function setUp(): void
{
parent::setUp();
$this->loadLaravelMigrations(['--database' => 'testing']);
}
public function test_can_skip_duplicate_models_in_batches()
{
User::create([
'name' => 'Funny Banana',
'email' => 'patrick@maatwebsite.nl',
'password' => 'password',
]);
DB::connection()->enableQueryLog();
$import = new class implements ToModel, WithBatchInserts, WithSkipDuplicates
{
use Importable;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
/**
* @return string|array
*/
public function uniqueBy()
{
return 'email';
}
/**
* @return int
*/
public function batchSize(): int
{
return 2;
}
};
$import->import('import-users.xlsx');
$this->assertCount(1, DB::getQueryLog());
DB::connection()->disableQueryLog();
$this->assertDatabaseHas('users', [
'name' => 'Funny Banana',
'email' => 'patrick@maatwebsite.nl',
'password' => 'password',
]);
$this->assertDatabaseHas('users', [
'name' => 'Taylor Otwell',
'email' => 'taylor@laravel.com',
'password' => 'secret',
]);
$this->assertEquals(2, User::count());
}
public function test_can_skip_duplicate_models_in_rows()
{
User::create([
'name' => 'Funny Potato',
'email' => 'patrick@maatwebsite.nl',
'password' => 'password',
]);
DB::connection()->enableQueryLog();
$import = new class implements ToModel, WithSkipDuplicates
{
use Importable;
/**
* @param array $row
* @return Model|Model[]|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
/**
* @return string|array
*/
public function uniqueBy()
{
return 'email';
}
};
$import->import('import-users.xlsx');
$this->assertCount(2, DB::getQueryLog());
DB::connection()->disableQueryLog();
$this->assertDatabaseHas('users', [
'name' => 'Funny Potato',
'email' => 'patrick@maatwebsite.nl',
'password' => 'password',
]);
$this->assertDatabaseHas('users', [
'name' => 'Taylor Otwell',
'email' => 'taylor@laravel.com',
'password' => 'secret',
]);
$this->assertEquals(2, User::count());
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/FromViewTest.php | tests/Concerns/FromViewTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromView;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
use Maatwebsite\Excel\Tests\Data\Stubs\SheetForUsersFromView;
use Maatwebsite\Excel\Tests\TestCase;
class FromViewTest extends TestCase
{
/**
* Setup the test environment.
*/
protected function setUp(): void
{
parent::setUp();
$this->withFactories(__DIR__ . '/../Data/Stubs/Database/Factories');
}
public function test_can_export_from_view()
{
/** @var Collection|User[] $users */
$users = factory(User::class)->times(100)->make();
$export = new class($users) implements FromView
{
use Exportable;
/**
* @var Collection
*/
protected $users;
/**
* @param Collection $users
*/
public function __construct(Collection $users)
{
$this->users = $users;
}
/**
* @return View
*/
public function view(): View
{
return view('users', [
'users' => $this->users,
]);
}
};
$response = $export->store('from-view.xlsx');
$this->assertTrue($response);
$contents = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/from-view.xlsx', 'Xlsx');
$expected = $users->map(function (User $user) {
return [
$user->name,
$user->email,
];
})->prepend(['Name', 'Email'])->toArray();
$this->assertEquals($expected, $contents);
}
public function test_can_export_multiple_sheets_from_view()
{
/** @var Collection|User[] $users */
$users = factory(User::class)->times(300)->make();
$export = new class($users) implements WithMultipleSheets
{
use Exportable;
/**
* @var Collection
*/
protected $users;
/**
* @param Collection $users
*/
public function __construct(Collection $users)
{
$this->users = $users;
}
/**
* @return SheetForUsersFromView[]
*/
public function sheets(): array
{
return [
new SheetForUsersFromView($this->users->forPage(1, 100)),
new SheetForUsersFromView($this->users->forPage(2, 100)),
new SheetForUsersFromView($this->users->forPage(3, 100)),
];
}
};
$response = $export->store('from-multiple-view.xlsx');
$this->assertTrue($response);
$contents = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/from-multiple-view.xlsx', 'Xlsx', 0);
$expected = $users->forPage(1, 100)->map(function (User $user) {
return [
$user->name,
$user->email,
];
})->prepend(['Name', 'Email'])->toArray();
$this->assertEquals(101, sizeof($contents));
$this->assertEquals($expected, $contents);
$contents = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/from-multiple-view.xlsx', 'Xlsx', 2);
$expected = $users->forPage(3, 100)->map(function (User $user) {
return [
$user->name,
$user->email,
];
})->prepend(['Name', 'Email'])->toArray();
$this->assertEquals(101, sizeof($contents));
$this->assertEquals($expected, $contents);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/WithEventsTest.php | tests/Concerns/WithEventsTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Support\Str;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Events\AfterBatch;
use Maatwebsite\Excel\Events\AfterChunk;
use Maatwebsite\Excel\Events\AfterImport;
use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Events\BeforeExport;
use Maatwebsite\Excel\Events\BeforeImport;
use Maatwebsite\Excel\Events\BeforeSheet;
use Maatwebsite\Excel\Events\BeforeWriting;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Reader;
use Maatwebsite\Excel\Sheet;
use Maatwebsite\Excel\Tests\Data\Stubs\BeforeExportListener;
use Maatwebsite\Excel\Tests\Data\Stubs\CustomConcern;
use Maatwebsite\Excel\Tests\Data\Stubs\CustomSheetConcern;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
use Maatwebsite\Excel\Tests\Data\Stubs\ExportWithEvents;
use Maatwebsite\Excel\Tests\Data\Stubs\ExportWithEventsChunks;
use Maatwebsite\Excel\Tests\Data\Stubs\ImportWithEvents;
use Maatwebsite\Excel\Tests\Data\Stubs\ImportWithEventsChunksAndBatches;
use Maatwebsite\Excel\Tests\TestCase;
use Maatwebsite\Excel\Writer;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
class WithEventsTest extends TestCase
{
use WithFaker;
public function test_export_events_get_called()
{
$event = new ExportWithEvents();
$eventsTriggered = 0;
$event->beforeExport = function ($event) use (&$eventsTriggered) {
$this->assertInstanceOf(BeforeExport::class, $event);
$this->assertInstanceOf(Writer::class, $event->getWriter());
$eventsTriggered++;
};
$event->beforeWriting = function ($event) use (&$eventsTriggered) {
$this->assertInstanceOf(BeforeWriting::class, $event);
$this->assertInstanceOf(Writer::class, $event->getWriter());
$eventsTriggered++;
};
$event->beforeSheet = function ($event) use (&$eventsTriggered) {
$this->assertInstanceOf(BeforeSheet::class, $event);
$this->assertInstanceOf(Sheet::class, $event->getSheet());
$eventsTriggered++;
};
$event->afterSheet = function ($event) use (&$eventsTriggered) {
$this->assertInstanceOf(AfterSheet::class, $event);
$this->assertInstanceOf(Sheet::class, $event->getSheet());
$eventsTriggered++;
};
$this->assertInstanceOf(BinaryFileResponse::class, $event->download('filename.xlsx'));
$this->assertEquals(4, $eventsTriggered);
}
public function test_import_events_get_called()
{
$import = new ImportWithEvents();
$eventsTriggered = 0;
$import->beforeImport = function ($event) use (&$eventsTriggered) {
$this->assertInstanceOf(BeforeImport::class, $event);
$this->assertInstanceOf(Reader::class, $event->getReader());
$eventsTriggered++;
};
$import->afterImport = function ($event) use (&$eventsTriggered) {
$this->assertInstanceOf(AfterImport::class, $event);
$this->assertInstanceOf(Reader::class, $event->getReader());
$eventsTriggered++;
};
$import->beforeSheet = function ($event) use (&$eventsTriggered) {
$this->assertInstanceOf(BeforeSheet::class, $event);
$this->assertInstanceOf(Sheet::class, $event->getSheet());
$eventsTriggered++;
};
$import->afterSheet = function ($event) use (&$eventsTriggered) {
$this->assertInstanceOf(AfterSheet::class, $event);
$this->assertInstanceOf(Sheet::class, $event->getSheet());
$eventsTriggered++;
};
$import->import('import.xlsx');
$this->assertEquals(4, $eventsTriggered);
}
public function test_import_chunked_events_get_called()
{
$import = new ImportWithEventsChunksAndBatches();
$beforeImport = 0;
$afterImport = 0;
$beforeSheet = 0;
$afterSheet = 0;
$afterBatch = 0;
$afterChunk = 0;
$import->beforeImport = function (BeforeImport $event) use (&$beforeImport) {
$this->assertInstanceOf(Reader::class, $event->getReader());
// Ensure event is fired only once
$this->assertEquals(0, $beforeImport, 'Before import called twice');
$beforeImport++;
};
$import->afterImport = function (AfterImport $event) use (&$afterImport) {
$this->assertInstanceOf(Reader::class, $event->getReader());
$this->assertEquals(0, $afterImport, 'After import called twice');
$afterImport++;
};
$import->beforeSheet = function (BeforeSheet $event) use (&$beforeSheet) {
$this->assertInstanceOf(Sheet::class, $event->getSheet());
$beforeSheet++;
};
$import->afterSheet = function (AfterSheet $event) use (&$afterSheet) {
$this->assertInstanceOf(Sheet::class, $event->getSheet());
$afterSheet++;
};
$import->afterBatch = function (AfterBatch $event) use ($import, &$afterBatch) {
$this->assertEquals(
$import->batchSize(),
$event->getBatchSize(),
'Wrong Batch size'
);
$this->assertEquals(
$afterBatch * $import->batchSize() + 1,
$event->getStartRow(),
'Wrong batch start row');
$afterBatch++;
};
$import->afterChunk = function (AfterChunk $event) use ($import, &$afterChunk) {
$this->assertEquals(
$event->getStartRow(),
$afterChunk * $import->chunkSize() + 1,
'Wrong chunk start row');
$afterChunk++;
};
$import->import('import-batches.xlsx');
$this->assertEquals(10, $afterSheet);
$this->assertEquals(10, $beforeSheet);
$this->assertEquals(50, $afterBatch);
$this->assertEquals(10, $afterChunk);
}
public function test_can_have_invokable_class_as_listener()
{
$event = new ExportWithEvents();
$event->beforeExport = new BeforeExportListener(function ($event) {
$this->assertInstanceOf(BeforeExport::class, $event);
$this->assertInstanceOf(Writer::class, $event->getWriter());
});
$this->assertInstanceOf(BinaryFileResponse::class, $event->download('filename.xlsx'));
}
public function test_can_have_global_event_listeners()
{
$event = new class
{
use Exportable;
};
$beforeExport = false;
Writer::listen(BeforeExport::class, function () use (&$beforeExport) {
$beforeExport = true;
});
$beforeWriting = false;
Writer::listen(BeforeWriting::class, function () use (&$beforeWriting) {
$beforeWriting = true;
});
$beforeSheet = false;
Sheet::listen(BeforeSheet::class, function () use (&$beforeSheet) {
$beforeSheet = true;
});
$afterSheet = false;
Sheet::listen(AfterSheet::class, function () use (&$afterSheet) {
$afterSheet = true;
});
$this->assertInstanceOf(BinaryFileResponse::class, $event->download('filename.xlsx'));
$this->assertTrue($beforeExport, 'Before export event not triggered');
$this->assertTrue($beforeWriting, 'Before writing event not triggered');
$this->assertTrue($beforeSheet, 'Before sheet event not triggered');
$this->assertTrue($afterSheet, 'After sheet event not triggered');
}
public function test_can_have_custom_concern_handlers()
{
// Add a custom concern handler for the given concern.
Excel::extend(CustomConcern::class, function (CustomConcern $exportable, Writer $writer) {
$writer->getSheetByIndex(0)->append(
$exportable->custom()
);
});
$exportWithConcern = new class implements CustomConcern
{
use Exportable;
public function custom()
{
return [
['a', 'b'],
];
}
};
$exportWithConcern->store('with-custom-concern.xlsx');
$actual = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/with-custom-concern.xlsx', 'Xlsx');
$this->assertEquals([
['a', 'b'],
], $actual);
$exportWithoutConcern = new class
{
use Exportable;
};
$exportWithoutConcern->store('without-custom-concern.xlsx');
$actual = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/without-custom-concern.xlsx', 'Xlsx');
$this->assertEquals([[null]], $actual);
}
public function test_can_have_custom_sheet_concern_handlers()
{
// Add a custom concern handler for the given concern.
Excel::extend(CustomSheetConcern::class, function (CustomSheetConcern $exportable, Sheet $sheet) {
$sheet->append(
$exportable->custom()
);
}, AfterSheet::class);
$exportWithConcern = new class implements CustomSheetConcern
{
use Exportable;
public function custom()
{
return [
['c', 'd'],
];
}
};
$exportWithConcern->store('with-custom-concern.xlsx');
$actual = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/with-custom-concern.xlsx', 'Xlsx');
$this->assertEquals([
['c', 'd'],
], $actual);
$exportWithoutConcern = new class
{
use Exportable;
};
$exportWithoutConcern->store('without-custom-concern.xlsx');
$actual = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/without-custom-concern.xlsx', 'Xlsx');
$this->assertEquals([[null]], $actual);
}
public function test_export_chunked_events_get_called()
{
$this->loadLaravelMigrations(['--database' => 'testing']);
User::query()->truncate();
User::query()->create([
'name' => $this->faker->name,
'email' => $this->faker->unique()->safeEmail,
'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
'remember_token' => Str::random(10),
]);
User::query()->create([
'name' => $this->faker->name,
'email' => $this->faker->unique()->safeEmail,
'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
'remember_token' => Str::random(10),
]);
$export = new ExportWithEventsChunks();
$export->queue('filename.xlsx');
// Chunk size is 1, so we expect 2 chunks to be executed with a total of 2 users
$this->assertEquals(2, ExportWithEventsChunks::$calledEvent);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/RemembersRowNumberTest.php | tests/Concerns/RemembersRowNumberTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\RemembersRowNumber;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Tests\TestCase;
class RemembersRowNumberTest extends TestCase
{
public function test_can_set_and_get_row_number()
{
$import = new class
{
use Importable;
use RemembersRowNumber;
};
$import->rememberRowNumber(50);
$this->assertEquals(50, $import->getRowNumber());
}
public function test_can_access_row_number_on_import_to_model()
{
$import = new class implements ToModel
{
use Importable;
use RemembersRowNumber;
public $rowNumbers = [];
public function model(array $row)
{
$this->rowNumbers[] = $this->getRowNumber();
}
};
$import->import('import-batches.xlsx');
$this->assertEquals([46, 47, 48, 49, 50, 51, 52, 53, 54, 55], array_slice($import->rowNumbers, 45, 10));
}
public function test_can_access_row_number_on_import_to_array_in_chunks()
{
$import = new class implements ToModel, WithChunkReading
{
use Importable;
use RemembersRowNumber;
public $rowNumbers = [];
public function chunkSize(): int
{
return 50;
}
public function model(array $row)
{
$this->rowNumbers[] = $this->getRowNumber();
}
};
$import->import('import-batches.xlsx');
$this->assertEquals([46, 47, 48, 49, 50, 51, 52, 53, 54, 55], array_slice($import->rowNumbers, 45, 10));
}
public function test_can_access_row_number_on_import_to_array_in_chunks_with_batch_inserts()
{
$import = new class implements ToModel, WithChunkReading, WithBatchInserts
{
use Importable;
use RemembersRowNumber;
public $rowNumbers = [];
public function chunkSize(): int
{
return 50;
}
public function model(array $row)
{
$this->rowNumbers[] = $this->rowNumber;
}
public function batchSize(): int
{
return 50;
}
};
$import->import('import-batches.xlsx');
$this->assertEquals([46, 47, 48, 49, 50, 51, 52, 53, 54, 55], array_slice($import->rowNumbers, 45, 10));
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/ToModelTest.php | tests/Concerns/ToModelTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Faker\Factory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\PersistRelations;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\Group;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
use Maatwebsite\Excel\Tests\TestCase;
class ToModelTest extends TestCase
{
/**
* Setup the test environment.
*/
protected function setUp(): void
{
parent::setUp();
$this->loadLaravelMigrations(['--database' => 'testing']);
$this->loadMigrationsFrom(dirname(__DIR__) . '/Data/Stubs/Database/Migrations');
}
public function test_can_import_each_row_to_model()
{
DB::connection()->enableQueryLog();
$import = new class implements ToModel
{
use Importable;
/**
* @param array $row
* @return Model|Model[]|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
};
$import->import('import-users.xlsx');
$this->assertCount(2, DB::getQueryLog());
DB::connection()->disableQueryLog();
$this->assertDatabaseHas('users', [
'name' => 'Patrick Brouwers',
'email' => 'patrick@maatwebsite.nl',
]);
$this->assertDatabaseHas('users', [
'name' => 'Taylor Otwell',
'email' => 'taylor@laravel.com',
]);
}
public function test_has_timestamps_when_imported_single_model()
{
$import = new class implements ToModel
{
use Importable;
/**
* @param array $row
* @return Model|Model[]|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
};
$import->import('import-users.xlsx');
$user = User::first();
$this->assertNotNull($user->created_at);
$this->assertNotNull($user->updated_at);
}
public function test_can_import_multiple_models_in_single_to_model()
{
DB::connection()->enableQueryLog();
$import = new class implements ToModel
{
use Importable;
/**
* @param array $row
* @return Model|Model[]|null
*/
public function model(array $row)
{
$user1 = new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
$faker = Factory::create();
$user2 = new User([
'name' => $faker->name,
'email' => $faker->email,
'password' => 'secret',
]);
return [$user1, $user2];
}
};
$import->import('import-users.xlsx');
$this->assertCount(4, DB::getQueryLog());
DB::connection()->disableQueryLog();
}
public function test_can_import_multiple_different_types_of_models_in_single_to_model()
{
DB::connection()->enableQueryLog();
$import = new class implements ToModel
{
use Importable;
/**
* @param array $row
* @return Model|Model[]|null
*/
public function model(array $row)
{
$user = new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
$group = new Group([
'name' => $row[0],
]);
return [$user, $group];
}
};
$import->import('import-users.xlsx');
$this->assertCount(4, DB::getQueryLog());
$this->assertEquals(2, User::count());
$this->assertEquals(2, Group::count());
DB::connection()->disableQueryLog();
}
public function test_can_import_models_with_belongs_to_relations()
{
User::query()->truncate();
Group::query()->truncate();
DB::connection()->enableQueryLog();
$import = new class implements ToModel, PersistRelations
{
use Importable;
/**
* @param array $row
* @return Model|Model[]|null
*/
public function model(array $row)
{
$user = new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
$user->group()->associate(
new Group([
'name' => $row[0],
])
);
return $user;
}
};
$import->import('import-users.xlsx');
$this->assertCount(6, DB::getQueryLog());
$users = User::all();
$users->each(function (User $user) {
$this->assertInstanceOf(Group::class, $user->group);
$this->assertIsInt($user->group->id);
});
$this->assertCount(2, $users);
$this->assertEquals(2, Group::count());
DB::connection()->disableQueryLog();
}
public function test_can_import_models_with_belongs_to_many_relations()
{
User::query()->truncate();
Group::query()->truncate();
DB::connection()->enableQueryLog();
$import = new class implements ToModel, PersistRelations
{
use Importable;
/**
* @param array $row
* @return Model|Model[]|null
*/
public function model(array $row)
{
$user = new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
$user->setRelation('groups', new Collection([
new Group([
'name' => $row[0],
]),
]));
return $user;
}
};
$import->import('import-users.xlsx');
$this->assertCount(6, DB::getQueryLog());
$users = User::all();
$users->each(function (User $user) {
$this->assertInstanceOf(Group::class, $user->groups->first());
});
$this->assertCount(2, $users);
$this->assertEquals(2, Group::count());
DB::connection()->disableQueryLog();
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/SkipsOnFailureTest.php | tests/Concerns/SkipsOnFailureTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Validation\Rule;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\OnEachRow;
use Maatwebsite\Excel\Concerns\SkipsFailures;
use Maatwebsite\Excel\Concerns\SkipsOnFailure;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Maatwebsite\Excel\Concerns\WithValidation;
use Maatwebsite\Excel\Row;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
use Maatwebsite\Excel\Tests\TestCase;
use Maatwebsite\Excel\Validators\Failure;
use PHPUnit\Framework\Assert;
class SkipsOnFailureTest extends TestCase
{
/**
* Setup the test environment.
*/
protected function setUp(): void
{
parent::setUp();
$this->loadLaravelMigrations(['--database' => 'testing']);
}
public function test_can_skip_on_error()
{
$import = new class implements ToModel, WithValidation, SkipsOnFailure
{
use Importable;
public $failures = 0;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
/**
* @return array
*/
public function rules(): array
{
return [
'1' => Rule::in(['patrick@maatwebsite.nl']),
];
}
/**
* @param Failure[] $failures
*/
public function onFailure(Failure ...$failures)
{
$failure = $failures[0];
Assert::assertEquals(2, $failure->row());
Assert::assertEquals('1', $failure->attribute());
Assert::assertEquals(['The selected 1 is invalid.'], $failure->errors());
Assert::assertEquals(['Taylor Otwell', 'taylor@laravel.com'], $failure->values());
Assert::assertEquals(2, $failure->jsonSerialize()['row']);
Assert::assertEquals('1', $failure->jsonSerialize()['attribute']);
Assert::assertEquals(['The selected 1 is invalid.'], $failure->jsonSerialize()['errors']);
Assert::assertEquals(['Taylor Otwell', 'taylor@laravel.com'], $failure->jsonSerialize()['values']);
$this->failures += \count($failures);
}
};
$import->import('import-users.xlsx');
$this->assertEquals(1, $import->failures);
// Shouldn't have rollbacked other imported rows.
$this->assertDatabaseHas('users', [
'email' => 'patrick@maatwebsite.nl',
]);
// Should have skipped inserting
$this->assertDatabaseMissing('users', [
'email' => 'taylor@laravel.com',
]);
}
public function test_skips_only_failed_rows_in_batch()
{
$import = new class implements ToModel, WithValidation, WithBatchInserts, SkipsOnFailure
{
use Importable;
public $failures = 0;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
/**
* @return array
*/
public function rules(): array
{
return [
'1' => Rule::in(['patrick@maatwebsite.nl']),
];
}
/**
* @param Failure[] $failures
*/
public function onFailure(Failure ...$failures)
{
$failure = $failures[0];
Assert::assertEquals(2, $failure->row());
Assert::assertEquals('1', $failure->attribute());
Assert::assertEquals(['The selected 1 is invalid.'], $failure->errors());
$this->failures += \count($failures);
}
/**
* @return int
*/
public function batchSize(): int
{
return 100;
}
};
$import->import('import-users.xlsx');
$this->assertEquals(1, $import->failures);
// Shouldn't have rollbacked/skipped the rest of the batch.
$this->assertDatabaseHas('users', [
'email' => 'patrick@maatwebsite.nl',
]);
// Should have skipped inserting
$this->assertDatabaseMissing('users', [
'email' => 'taylor@laravel.com',
]);
}
public function test_can_skip_failures_and_collect_all_failures_at_the_end()
{
$import = new class implements ToModel, WithValidation, SkipsOnFailure
{
use Importable, SkipsFailures;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
/**
* @return array
*/
public function rules(): array
{
return [
'1' => Rule::in(['patrick@maatwebsite.nl']),
];
}
};
$import->import('import-users.xlsx');
$this->assertCount(1, $import->failures());
/** @var Failure $failure */
$failure = $import->failures()->first();
$this->assertEquals(2, $failure->row());
$this->assertEquals('1', $failure->attribute());
$this->assertEquals(['The selected 1 is invalid.'], $failure->errors());
// Shouldn't have rollbacked other imported rows.
$this->assertDatabaseHas('users', [
'email' => 'patrick@maatwebsite.nl',
]);
// Should have skipped inserting
$this->assertDatabaseMissing('users', [
'email' => 'taylor@laravel.com',
]);
}
public function test_can_validate_using_oneachrow_and_skipsonfailure()
{
$import = new class implements OnEachRow, WithValidation, SkipsOnFailure
{
use Importable, SkipsFailures;
/**
* @param Row $row
* @return Model|null
*/
public function onRow(Row $row)
{
$row = $row->toArray();
return User::create([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
/**
* @return array
*/
public function rules(): array
{
return [
'1' => Rule::in(['patrick@maatwebsite.nl']),
];
}
};
$this->assertEmpty(User::all());
$import->import('import-users.xlsx');
$this->assertCount(1, $import->failures());
// Shouldn't have rollbacked other imported rows.
$this->assertDatabaseHas('users', [
'email' => 'patrick@maatwebsite.nl',
]);
// Should have skipped inserting
$this->assertDatabaseMissing('users', [
'email' => 'taylor@laravel.com',
]);
}
public function test_can_validate_using_tocollection_and_skipsonfailure()
{
$import = new class implements ToCollection, WithValidation, SkipsOnFailure
{
use Importable, SkipsFailures;
/**
* @param Row $row
* @return Model|null
*/
public function collection(Collection $rows)
{
$rows = $rows->each(function ($row) {
return User::create([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
});
}
/**
* @return array
*/
public function rules(): array
{
return [
'1' => Rule::in(['patrick@maatwebsite.nl']),
];
}
};
$this->assertEmpty(User::all());
$import->import('import-users.xlsx');
$this->assertCount(1, $import->failures());
// Shouldn't have rollbacked other imported rows.
$this->assertDatabaseHas('users', [
'email' => 'patrick@maatwebsite.nl',
]);
// Should have skipped inserting
$this->assertDatabaseMissing('users', [
'email' => 'taylor@laravel.com',
]);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/ShouldQueueWithoutChainTest.php | tests/Concerns/ShouldQueueWithoutChainTest.php | <?php
use Illuminate\Queue\Events\JobProcessed;
use Illuminate\Queue\SyncQueue;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Queue;
use Maatwebsite\Excel\Jobs\AfterImportJob;
use Maatwebsite\Excel\Jobs\QueueImport;
use Maatwebsite\Excel\Jobs\ReadChunk;
use Maatwebsite\Excel\Tests\Data\Stubs\QueueImportWithoutJobChaining;
use Maatwebsite\Excel\Tests\TestCase;
class ShouldQueueWithoutChainTest extends TestCase
{
/**
* Setup the test environment.
*/
protected function setUp(): void
{
parent::setUp();
$this->loadLaravelMigrations(['--database' => 'testing']);
$this->loadMigrationsFrom(dirname(__DIR__) . '/Data/Stubs/Database/Migrations');
}
public function test_can_import_to_model_in_chunks()
{
DB::connection()->enableQueryLog();
$import = new QueueImportWithoutJobChaining();
$import->import('import-users.xlsx');
$this->assertCount(2, DB::getQueryLog());
DB::connection()->disableQueryLog();
}
public function test_can_import_to_model_without_job_chaining()
{
Queue::fake();
$import = new QueueImportWithoutJobChaining();
$import->import('import-users.xlsx');
Queue::assertPushed(ReadChunk::class, 2);
Queue::assertPushed(AfterImportJob::class, 1);
Queue::assertPushed(AfterImportJob::class, function ($import) {
return !is_null($import->delay);
});
Queue::assertNotPushed(QueueImport::class);
}
public function test_a_queue_name_can_be_specified_when_importing()
{
Queue::fake();
$import = new QueueImportWithoutJobChaining();
$import->queue = 'queue-name';
$import->import('import-users.xlsx');
Queue::assertPushedOn('queue-name', ReadChunk::class);
Queue::assertPushedOn('queue-name', AfterImportJob::class);
}
public function test_the_cleanup_only_runs_when_all_jobs_are_done()
{
$fake = Queue::fake();
if (method_exists($fake, 'serializeAndRestore')) {
$fake->serializeAndRestore(); // More realism
}
$import = new QueueImportWithoutJobChaining();
$import->import('import-users.xlsx');
$jobs = Queue::pushedJobs();
$chunks = collect($jobs[ReadChunk::class])->pluck('job');
$chunks->each(function (ReadChunk $chunk) {
self::assertFalse(ReadChunk::isComplete($chunk->getUniqueId()));
});
self::assertCount(2, $chunks);
$afterImport = $jobs[AfterImportJob::class][0]['job'];
if (!method_exists($fake, 'except')) {
/** @var SyncQueue $queue */
$fake = app(SyncQueue::class);
$fake->setContainer(app());
} else {
$fake->except([AfterImportJob::class, ReadChunk::class]);
}
$fake->push($chunks->first());
self::assertTrue(ReadChunk::isComplete($chunks->first()->getUniqueId()));
self::assertFalse(ReadChunk::isComplete($chunks->last()->getUniqueId()));
Event::listen(JobProcessed::class, function (JobProcessed $event) {
self::assertTrue($event->job->isReleased());
});
$fake->push($afterImport);
Event::forget(JobProcessed::class);
$fake->push($chunks->last());
Event::listen(JobProcessed::class, function (JobProcessed $event) {
self::assertFalse($event->job->isReleased());
});
$fake->push($afterImport);
Event::forget(JobProcessed::class);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/WithMultipleSheetsTest.php | tests/Concerns/WithMultipleSheetsTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\SkipsUnknownSheets;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
use Maatwebsite\Excel\Tests\Data\Stubs\SheetForUsersFromView;
use Maatwebsite\Excel\Tests\Data\Stubs\SheetWith100Rows;
use Maatwebsite\Excel\Tests\TestCase;
use PHPUnit\Framework\Assert;
class WithMultipleSheetsTest extends TestCase
{
/**
* Setup the test environment.
*/
protected function setUp(): void
{
parent::setUp();
$this->withFactories(__DIR__ . '/../Data/Stubs/Database/Factories');
}
public function test_can_export_with_multiple_sheets_using_collections()
{
$export = new class implements WithMultipleSheets
{
use Exportable;
/**
* @return SheetWith100Rows[]
*/
public function sheets(): array
{
return [
new SheetWith100Rows('A'),
new SheetWith100Rows('B'),
new SheetWith100Rows('C'),
];
}
};
$export->store('from-view.xlsx');
$this->assertCount(100, $this->readAsArray(__DIR__ . '/../Data/Disks/Local/from-view.xlsx', 'Xlsx', 0));
$this->assertCount(100, $this->readAsArray(__DIR__ . '/../Data/Disks/Local/from-view.xlsx', 'Xlsx', 1));
$this->assertCount(100, $this->readAsArray(__DIR__ . '/../Data/Disks/Local/from-view.xlsx', 'Xlsx', 2));
}
public function test_can_export_multiple_sheets_from_view()
{
/** @var Collection|User[] $users */
$users = factory(User::class)->times(300)->make();
$export = new class($users) implements WithMultipleSheets
{
use Exportable;
/**
* @var Collection
*/
protected $users;
/**
* @param Collection $users
*/
public function __construct(Collection $users)
{
$this->users = $users;
}
/**
* @return SheetForUsersFromView[]
*/
public function sheets(): array
{
return [
new SheetForUsersFromView($this->users->forPage(1, 100)),
new SheetForUsersFromView($this->users->forPage(2, 100)),
new SheetForUsersFromView($this->users->forPage(3, 100)),
];
}
};
$export->store('from-view.xlsx');
$this->assertCount(101, $this->readAsArray(__DIR__ . '/../Data/Disks/Local/from-view.xlsx', 'Xlsx', 0));
$this->assertCount(101, $this->readAsArray(__DIR__ . '/../Data/Disks/Local/from-view.xlsx', 'Xlsx', 1));
$this->assertCount(101, $this->readAsArray(__DIR__ . '/../Data/Disks/Local/from-view.xlsx', 'Xlsx', 2));
}
public function test_unknown_sheet_index_will_throw_sheet_not_found_exception()
{
$this->expectException(\Maatwebsite\Excel\Exceptions\SheetNotFoundException::class);
$this->expectExceptionMessage('Your requested sheet index: 9999 is out of bounds. The actual number of sheets is 2.');
$import = new class implements WithMultipleSheets
{
use Importable;
public function sheets(): array
{
return [
9999 => new class {
},
];
}
};
$import->import('import-multiple-sheets.xlsx');
}
public function test_unknown_sheet_name_will_throw_sheet_not_found_exception()
{
$this->expectException(\Maatwebsite\Excel\Exceptions\SheetNotFoundException::class);
$this->expectExceptionMessage('Your requested sheet name [Some Random Sheet Name] is out of bounds.');
$import = new class implements WithMultipleSheets
{
use Importable;
public function sheets(): array
{
return [
'Some Random Sheet Name' => new class {
},
];
}
};
$import->import('import-multiple-sheets.xlsx');
}
public function test_unknown_sheet_name_can_be_ignored()
{
$import = new class implements WithMultipleSheets, SkipsUnknownSheets
{
use Importable;
public $unknown;
public function sheets(): array
{
return [
'Some Random Sheet Name' => new class {
},
];
}
/**
* @param string|int $sheetName
*/
public function onUnknownSheet($sheetName)
{
$this->unknown = $sheetName;
}
};
$import->import('import-multiple-sheets.xlsx');
$this->assertEquals('Some Random Sheet Name', $import->unknown);
}
public function test_unknown_sheet_indices_can_be_ignored_per_name()
{
$import = new class implements WithMultipleSheets
{
use Importable;
public function sheets(): array
{
return [
'Some Random Sheet Name' => new class implements SkipsUnknownSheets
{
/**
* @param string|int $sheetName
*/
public function onUnknownSheet($sheetName)
{
Assert::assertEquals('Some Random Sheet Name', $sheetName);
}
},
];
}
};
$import->import('import-multiple-sheets.xlsx');
}
public function test_unknown_sheet_indices_can_be_ignored()
{
$import = new class implements WithMultipleSheets, SkipsUnknownSheets
{
use Importable;
public $unknown;
public function sheets(): array
{
return [
99999 => new class {
},
];
}
/**
* @param string|int $sheetName
*/
public function onUnknownSheet($sheetName)
{
$this->unknown = $sheetName;
}
};
$import->import('import-multiple-sheets.xlsx');
$this->assertEquals(99999, $import->unknown);
}
public function test_unknown_sheet_indices_can_be_ignored_per_sheet()
{
$import = new class implements WithMultipleSheets
{
use Importable;
public function sheets(): array
{
return [
99999 => new class implements SkipsUnknownSheets
{
/**
* @param string|int $sheetName
*/
public function onUnknownSheet($sheetName)
{
Assert::assertEquals(99999, $sheetName);
}
},
];
}
};
$import->import('import-multiple-sheets.xlsx');
}
public function test_can_import_multiple_sheets()
{
$import = new class implements WithMultipleSheets
{
use Importable;
public function sheets(): array
{
return [
new class implements ToArray
{
public function array(array $array)
{
Assert::assertEquals([
['1.A1', '1.B1'],
['1.A2', '1.B2'],
], $array);
}
},
new class implements ToArray
{
public function array(array $array)
{
Assert::assertEquals([
['2.A1', '2.B1'],
['2.A2', '2.B2'],
], $array);
}
},
];
}
};
$import->import('import-multiple-sheets.xlsx');
}
public function test_can_import_multiple_sheets_by_sheet_name()
{
$import = new class implements WithMultipleSheets
{
use Importable;
public function sheets(): array
{
return [
'Sheet2' => new class implements ToArray
{
public function array(array $array)
{
Assert::assertEquals([
['2.A1', '2.B1'],
['2.A2', '2.B2'],
], $array);
}
},
'Sheet1' => new class implements ToArray
{
public function array(array $array)
{
Assert::assertEquals([
['1.A1', '1.B1'],
['1.A2', '1.B2'],
], $array);
}
},
];
}
};
$import->import('import-multiple-sheets.xlsx');
}
public function test_can_import_multiple_sheets_by_sheet_index_and_name()
{
$import = new class implements WithMultipleSheets
{
use Importable;
public $sheets = [];
public function __construct()
{
$this->sheets = [
0 => new class implements ToArray
{
public $called = false;
public function array(array $array)
{
$this->called = true;
Assert::assertEquals([
['1.A1', '1.B1'],
['1.A2', '1.B2'],
], $array);
}
},
'Sheet2' => new class implements ToArray
{
public $called = false;
public function array(array $array)
{
$this->called = true;
Assert::assertEquals([
['2.A1', '2.B1'],
['2.A2', '2.B2'],
], $array);
}
},
];
}
public function sheets(): array
{
return $this->sheets;
}
};
$import->import('import-multiple-sheets.xlsx');
foreach ($import->sheets as $sheet) {
$this->assertTrue($sheet->called);
}
}
public function test_can_import_multiple_sheets_by_sheet_name_and_index()
{
$import = new class implements WithMultipleSheets
{
use Importable;
public $sheets = [];
public function __construct()
{
$this->sheets = [
'Sheet1' => new class implements ToArray
{
public $called = false;
public function array(array $array)
{
$this->called = true;
Assert::assertEquals([
['1.A1', '1.B1'],
['1.A2', '1.B2'],
], $array);
}
},
1 => new class implements ToArray
{
public $called = false;
public function array(array $array)
{
$this->called = true;
Assert::assertEquals([
['2.A1', '2.B1'],
['2.A2', '2.B2'],
], $array);
}
},
];
}
public function sheets(): array
{
return $this->sheets;
}
};
$import->import('import-multiple-sheets.xlsx');
foreach ($import->sheets as $sheet) {
$this->assertTrue($sheet->called);
}
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/WithBatchInsertsTest.php | tests/Concerns/WithBatchInsertsTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\Group;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
use Maatwebsite\Excel\Tests\TestCase;
class WithBatchInsertsTest extends TestCase
{
/**
* Setup the test environment.
*/
protected function setUp(): void
{
parent::setUp();
$this->loadLaravelMigrations(['--database' => 'testing']);
$this->loadMigrationsFrom(dirname(__DIR__) . '/Data/Stubs/Database/Migrations');
}
public function test_can_import_to_model_in_batches()
{
DB::connection()->enableQueryLog();
$import = new class implements ToModel, WithBatchInserts
{
use Importable;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
/**
* @return int
*/
public function batchSize(): int
{
return 2;
}
};
$import->import('import-users.xlsx');
$this->assertCount(1, DB::getQueryLog());
DB::connection()->disableQueryLog();
$this->assertDatabaseHas('users', [
'name' => 'Patrick Brouwers',
'email' => 'patrick@maatwebsite.nl',
]);
$this->assertDatabaseHas('users', [
'name' => 'Taylor Otwell',
'email' => 'taylor@laravel.com',
]);
}
public function test_can_import_to_model_in_batches_bigger_file()
{
DB::connection()->enableQueryLog();
$import = new class implements ToModel, WithBatchInserts
{
use Importable;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new Group([
'name' => $row[0],
]);
}
/**
* @return int
*/
public function batchSize(): int
{
return 1000;
}
};
$import->import('import-batches.xlsx');
$this->assertCount(5000 / $import->batchSize(), DB::getQueryLog());
DB::connection()->disableQueryLog();
}
public function test_can_import_multiple_different_types_of_models_in_single_to_model()
{
DB::connection()->enableQueryLog();
$import = new class implements ToModel, WithBatchInserts
{
use Importable;
/**
* @param array $row
* @return Model|Model[]|null
*/
public function model(array $row)
{
$user = new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
$group = new Group([
'name' => $row[0],
]);
return [$user, $group];
}
/**
* @return int
*/
public function batchSize(): int
{
return 2;
}
};
$import->import('import-users.xlsx');
// Expected 2 batch queries, 1 for users, 1 for groups
$this->assertCount(2, DB::getQueryLog());
$this->assertEquals(2, User::count());
$this->assertEquals(2, Group::count());
DB::connection()->disableQueryLog();
}
public function test_has_timestamps_when_imported_in_batches()
{
$import = new class implements ToModel, WithBatchInserts
{
use Importable;
/**
* @param array $row
* @return Model|Model[]|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
/**
* @return int
*/
public function batchSize(): int
{
return 2;
}
};
$import->import('import-users.xlsx');
$user = User::first();
$this->assertNotNull($user->created_at);
$this->assertNotNull($user->updated_at);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/OnEachRowTest.php | tests/Concerns/OnEachRowTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\OnEachRow;
use Maatwebsite\Excel\Row;
use Maatwebsite\Excel\Tests\TestCase;
use PHPUnit\Framework\Assert;
class OnEachRowTest extends TestCase
{
public function test_can_import_each_row_individually()
{
$import = new class implements OnEachRow
{
use Importable;
public $called = 0;
/**
* @param Row $row
*/
public function onRow(Row $row)
{
foreach ($row->getCellIterator() as $cell) {
Assert::assertEquals('test', $cell->getValue());
}
Assert::assertEquals([
'test', 'test',
], $row->toArray());
Assert::assertEquals('test', $row[0]);
$this->called++;
}
};
$import->import('import.xlsx');
$this->assertEquals(2, $import->called);
}
public function test_it_respects_the_end_column()
{
$import = new class implements OnEachRow
{
use Importable;
/**
* @param Row $row
*/
public function onRow(Row $row)
{
// Accessing a row as an array calls toArray() without an end
// column. This saves the row in the cache, so we have to
// invalidate the cache once the end column changes
$row[0];
Assert::assertEquals([
'test',
], $row->toArray(null, false, true, 'A'));
}
};
$import->import('import.xlsx');
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/WithCustomCsvSettingsTest.php | tests/Concerns/WithCustomCsvSettingsTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\WithCustomCsvSettings;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\HeadingRowImport;
use Maatwebsite\Excel\Tests\TestCase;
use PHPUnit\Framework\Assert;
class WithCustomCsvSettingsTest extends TestCase
{
/**
* @var Excel
*/
protected $SUT;
protected function setUp(): void
{
parent::setUp();
$this->SUT = $this->app->make(Excel::class);
}
public function test_can_store_csv_export_with_custom_settings()
{
$export = new class implements FromCollection, WithCustomCsvSettings
{
/**
* @return Collection
*/
public function collection()
{
return collect([
['A1', 'B1'],
['A2', 'B2'],
]);
}
/**
* @return array
*/
public function getCsvSettings(): array
{
return [
'delimiter' => ';',
'enclosure' => '',
'line_ending' => PHP_EOL,
'use_bom' => true,
'include_separator_line' => true,
'excel_compatibility' => false,
'output_encoding' => '',
'test_auto_detect' => false,
];
}
};
$this->SUT->store($export, 'custom-csv.csv');
$contents = file_get_contents(__DIR__ . '/../Data/Disks/Local/custom-csv.csv');
$this->assertStringContains('sep=;', $contents);
$this->assertStringContains('A1;B1', $contents);
$this->assertStringContains('A2;B2', $contents);
}
public function test_can_store_csv_export_with_custom_encoding()
{
$export = new class implements FromCollection, WithCustomCsvSettings
{
/**
* @return Collection
*/
public function collection()
{
return collect([
['A1', '€ŠšŽžŒœŸ'],
['A2', 'åßàèòìù'],
]);
}
/**
* @return array
*/
public function getCsvSettings(): array
{
return [
'delimiter' => ';',
'enclosure' => '',
'line_ending' => PHP_EOL,
'use_bom' => false,
'include_separator_line' => true,
'excel_compatibility' => false,
'output_encoding' => 'ISO-8859-15',
];
}
};
$this->SUT->store($export, 'custom-csv-iso.csv');
$contents = file_get_contents(__DIR__ . '/../Data/Disks/Local/custom-csv-iso.csv');
Assert::assertEquals('ISO-8859-15', mb_detect_encoding($contents, 'ISO-8859-15', true));
Assert::assertFalse(mb_detect_encoding($contents, 'UTF-8', true));
$contents = mb_convert_encoding($contents, 'UTF-8', 'ISO-8859-15');
$this->assertStringContains('sep=;', $contents);
$this->assertStringContains('A1;€ŠšŽžŒœŸ', $contents);
$this->assertStringContains('A2;åßàèòìù', $contents);
}
public function test_can_read_csv_with_auto_detecting_delimiter_semicolon()
{
$this->assertEquals([
[
['a1', 'b1'],
],
], (new HeadingRowImport())->toArray('csv-with-other-delimiter.csv'));
}
public function test_can_read_csv_with_auto_detecting_delimiter_comma()
{
$this->assertEquals([
[
['a1', 'b1'],
],
], (new HeadingRowImport())->toArray('csv-with-comma.csv'));
}
public function test_can_read_csv_import_with_custom_settings()
{
$import = new class implements WithCustomCsvSettings, ToArray
{
/**
* @return array
*/
public function getCsvSettings(): array
{
return [
'delimiter' => ';',
'enclosure' => '',
'escape_character' => '\\',
'contiguous' => true,
'input_encoding' => 'UTF-8',
];
}
/**
* @param array $array
*/
public function array(array $array)
{
Assert::assertEquals([
['A1', 'B1'],
['A2', 'B2'],
], $array);
}
};
$this->SUT->import($import, 'csv-with-other-delimiter.csv');
}
public function test_cannot_read_with_wrong_delimiter()
{
$import = new class implements WithCustomCsvSettings, ToArray
{
/**
* @return array
*/
public function getCsvSettings(): array
{
return [
'delimiter' => ',',
];
}
/**
* @param array $array
*/
public function array(array $array)
{
Assert::assertEquals([
['A1;B1'],
['A2;B2'],
], $array);
}
};
$this->SUT->import($import, 'csv-with-other-delimiter.csv');
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/WithCustomStartCellTest.php | tests/Concerns/WithCustomStartCellTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithCustomStartCell;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Tests\TestCase;
class WithCustomStartCellTest extends TestCase
{
/**
* @var Excel
*/
protected $SUT;
protected function setUp(): void
{
parent::setUp();
$this->SUT = $this->app->make(Excel::class);
}
public function test_can_store_collection_with_custom_start_cell()
{
$export = new class implements FromCollection, WithCustomStartCell
{
/**
* @return Collection
*/
public function collection()
{
return collect([
['A1', 'B1'],
['A2', 'B2'],
]);
}
/**
* @return string
*/
public function startCell(): string
{
return 'B2';
}
};
$this->SUT->store($export, 'custom-start-cell.csv');
$contents = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/custom-start-cell.csv', 'Csv');
$this->assertEquals([
[null, null, null],
[null, 'A1', 'B1'],
[null, 'A2', 'B2'],
], $contents);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/WithMappingTest.php | tests/Concerns/WithMappingTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Tests\Data\Stubs\WithMappingExport;
use Maatwebsite\Excel\Tests\TestCase;
class WithMappingTest extends TestCase
{
public function test_can_export_with_heading()
{
$export = new WithMappingExport();
$response = $export->store('with-mapping-store.xlsx');
$this->assertTrue($response);
$actual = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/with-mapping-store.xlsx', 'Xlsx');
$expected = [
[
'mapped-A1',
'mapped-B1',
'mapped-C1',
],
[
'mapped-A2',
'mapped-B2',
'mapped-C2',
],
];
$this->assertEquals($expected, $actual);
}
public function test_can_return_multiple_rows_in_map()
{
$export = new class implements FromArray, WithMapping
{
use Exportable;
/**
* @return array
*/
public function array(): array
{
return [
['id' => 1],
['id' => 2],
['id' => 3],
];
}
/**
* @param mixed $row
* @return array
*/
public function map($row): array
{
return [
[$row['id']],
[$row['id']],
];
}
};
$response = $export->store('with-mapping-store.xlsx');
$this->assertTrue($response);
$actual = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/with-mapping-store.xlsx', 'Xlsx');
$this->assertCount(6, $actual);
}
public function test_json_array_columns_shouldnt_be_detected_as_multiple_rows()
{
$export = new class implements FromArray
{
use Exportable;
/**
* @return array
*/
public function array(): array
{
return [
['id' => 1, 'json' => ['other_id' => 1]],
['id' => 2, 'json' => ['other_id' => 2]],
['id' => 3, 'json' => ['other_id' => 3]],
];
}
};
$response = $export->store('with-mapping-store.xlsx');
$this->assertTrue($response);
$actual = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/with-mapping-store.xlsx', 'Xlsx');
$this->assertCount(3, $actual);
$this->assertEquals([
[1, \json_encode(['other_id' => 1])],
[2, \json_encode(['other_id' => 2])],
[3, \json_encode(['other_id' => 3])],
], $actual);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/WithValidationTest.php | tests/Concerns/WithValidationTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Validation\Rule;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\OnEachRow;
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Maatwebsite\Excel\Concerns\WithGroupedHeadingRow;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;
use Maatwebsite\Excel\Row;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
use Maatwebsite\Excel\Tests\TestCase;
use Maatwebsite\Excel\Validators\ValidationException;
use PHPUnit\Framework\Assert;
class WithValidationTest extends TestCase
{
/**
* Setup the test environment.
*/
protected function setUp(): void
{
parent::setUp();
$this->loadLaravelMigrations(['--database' => 'testing']);
$this->loadMigrationsFrom(dirname(__DIR__) . '/Data/Stubs/Database/Migrations');
}
public function test_can_validate_rows()
{
$import = new class implements ToModel, WithValidation
{
use Importable;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
/**
* @return array
*/
public function rules(): array
{
return [
'1' => Rule::in(['patrick@maatwebsite.nl']),
];
}
};
try {
$import->import('import-users.xlsx');
} catch (ValidationException $e) {
$this->validateFailure($e, 2, '1', [
'The selected 1(field)? is invalid.',
]);
$this->assertRegex(
'/There was an error on row 2. The selected 1 (field)?is invalid./',
$e->errors()[0][0]
);
}
$this->assertInstanceOf(ValidationException::class, $e ?? null);
}
public function test_can_validate_rows_with_closure_validation_rules()
{
$import = new class implements ToModel, WithValidation
{
use Importable;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
/**
* @return array
*/
public function rules(): array
{
return [
'1' => function ($attribute, $value, $onFail) {
if ($value !== 'patrick@maatwebsite.nl') {
$onFail(sprintf('Value in column 1 is not an allowed e-mail.'));
}
},
];
}
};
try {
$import->import('import-users.xlsx');
} catch (ValidationException $e) {
$this->validateFailure($e, 2, '1', [
'Value in column 1 is not an allowed e-mail.',
]);
$this->assertRegex(
'/There was an error on row 2. Value in column 1 is not an allowed e-mail./',
$e->errors()[0][0]
);
}
$this->assertInstanceOf(ValidationException::class, $e ?? null);
}
public function test_can_validate_rows_with_custom_validation_rule_objects()
{
$import = new class implements ToModel, WithValidation
{
use Importable;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
/**
* @return array
*/
public function rules(): array
{
return [
'1' => new class implements \Illuminate\Contracts\Validation\Rule
{
/**
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
return $value === 'patrick@maatwebsite.nl';
}
/**
* Get the validation error message.
*
* @return string|array
*/
public function message()
{
return 'Value is not an allowed e-mail.';
}
},
];
}
};
try {
$import->import('import-users.xlsx');
} catch (ValidationException $e) {
$this->validateFailure($e, 2, '1', [
'Value is not an allowed e-mail.',
]);
$this->assertRegex(
'/There was an error on row 2. Value is not an allowed e-mail./',
$e->errors()[0][0]
);
}
$this->assertInstanceOf(ValidationException::class, $e ?? null);
}
public function test_can_validate_rows_with_conditionality()
{
$import = new class implements ToModel, WithValidation
{
use Importable;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
/**
* @return array
*/
public function rules(): array
{
return [
'conditional_required_column' => 'required_if:1,patrick@maatwebsite.nl',
];
}
};
try {
$import->import('import-users.xlsx');
} catch (ValidationException $e) {
$this->validateFailure($e, 1, 'conditional_required_column', [
'The conditional_required_column field is required when 1.1 is patrick@maatwebsite.nl.',
]);
}
$this->assertInstanceOf(ValidationException::class, $e ?? null);
}
public function test_can_validate_rows_with_unless_conditionality()
{
$import = new class implements ToModel, WithValidation
{
use Importable;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
/**
* @return array
*/
public function rules(): array
{
return [
'conditional_required_unless_column' => 'required_unless:1,patrick@maatwebsite.nl',
];
}
};
try {
$import->import('import-users.xlsx');
} catch (ValidationException $e) {
$this->validateFailure($e, 2, 'conditional_required_unless_column', [
'The conditional_required_unless_column field is required unless 2.1 is in patrick@maatwebsite.nl.',
]);
}
$this->assertInstanceOf(ValidationException::class, $e ?? null);
}
public function test_can_validate_rows_with_combined_rules_with_colons()
{
$import = new class implements ToModel, WithValidation
{
use Importable;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
/**
* @return array
*/
public function rules(): array
{
return [
'1' => 'required_with:0|unique:users,email',
];
}
};
$import->import('import-users.xlsx');
$this->assertDatabaseHas('users', [
'email' => 'patrick@maatwebsite.nl',
]);
try {
$import->import('import-users.xlsx');
} catch (ValidationException $e) {
$this->validateFailure($e, 1, '1', [
'The 1 has already been taken.',
]);
}
$this->assertInstanceOf(ValidationException::class, $e ?? null);
}
public function test_can_validate_with_custom_attributes()
{
$import = new class implements ToModel, WithValidation
{
use Importable;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
/**
* @return array
*/
public function rules(): array
{
return [
'1' => Rule::in(['patrick@maatwebsite.nl']),
];
}
/**
* @return array
*/
public function customValidationAttributes()
{
return ['1' => 'email'];
}
};
try {
$import->import('import-users.xlsx');
} catch (ValidationException $e) {
$this->validateFailure($e, 2, 'email', [
'The selected email is invalid.',
]);
}
$this->assertInstanceOf(ValidationException::class, $e ?? null);
}
public function test_can_validate_with_custom_attributes_pointing_to_another_attribute()
{
$import = new class implements ToModel, WithValidation
{
use Importable;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
/**
* @return array
*/
public function rules(): array
{
return [
'1' => ['required'],
'2' => ['required_with:*.1'],
];
}
/**
* @return array
*/
public function customValidationAttributes()
{
return ['1' => 'email', '2' => 'password'];
}
};
try {
$import->import('import-users.xlsx');
} catch (ValidationException $e) {
$this->validateFailure($e, 1, 'password', [
'The password field is required when email is present.',
]);
}
$this->assertInstanceOf(ValidationException::class, $e ?? null);
}
public function test_can_validate_with_custom_message()
{
$import = new class implements ToModel, WithValidation
{
use Importable;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
/**
* @return array
*/
public function rules(): array
{
return [
'1' => Rule::in(['patrick@maatwebsite.nl']),
];
}
/**
* @return array
*/
public function customValidationMessages()
{
return [
'1.in' => 'Custom message for :attribute.',
];
}
};
try {
$import->import('import-users.xlsx');
} catch (ValidationException $e) {
$this->validateFailure($e, 2, '1', [
'Custom message for 1.',
]);
}
$this->assertInstanceOf(ValidationException::class, $e ?? null);
}
public function test_can_validate_rows_with_headings()
{
$import = new class implements ToModel, WithHeadingRow, WithValidation
{
use Importable;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new User([
'name' => $row['name'],
'email' => $row['email'],
'password' => 'secret',
]);
}
/**
* @return array
*/
public function rules(): array
{
return [
'email' => Rule::in(['patrick@maatwebsite.nl']),
];
}
};
try {
$import->import('import-users-with-headings.xlsx');
} catch (ValidationException $e) {
$this->validateFailure($e, 3, 'email', [
'The selected email is invalid.',
]);
}
$this->assertInstanceOf(ValidationException::class, $e ?? null);
}
public function test_can_validate_rows_with_grouped_headings()
{
$import = new class implements ToModel, WithGroupedHeadingRow, WithValidation
{
use Importable;
/**
* Prepare the data for validation.
*
* @param array $row
* @param int $index
* @return array
*/
public function prepareForValidation(array $row, int $index)
{
if ($index === 2) {
Assert::assertIsArray($row['options']);
$row['options'] = 'not an array';
}
return $row;
}
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new User([
'name' => $row['name'],
'email' => $row['email'],
'password' => 'secret',
'options' => $row['options'],
]);
}
/**
* @return array
*/
public function rules(): array
{
return [
'options' => 'array',
];
}
};
try {
$import->import('import-users-with-grouped-headers.xlsx');
} catch (ValidationException $e) {
$this->validateFailure($e, 2, 'options', [
'The options( field)? must be an array.',
]);
}
$this->assertInstanceOf(ValidationException::class, $e ?? null);
}
public function test_can_validate_rows_in_batches()
{
$import = new class implements ToModel, WithHeadingRow, WithBatchInserts, WithValidation
{
use Importable;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new User([
'name' => $row['name'],
'email' => $row['email'],
'password' => 'secret',
]);
}
/**
* @return int
*/
public function batchSize(): int
{
return 2;
}
/**
* @return array
*/
public function rules(): array
{
return [
'email' => Rule::in(['patrick@maatwebsite.nl']),
];
}
};
try {
$import->import('import-users-with-headings.xlsx');
} catch (ValidationException $e) {
$this->validateFailure($e, 3, 'email', [
'The selected email is invalid.',
]);
}
$this->assertInstanceOf(ValidationException::class, $e ?? null);
}
public function test_can_validate_using_oneachrow()
{
$import = new class implements OnEachRow, WithHeadingRow, WithValidation
{
use Importable;
/**
* @param Row $row
* @return Model|null
*/
public function onRow(Row $row)
{
$values = $row->toArray();
return new User([
'name' => $values['name'],
'email' => $values['email'],
'password' => 'secret',
]);
}
/**
* @return array
*/
public function rules(): array
{
return [
'email' => Rule::in(['patrick@maatwebsite.nl']),
];
}
};
try {
$import->import('import-users-with-headings.xlsx');
} catch (ValidationException $e) {
$this->validateFailure($e, 3, 'email', [
'The selected email is invalid.',
]);
}
$this->assertInstanceOf(ValidationException::class, $e ?? null);
}
public function test_can_validate_using_collection()
{
$import = new class implements ToCollection, WithHeadingRow, WithValidation
{
use Importable;
public function collection(Collection $rows)
{
//
}
/**
* @return array
*/
public function rules(): array
{
return [
'email' => Rule::in(['patrick@maatwebsite.nl']),
];
}
};
try {
$import->import('import-users-with-headings.xlsx');
} catch (ValidationException $e) {
$this->validateFailure($e, 3, 'email', [
'The selected email is invalid.',
]);
}
$this->assertInstanceOf(ValidationException::class, $e ?? null);
}
public function test_can_validate_using_array()
{
$import = new class implements ToArray, WithHeadingRow, WithValidation
{
use Importable;
public function array(array $rows)
{
//
}
/**
* @return array
*/
public function rules(): array
{
return [
'email' => Rule::in(['patrick@maatwebsite.nl']),
];
}
};
try {
$import->import('import-users-with-headings.xlsx');
} catch (ValidationException $e) {
$this->validateFailure($e, 3, 'email', [
'The selected email is invalid.',
]);
}
$this->assertInstanceOf(ValidationException::class, $e ?? null);
}
public function test_can_configure_validator()
{
$import = new class implements ToModel, WithValidation
{
use Importable;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
/**
* @return array
*/
public function rules(): array
{
return [
'1' => 'email',
];
}
/**
* Configure the validator.
*
* @param \Illuminate\Contracts\Validation\Validator $validator
* @return void
*/
public function withValidator($validator)
{
$validator->sometimes('*.1', Rule::in(['patrick@maatwebsite.nl']), function () {
return true;
});
}
};
try {
$import->import('import-users.xlsx');
} catch (ValidationException $e) {
$this->validateFailure($e, 2, '1', [
'The selected 1 is invalid.',
]);
$this->assertRegex(
'/There was an error on row 2. The selected 1 (field)?is invalid./',
$e->errors()[0][0]
);
}
$this->assertInstanceOf(ValidationException::class, $e ?? null);
}
public function test_can_prepare_using_toarray()
{
$import = new class implements ToArray, WithValidation
{
use Importable;
/**
* @return array
*/
public function rules(): array
{
return [
'1' => 'email',
];
}
/**
* Prepare the data for validation.
*
* @param array $row
* @param int $index
* @return array
*/
public function prepareForValidation(array $row, int $index)
{
if ($index === 2) {
$row[1] = 'not an email';
}
return $row;
}
/**
* @param array $array
* @return array
*/
public function array(array $array)
{
return [];
}
};
try {
$import->import('import-users.xlsx');
} catch (ValidationException $e) {
$this->validateFailure($e, 2, '1', [
'The 1( field)? must be a valid email address.',
]);
$this->assertRegex(
'/There was an error on row 2. The 1( field)? must be a valid email address./',
$e->errors()[0][0]
);
}
$this->assertInstanceOf(ValidationException::class, $e ?? null);
}
public function test_can_prepare_using_tocollection()
{
$import = new class implements ToCollection, WithValidation
{
use Importable;
/**
* @return array
*/
public function rules(): array
{
return [
'1' => 'email',
];
}
/**
* Prepare the data for validation.
*
* @param array $row
* @param int $index
* @return array
*/
public function prepareForValidation(array $row, int $index)
{
if ($index === 2) {
$row[1] = 'not an email';
}
return $row;
}
/**
* @param \Illuminate\Support\Collection $collection
* @return mixed
*/
public function collection(Collection $collection)
{
return collect();
}
};
try {
$import->import('import-users.xlsx');
} catch (ValidationException $e) {
$this->validateFailure($e, 2, '1', [
'The 1( field)? must be a valid email address.',
]);
$this->assertRegex(
'/There was an error on row 2. The 1( field)? must be a valid email address./',
$e->errors()[0][0]
);
}
$this->assertInstanceOf(ValidationException::class, $e ?? null);
}
public function test_can_prepare_using_tomodel()
{
$import = new class implements ToModel, WithValidation
{
use Importable;
/**
* @return array
*/
public function rules(): array
{
return [
'1' => 'email',
];
}
/**
* Prepare the data for validation.
*
* @param array $row
* @param int $index
* @return array
*/
public function prepareForValidation(array $row, int $index)
{
if ($index === 2) {
$row[1] = 'not an email';
}
return $row;
}
/**
* @param array $row
* @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Model[]|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
};
try {
$import->import('import-users.xlsx');
} catch (ValidationException $e) {
$this->validateFailure($e, 2, '1', [
'The 1( field)? must be a valid email address.',
]);
$this->assertRegex(
'/There was an error on row 2. The 1( field)? must be a valid email address./',
$e->errors()[0][0]
);
}
$this->assertInstanceOf(ValidationException::class, $e ?? null);
}
public function test_can_prepare_using_oneachrow()
{
$import = new class implements OnEachRow, WithValidation
{
use Importable;
/**
* @return array
*/
public function rules(): array
{
return [
'1' => 'email',
];
}
/**
* Prepare the data for validation.
*
* @param array $row
* @param int $index
* @return array
*/
public function prepareForValidation(array $row, int $index)
{
if ($index === 2) {
$row[1] = 'not an email';
}
return $row;
}
/**
* @param \Maatwebsite\Excel\Row $row
* @return void
*/
public function onRow(Row $row)
{
User::query()->create([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
};
try {
$import->import('import-users.xlsx');
} catch (ValidationException $e) {
$this->validateFailure($e, 2, '1', [
'The 1( field)? must be a valid email address.',
]);
$this->assertRegex(
'/There was an error on row 2. The 1( field)? must be a valid email address./',
$e->errors()[0][0]
);
}
$this->assertInstanceOf(ValidationException::class, $e ?? null);
}
public function test_can_prepare_using_skipsemptyrows()
{
$import = new class implements OnEachRow, WithValidation, SkipsEmptyRows
{
use Importable;
/**
* @return array
*/
public function rules(): array
{
return [
'1' => 'email',
];
}
/**
* Prepare the data for validation.
*
* @param array $row
* @param int $index
* @return array
*/
public function prepareForValidation(array $row, int $index)
{
if ($index === 2) {
$row[1] = 'not an email';
}
return $row;
}
/**
* @param \Maatwebsite\Excel\Row $row
* @return void
*/
public function onRow(Row $row)
{
User::query()->create([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
};
try {
$import->import('import-users.xlsx');
} catch (ValidationException $e) {
$this->validateFailure($e, 2, '1', [
'The 1( field)? must be a valid email address.',
]);
$this->assertRegex(
'/There was an error on row 2. The 1( field)? must be a valid email address./',
$e->errors()[0][0]
);
}
$this->assertInstanceOf(ValidationException::class, $e ?? null);
}
/**
* @param ValidationException $e
* @param int $row
* @param string $attribute
* @param array $messages
*/
private function validateFailure(ValidationException $e, int $row, string $attribute, array $messages)
{
$failures = $e->failures();
$failure = head($failures);
$this->assertEquals($row, $failure->row());
$this->assertEquals($attribute, $failure->attribute());
$this->assertEquals($row, $failure->jsonSerialize()['row']);
$this->assertEquals($attribute, $failure->jsonSerialize()['attribute']);
$this->assertRegex('/' . $messages[0] . '/', $failure->errors()[0]);
$this->assertRegex('/' . $messages[0] . '/', $failure->jsonSerialize()['errors'][0]);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/WithHeadingRowTest.php | tests/Concerns/WithHeadingRowTest.php | <?php
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;
use Maatwebsite\Excel\Tests\TestCase;
use PHPUnit\Framework\Assert;
class WithHeadingRowTest extends TestCase
{
/**
* Setup the test environment.
*/
protected function setUp(): void
{
parent::setUp();
$this->loadLaravelMigrations(['--database' => 'testing']);
}
public function test_can_import_each_row_to_model_with_heading_row()
{
$import = new class implements ToModel, WithHeadingRow
{
use Importable;
/**
* @param array $row
* @return Model
*/
public function model(array $row): Model
{
return new User([
'name' => $row['name'],
'email' => $row['email'],
'password' => 'secret',
]);
}
};
$import->import('import-users-with-headings.xlsx');
$this->assertDatabaseHas('users', [
'name' => 'Patrick Brouwers',
'email' => 'patrick@maatwebsite.nl',
]);
$this->assertDatabaseHas('users', [
'name' => 'Taylor Otwell',
'email' => 'taylor@laravel.com',
]);
}
public function test_can_import_each_row_to_model_with_different_heading_row()
{
$import = new class implements ToModel, WithHeadingRow
{
use Importable;
/**
* @param array $row
* @return Model
*/
public function model(array $row): Model
{
return new User([
'name' => $row['name'],
'email' => $row['email'],
'password' => 'secret',
]);
}
/**
* @return int
*/
public function headingRow(): int
{
return 4;
}
};
$import->import('import-users-with-different-heading-row.xlsx');
$this->assertDatabaseHas('users', [
'name' => 'Patrick Brouwers',
'email' => 'patrick@maatwebsite.nl',
]);
$this->assertDatabaseHas('users', [
'name' => 'Taylor Otwell',
'email' => 'taylor@laravel.com',
]);
}
public function test_can_import_to_array_with_heading_row()
{
$import = new class implements ToArray, WithHeadingRow
{
use Importable;
/**
* @param array $array
*/
public function array(array $array)
{
Assert::assertEquals([
[
'name' => 'Patrick Brouwers',
'email' => 'patrick@maatwebsite.nl',
],
[
'name' => 'Taylor Otwell',
'email' => 'taylor@laravel.com',
],
], $array);
}
};
$import->import('import-users-with-headings.xlsx');
}
public function test_can_import_empty_rows_with_header()
{
$import = new class() implements ToArray, WithHeadingRow
{
use Importable;
/**
* @param array $array
*/
public function array(array $array)
{
Assert::assertEmpty($array);
}
};
$import->import('import-empty-users-with-headings.xlsx');
}
public function test_can_import_empty_models_with_header()
{
$import = new class() implements ToModel, WithHeadingRow
{
use Importable;
/**
* @param array $row
* @return Model
*/
public function model(array $row): Model
{
return new User([
'name' => $row['name'],
'email' => $row['email'],
'password' => 'secret',
]);
}
};
$import->import('import-empty-users-with-headings.xlsx');
$this->assertEmpty(User::all());
}
public function test_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);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/WithStartRowTest.php | tests/Concerns/WithStartRowTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Illuminate\Database\Eloquent\Model;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
use Maatwebsite\Excel\Tests\TestCase;
use PHPUnit\Framework\Assert;
class WithStartRowTest extends TestCase
{
/**
* Setup the test environment.
*/
protected function setUp(): void
{
parent::setUp();
$this->loadLaravelMigrations(['--database' => 'testing']);
}
public function test_can_import_each_row_to_model_with_different_start_row()
{
$import = new class implements ToModel, WithStartRow
{
use Importable;
/**
* @param array $row
* @return Model
*/
public function model(array $row): Model
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
/**
* @return int
*/
public function startRow(): int
{
return 5;
}
};
$import->import('import-users-with-different-heading-row.xlsx');
$this->assertDatabaseHas('users', [
'name' => 'Patrick Brouwers',
'email' => 'patrick@maatwebsite.nl',
]);
$this->assertDatabaseHas('users', [
'name' => 'Taylor Otwell',
'email' => 'taylor@laravel.com',
]);
}
public function test_can_import_to_array_with_start_row()
{
$import = new class implements ToArray, WithStartRow
{
use Importable;
/**
* @param array $array
*/
public function array(array $array)
{
Assert::assertEquals([
[
'Patrick Brouwers',
'patrick@maatwebsite.nl',
],
[
'Taylor Otwell',
'taylor@laravel.com',
],
], $array);
}
/**
* @return int
*/
public function startRow(): int
{
return 5;
}
};
$import->import('import-users-with-different-heading-row.xlsx');
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/WithGroupedHeadingRowTest.php | tests/Concerns/WithGroupedHeadingRowTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\OnEachRow;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithGroupedHeadingRow;
use Maatwebsite\Excel\Row;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
use Maatwebsite\Excel\Tests\TestCase;
use PHPUnit\Framework\Assert;
class WithGroupedHeadingRowTest extends TestCase
{
/**
* Setup the test environment.
*/
protected function setUp(): void
{
parent::setUp();
$this->loadLaravelMigrations(['--database' => 'testing']);
$this->loadMigrationsFrom(dirname(__DIR__) . '/Data/Stubs/Database/Migrations');
}
public function test_can_import_to_array_with_grouped_headers()
{
$import = new class implements ToArray, WithGroupedHeadingRow
{
use Importable;
/**
* @param array $array
*/
public function array(array $array)
{
Assert::assertEquals([
[
'name' => 'Patrick Brouwers',
'email' => 'patrick@maatwebsite.nl',
'options' => [
'laravel',
'excel',
],
],
], $array);
}
};
$import->import('import-users-with-grouped-headers.xlsx');
}
public function test_can_import_oneachrow_with_grouped_headers()
{
$import = new class implements OnEachRow, WithGroupedHeadingRow
{
use Importable;
/**
* @param \Maatwebsite\Excel\Row $row
* @return void
*/
public function onRow(Row $row)
{
Assert::assertEquals(
[
'name' => 'Patrick Brouwers',
'email' => 'patrick@maatwebsite.nl',
'options' => [
'laravel',
'excel',
],
], $row->toArray());
}
};
$import->import('import-users-with-grouped-headers.xlsx');
}
public function test_can_import_to_collection_with_grouped_headers()
{
$import = new class implements ToCollection, WithGroupedHeadingRow
{
use Importable;
public $called = false;
/**
* @param Collection $collection
*/
public function collection(Collection $collection)
{
$this->called = true;
Assert::assertEquals([
[
'name' => 'Patrick Brouwers',
'email' => 'patrick@maatwebsite.nl',
'options' => [
'laravel',
'excel',
],
],
], $collection->toArray());
}
};
$import->import('import-users-with-grouped-headers.xlsx');
$this->assertTrue($import->called);
}
public function test_can_import_each_row_to_model_with_grouped_headers()
{
$import = new class implements ToModel, WithGroupedHeadingRow
{
use Importable;
/**
* @param array $row
* @return Model
*/
public function model(array $row): Model
{
return new User([
'name' => $row['name'],
'email' => $row['email'],
'password' => 'secret',
'options' => $row['options'],
]);
}
};
$import->import('import-users-with-grouped-headers.xlsx');
$this->assertDatabaseHas('users', [
'name' => 'Patrick Brouwers',
'email' => 'patrick@maatwebsite.nl',
'options' => '["laravel","excel"]',
]);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/WithStrictNullComparisonTest.php | tests/Concerns/WithStrictNullComparisonTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithStrictNullComparison;
use Maatwebsite\Excel\Tests\TestCase;
class WithStrictNullComparisonTest extends TestCase
{
public function test_exported_zero_values_are_not_null_when_exporting_with_strict_null_comparison()
{
$export = new class implements FromCollection, WithHeadings, WithStrictNullComparison
{
use Exportable;
/**
* @return Collection
*/
public function collection()
{
return collect([
['string', '0', 0, 0.0, 'string'],
]);
}
/**
* @return array
*/
public function headings(): array
{
return ['string', '0', 0, 0.0, 'string'];
}
};
$response = $export->store('with-strict-null-comparison-store.xlsx');
$this->assertTrue($response);
$actual = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/with-strict-null-comparison-store.xlsx', 'Xlsx');
$expected = [
['string', 0.0, 0.0, 0.0, 'string'],
['string', 0.0, 0.0, 0.0, 'string'],
];
$this->assertEquals($expected, $actual);
}
public function test_exported_zero_values_are_null_when_not_exporting_with_strict_null_comparison()
{
$export = new class implements FromCollection, WithHeadings
{
use Exportable;
/**
* @return Collection
*/
public function collection()
{
return collect([
['string', 0, 0.0, 'string'],
]);
}
/**
* @return array
*/
public function headings(): array
{
return ['string', 0, 0.0, 'string'];
}
};
$response = $export->store('without-strict-null-comparison-store.xlsx');
$this->assertTrue($response);
$actual = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/without-strict-null-comparison-store.xlsx', 'Xlsx');
$expected = [
['string', null, null, 'string'],
['string', null, null, 'string'],
];
$this->assertEquals($expected, $actual);
}
public function test_exports_trailing_empty_cells()
{
$export = new class implements FromCollection, WithStrictNullComparison
{
use Exportable;
/**
* @return Collection
*/
public function collection()
{
return collect([
['a1', '', '', 'd1', ''],
['a2', '', '', 'd2', ''],
]);
}
};
$response = $export->store('empty-cells.csv');
$this->assertTrue($response);
$file = __DIR__ . '/../Data/Disks/Local/empty-cells.csv';
$actual = $this->readAsArray($file, 'Csv');
$expected = [
['a1', null, null, 'd1'],
['a2', null, null, 'd2'],
];
$this->assertEquals($expected, $actual);
$contents = file_get_contents($file);
$this->assertStringContains('"a1","","","d1",""', $contents);
$this->assertStringContains('"a2","","","d2",""', $contents);
}
public function test_exports_trailing_empty_cells_by_setting_config_strict_null_comparison()
{
config()->set('excel.exports.strict_null_comparison', false);
$export = new class implements FromCollection
{
use Exportable;
/**
* @return Collection
*/
public function collection()
{
return collect([
['a1', '', '', 'd1', ''],
['a2', '', '', 'd2', ''],
]);
}
};
$file = __DIR__ . '/../Data/Disks/Local/empty-cells-config.csv';
$export->store('empty-cells-config.csv');
$contents = file_get_contents($file);
$this->assertStringContains('"a1","","","d1"', $contents);
config()->set('excel.exports.strict_null_comparison', true);
$export->store('empty-cells-config.csv');
$contents = file_get_contents($file);
$this->assertStringContains('"a1","","","d1",""', $contents);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/RegistersEventListenersTest.php | tests/Concerns/RegistersEventListenersTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Events\BeforeExport;
use Maatwebsite\Excel\Events\BeforeImport;
use Maatwebsite\Excel\Events\BeforeSheet;
use Maatwebsite\Excel\Events\BeforeWriting;
use Maatwebsite\Excel\Reader;
use Maatwebsite\Excel\Sheet;
use Maatwebsite\Excel\Tests\Data\Stubs\BeforeExportListener;
use Maatwebsite\Excel\Tests\Data\Stubs\ExportWithEvents;
use Maatwebsite\Excel\Tests\Data\Stubs\ExportWithRegistersEventListeners;
use Maatwebsite\Excel\Tests\Data\Stubs\ImportWithRegistersEventListeners;
use Maatwebsite\Excel\Tests\TestCase;
use Maatwebsite\Excel\Writer;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
class RegistersEventListenersTest extends TestCase
{
public function test_events_get_called_when_exporting()
{
$event = new ExportWithRegistersEventListeners();
$eventsTriggered = 0;
$event::$beforeExport = function ($event) use (&$eventsTriggered) {
$this->assertInstanceOf(BeforeExport::class, $event);
$this->assertInstanceOf(Writer::class, $event->writer);
$eventsTriggered++;
};
$event::$beforeWriting = function ($event) use (&$eventsTriggered) {
$this->assertInstanceOf(BeforeWriting::class, $event);
$this->assertInstanceOf(Writer::class, $event->writer);
$eventsTriggered++;
};
$event::$beforeSheet = function ($event) use (&$eventsTriggered) {
$this->assertInstanceOf(BeforeSheet::class, $event);
$this->assertInstanceOf(Sheet::class, $event->sheet);
$eventsTriggered++;
};
$event::$afterSheet = function ($event) use (&$eventsTriggered) {
$this->assertInstanceOf(AfterSheet::class, $event);
$this->assertInstanceOf(Sheet::class, $event->sheet);
$eventsTriggered++;
};
$this->assertInstanceOf(BinaryFileResponse::class, $event->download('filename.xlsx'));
$this->assertEquals(4, $eventsTriggered);
}
public function test_events_get_called_when_importing()
{
$event = new ImportWithRegistersEventListeners();
$eventsTriggered = 0;
$event::$beforeImport = function ($event) use (&$eventsTriggered) {
$this->assertInstanceOf(BeforeImport::class, $event);
$this->assertInstanceOf(Reader::class, $event->reader);
$eventsTriggered++;
};
$event::$beforeSheet = function ($event) use (&$eventsTriggered) {
$this->assertInstanceOf(BeforeSheet::class, $event);
$this->assertInstanceOf(Sheet::class, $event->sheet);
$eventsTriggered++;
};
$event::$afterSheet = function ($event) use (&$eventsTriggered) {
$this->assertInstanceOf(AfterSheet::class, $event);
$this->assertInstanceOf(Sheet::class, $event->sheet);
$eventsTriggered++;
};
$event->import('import.xlsx');
$this->assertEquals(3, $eventsTriggered);
}
public function test_can_have_invokable_class_as_listener()
{
$event = new ExportWithEvents();
$event->beforeExport = new BeforeExportListener(function ($event) {
$this->assertInstanceOf(BeforeExport::class, $event);
$this->assertInstanceOf(Writer::class, $event->writer);
});
$this->assertInstanceOf(BinaryFileResponse::class, $event->download('filename.xlsx'));
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/FromIteratorTest.php | tests/Concerns/FromIteratorTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use ArrayIterator;
use Iterator;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromIterator;
use Maatwebsite\Excel\Tests\TestCase;
class FromIteratorTest extends TestCase
{
public function test_can_export_from_iterator()
{
$export = new class implements FromIterator
{
use Exportable;
/**
* @return array
*/
public function array()
{
return [
['test', 'test'],
['test', 'test'],
];
}
/**
* @return Iterator
*/
public function iterator(): Iterator
{
return new ArrayIterator($this->array());
}
};
$response = $export->store('from-iterator-store.xlsx');
$this->assertTrue($response);
$contents = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/from-iterator-store.xlsx', 'Xlsx');
$this->assertEquals($export->array(), $contents);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/WithColumnLimitTest.php | tests/Concerns/WithColumnLimitTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\WithColumnLimit;
use Maatwebsite\Excel\Tests\TestCase;
use PHPUnit\Framework\Assert;
class WithColumnLimitTest extends TestCase
{
/**
* Setup the test environment.
*/
protected function setUp(): void
{
parent::setUp();
$this->loadLaravelMigrations(['--database' => 'testing']);
}
public function test_can_import_to_array_with_column_limit()
{
$import = new class implements ToArray, WithColumnLimit
{
use Importable;
/**
* @param array $array
*/
public function array(array $array)
{
Assert::assertEquals([
[
'Patrick Brouwers',
],
[
'Taylor Otwell',
],
], $array);
}
public function endColumn(): string
{
return 'A';
}
};
$import->import('import-users.xlsx');
}
public function test_can_import_to_array_with_column_limit_and_skips_empty_rows()
{
$import = new class implements ToArray, WithColumnLimit, SkipsEmptyRows
{
use Importable;
/**
* @param array $array
*/
public function array(array $array)
{
Assert::assertEquals([
[
'Test1',
'Test2',
null,
null,
],
[
'Test3',
'Test4',
null,
null,
],
[
'Test5',
'Test6',
null,
null,
],
], $array);
}
public function endColumn(): string
{
return 'D';
}
};
$import->import('import-empty-rows.xlsx');
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/ImportableTest.php | tests/Concerns/ImportableTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Importer;
use Maatwebsite\Excel\Tests\TestCase;
use PHPUnit\Framework\Assert;
class ImportableTest extends TestCase
{
public function test_can_import_a_simple_xlsx_file()
{
$import = new class implements ToArray
{
use Importable;
/**
* @param array $array
*/
public function array(array $array)
{
Assert::assertEquals([
['test', 'test'],
['test', 'test'],
], $array);
}
};
$imported = $import->import('import.xlsx');
$this->assertInstanceOf(Importer::class, $imported);
}
public function test_can_import_a_simple_xlsx_file_from_uploaded_file()
{
$import = new class implements ToArray
{
use Importable;
/**
* @param array $array
*/
public function array(array $array)
{
Assert::assertEquals([
['test', 'test'],
['test', 'test'],
], $array);
}
};
$import->import($this->givenUploadedFile(__DIR__ . '/../Data/Disks/Local/import.xlsx'));
}
public function test_can_import_a_simple_csv_file_with_html_tags_inside()
{
$import = new class implements ToArray
{
use Importable;
/**
* @param array $array
*/
public function array(array $array)
{
Assert::assertEquals([
['key1', 'A', 'row1'],
['key2', 'B', '<p>row2</p>'],
['key3', 'C', 'row3'],
['key4', 'D', 'row4'],
['key5', 'E', 'row5'],
['key6', 'F', '<a href=/url-example">link</a>"'],
], $array);
}
};
$import->import('csv-with-html-tags.csv', 'local', Excel::CSV);
}
public function test_can_import_a_simple_xlsx_file_with_ignore_empty_set_to_true()
{
config()->set('excel.imports.ignore_empty', true);
$import = new class implements ToArray
{
use Importable;
/**
* @param array $array
*/
public function array(array $array)
{
Assert::assertEquals([
['test', 'test'],
['test', 'test'],
], $array);
}
};
$imported = $import->import('import-with-some-empty-rows.xlsx');
$this->assertInstanceOf(Importer::class, $imported);
}
public function test_can_import_a_simple_xlsx_file_with_ignore_empty_set_to_false()
{
config()->set('excel.imports.ignore_empty', false);
$import = new class implements ToArray
{
use Importable;
/**
* @param array $array
*/
public function array(array $array)
{
Assert::assertEquals([
['test', 'test'],
['test', 'test'],
['', ''],
['', ''],
], $array);
}
};
$imported = $import->import('import-with-some-empty-rows.xlsx');
$this->assertInstanceOf(Importer::class, $imported);
}
public function test_cannot_import_a_non_existing_xlsx_file()
{
$this->expectException(FileNotFoundException::class);
$import = new class
{
use Importable;
};
$import->import('doesnotexistanywhere.xlsx');
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/WithCustomQuerySizeTest.php | tests/Concerns/WithCustomQuerySizeTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Maatwebsite\Excel\Tests\Data\Stubs\AfterQueueExportJob;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\Group;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
use Maatwebsite\Excel\Tests\Data\Stubs\FromQueryWithCustomQuerySize;
use Maatwebsite\Excel\Tests\TestCase;
class WithCustomQuerySizeTest extends TestCase
{
/**
* Setup the test environment.
*/
protected function setUp(): void
{
parent::setUp();
$this->loadLaravelMigrations(['--database' => 'testing']);
$this->loadMigrationsFrom(dirname(__DIR__) . '/Data/Stubs/Database/Migrations');
$this->withFactories(dirname(__DIR__) . '/Data/Stubs/Database/Factories');
factory(Group::class)->times(5)->create()->each(function ($group) {
$group->users()->attach(factory(User::class)->times(rand(1, 3))->create());
});
config()->set('excel.exports.chunk_size', 2);
}
public function test_can_export_with_custom_count()
{
$export = new FromQueryWithCustomQuerySize();
$export->queue('export-from-query-with-count.xlsx', null, 'Xlsx')->chain([
new AfterQueueExportJob(dirname(__DIR__) . '/Data/Disks/Local/export-from-query-with-count.xlsx'),
]);
$actual = $this->readAsArray(dirname(__DIR__) . '/Data/Disks/Local/export-from-query-with-count.xlsx', 'Xlsx');
$this->assertCount(Group::count(), $actual);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/ExportableTest.php | tests/Concerns/ExportableTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Illuminate\Contracts\Support\Responsable;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Exporter;
use Maatwebsite\Excel\Tests\Data\Stubs\EmptyExport;
use Maatwebsite\Excel\Tests\TestCase;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
class ExportableTest extends TestCase
{
public function test_needs_to_have_a_file_name_when_downloading()
{
$this->expectException(\Maatwebsite\Excel\Exceptions\NoFilenameGivenException::class);
$this->expectExceptionMessage('A filename needs to be passed in order to download the export');
$export = new class
{
use Exportable;
};
$export->download();
}
public function test_needs_to_have_a_file_name_when_storing()
{
$this->expectException(\Maatwebsite\Excel\Exceptions\NoFilePathGivenException::class);
$this->expectExceptionMessage('A filepath needs to be passed in order to store the export');
$export = new class
{
use Exportable;
};
$export->store();
}
public function test_needs_to_have_a_file_name_when_queuing()
{
$this->expectException(\Maatwebsite\Excel\Exceptions\NoFilePathGivenException::class);
$this->expectExceptionMessage('A filepath needs to be passed in order to store the export');
$export = new class
{
use Exportable;
};
$export->queue();
}
public function test_responsable_needs_to_have_file_name_configured_inside_the_export()
{
$this->expectException(\Maatwebsite\Excel\Exceptions\NoFilenameGivenException::class);
$this->expectExceptionMessage('A filename needs to be passed in order to download the export');
$export = new class implements Responsable
{
use Exportable;
};
$export->toResponse(new Request());
}
public function test_is_responsable()
{
$export = new class implements Responsable
{
use Exportable;
protected $fileName = 'export.xlsx';
};
$this->assertInstanceOf(Responsable::class, $export);
$response = $export->toResponse(new Request());
$this->assertInstanceOf(BinaryFileResponse::class, $response);
}
public function test_can_have_customized_header()
{
$export = new class
{
use Exportable;
};
$response = $export->download(
'name.csv',
Excel::CSV,
[
'Content-Type' => 'text/csv',
]
);
$this->assertEquals('text/csv', $response->headers->get('Content-Type'));
}
public function test_can_set_custom_headers_in_export_class()
{
$export = new class
{
use Exportable;
protected $fileName = 'name.csv';
protected $writerType = Excel::CSV;
protected $headers = [
'Content-Type' => 'text/csv',
];
};
$response = $export->toResponse(request());
$this->assertEquals('text/csv', $response->headers->get('Content-Type'));
}
public function test_can_get_raw_export_contents()
{
$export = new EmptyExport;
$response = $export->raw(Excel::XLSX);
$this->assertNotEmpty($response);
}
public function test_can_have_customized_disk_options_when_storing()
{
$export = new EmptyExport;
$this->mock(Exporter::class)
->shouldReceive('store')->once()
->with($export, 'name.csv', 's3', Excel::CSV, ['visibility' => 'private']);
$export->store('name.csv', 's3', Excel::CSV, ['visibility' => 'private']);
}
public function test_can_have_customized_disk_options_when_queueing()
{
$export = new EmptyExport;
$this->mock(Exporter::class)
->shouldReceive('queue')->once()
->with($export, 'name.csv', 's3', Excel::CSV, ['visibility' => 'private']);
$export->queue('name.csv', 's3', Excel::CSV, ['visibility' => 'private']);
}
public function test_can_set_disk_options_in_export_class_when_storing()
{
$export = new class
{
use Exportable;
public $disk = 's3';
public $writerType = Excel::CSV;
public $diskOptions = ['visibility' => 'private'];
};
$this->mock(Exporter::class)
->shouldReceive('store')->once()
->with($export, 'name.csv', 's3', Excel::CSV, ['visibility' => 'private']);
$export->store('name.csv');
}
public function test_can_set_disk_options_in_export_class_when_queuing()
{
$export = new class
{
use Exportable;
public $disk = 's3';
public $writerType = Excel::CSV;
public $diskOptions = ['visibility' => 'private'];
};
$this->mock(Exporter::class)
->shouldReceive('queue')->once()
->with($export, 'name.csv', 's3', Excel::CSV, ['visibility' => 'private']);
$export->queue('name.csv');
}
public function test_can_override_export_class_disk_options_when_calling_store()
{
$export = new class
{
use Exportable;
public $diskOptions = ['visibility' => 'public'];
};
$this->mock(Exporter::class)
->shouldReceive('store')->once()
->with($export, 'name.csv', 's3', Excel::CSV, ['visibility' => 'private']);
$export->store('name.csv', 's3', Excel::CSV, ['visibility' => 'private']);
}
public function test_can_override_export_class_disk_options_when_calling_queue()
{
$export = new class
{
use Exportable;
public $diskOptions = ['visibility' => 'public'];
};
$this->mock(Exporter::class)
->shouldReceive('queue')->once()
->with($export, 'name.csv', 's3', Excel::CSV, ['visibility' => 'private']);
$export->queue('name.csv', 's3', Excel::CSV, ['visibility' => 'private']);
}
public function test_can_have_empty_disk_options_when_storing()
{
$export = new EmptyExport;
$this->mock(Exporter::class)
->shouldReceive('store')->once()
->with($export, 'name.csv', null, null, []);
$export->store('name.csv');
}
public function test_can_have_empty_disk_options_when_queueing()
{
$export = new EmptyExport;
$this->mock(Exporter::class)
->shouldReceive('queue')->once()
->with($export, 'name.csv', null, null, []);
$export->queue('name.csv');
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/WithCustomValueBinderTest.php | tests/Concerns/WithCustomValueBinderTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\WithCustomValueBinder;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Tests\TestCase;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PHPUnit\Framework\Assert;
class WithCustomValueBinderTest extends TestCase
{
public function test_can_set_a_value_binder_on_export()
{
Carbon::setTestNow(new Carbon('2018-08-07 18:00:00'));
$export = new class extends DefaultValueBinder implements FromCollection, WithCustomValueBinder
{
use Exportable;
/**
* @return Collection
*/
public function collection()
{
return collect([
[Carbon::now(), '10%'],
]);
}
/**
* {@inheritdoc}
*/
public function bindValue(Cell $cell, $value)
{
// Handle percentage
if (preg_match('/^\-?\d*\.?\d*\s?\%$/', $value)) {
$cell->setValueExplicit(
(float) str_replace('%', '', $value) / 100,
DataType::TYPE_NUMERIC
);
$cell
->getWorksheet()
->getStyle($cell->getCoordinate())
->getNumberFormat()
->setFormatCode(NumberFormat::FORMAT_PERCENTAGE_00);
return true;
}
// Handle Carbon dates
if ($value instanceof Carbon) {
$cell->setValueExplicit(
Date::dateTimeToExcel($value),
DataType::TYPE_NUMERIC
);
$cell->getWorksheet()
->getStyle($cell->getCoordinate())
->getNumberFormat()
->setFormatCode(NumberFormat::FORMAT_DATE_DATETIME);
return true;
}
return parent::bindValue($cell, $value);
}
};
$export->store('custom-value-binder-export.xlsx');
$spreadsheet = $this->read(__DIR__ . '/../Data/Disks/Local/custom-value-binder-export.xlsx', 'Xlsx');
$sheet = $spreadsheet->getActiveSheet();
// Check if the cell has the Excel date
$this->assertSame(Date::dateTimeToExcel(Carbon::now()), $sheet->getCell('A1')->getValue());
// Check if formatted as datetime
$this->assertEquals(NumberFormat::FORMAT_DATE_DATETIME, $sheet->getCell('A1')->getStyle()->getNumberFormat()->getFormatCode());
// Check if the cell has the converted percentage
$this->assertSame(0.1, $sheet->getCell('B1')->getValue());
// Check if formatted as percentage
$this->assertEquals(NumberFormat::FORMAT_PERCENTAGE_00, $sheet->getCell('B1')->getStyle()->getNumberFormat()->getFormatCode());
}
public function test_can_set_a_value_binder_on_import()
{
$import = new class extends DefaultValueBinder implements WithCustomValueBinder, ToArray
{
/**
* {@inheritdoc}
*/
public function bindValue(Cell $cell, $value)
{
if ($cell->getCoordinate() === 'B2') {
$cell->setValueExplicit($value, DataType::TYPE_STRING);
return true;
}
if ($cell->getRow() === 3) {
$date = Carbon::instance(Date::excelToDateTimeObject($value));
$cell->setValueExplicit($date->toDateTimeString(), DataType::TYPE_STRING);
return true;
}
return parent::bindValue($cell, $value);
}
/**
* @param array $array
*/
public function array(array $array)
{
Assert::assertSame([
[
'col1',
'col2',
],
[
1,
'2', // Forced to be a string
],
[
'2018-08-06 18:31:46', // Convert Excel datetime to datetime strings
'2018-08-07 00:00:00', // Convert Excel date to datetime strings
],
], $array);
}
};
$this->app->make(Excel::class)->import($import, 'value-binder-import.xlsx');
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/WithReadFilterTest.php | tests/Concerns/WithReadFilterTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\WithReadFilter;
use Maatwebsite\Excel\Tests\TestCase;
use PhpOffice\PhpSpreadsheet\Reader\IReadFilter;
use PHPUnit\Framework\Assert;
class WithReadFilterTest extends TestCase
{
public function test_can_register_custom_read_filter()
{
$export = new class implements WithReadFilter
{
use Importable;
public function readFilter(): IReadFilter
{
return new class implements IReadFilter
{
public function readCell($column, $row, $worksheetName = '')
{
// Assert read filter is being called.
// If assertion is not called, test will fail due to
// test having no other assertions.
Assert::assertTrue(true);
return true;
}
};
}
};
$export->toArray('import-users.xlsx');
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/WithMappedCellsTest.php | tests/Concerns/WithMappedCellsTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Illuminate\Support\Str;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithMappedCells;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
use Maatwebsite\Excel\Tests\TestCase;
use PHPUnit\Framework\Assert;
class WithMappedCellsTest extends TestCase
{
/**
* Setup the test environment.
*/
protected function setUp(): void
{
parent::setUp();
$this->loadLaravelMigrations(['--database' => 'testing']);
}
public function test_can_import_with_references_to_cells()
{
$import = new class implements WithMappedCells, ToArray
{
use Importable;
/**
* @return array
*/
public function mapping(): array
{
return [
'name' => 'B1',
'email' => 'B2',
];
}
/**
* @param array $array
*/
public function array(array $array)
{
Assert::assertEquals([
'name' => 'Patrick Brouwers',
'email' => 'patrick@maatwebsite.nl',
], $array);
}
};
$import->import('mapped-import.xlsx');
}
public function test_can_import_with_nested_references_to_cells()
{
$import = new class implements WithMappedCells, ToArray
{
use Importable;
/**
* @return array
*/
public function mapping(): array
{
return [
[
'name' => 'B1',
'email' => 'B2',
],
[
'name' => 'D1',
'email' => 'D2',
],
];
}
/**
* @param array $array
*/
public function array(array $array)
{
Assert::assertEquals([
[
'name' => 'Patrick Brouwers',
'email' => 'patrick@maatwebsite.nl',
],
[
'name' => 'Typingbeaver',
'email' => 'typingbeaver@mailbox.org',
],
], $array);
}
};
$import->import('mapped-import.xlsx');
}
public function test_can_import_with_references_to_cells_to_model()
{
$import = new class implements WithMappedCells, ToModel
{
use Importable;
/**
* @return array
*/
public function mapping(): array
{
return [
'name' => 'B1',
'email' => 'B2',
];
}
/**
* @param array $array
* @return User
*/
public function model(array $array)
{
Assert::assertEquals([
'name' => 'Patrick Brouwers',
'email' => 'patrick@maatwebsite.nl',
], $array);
$array['password'] = Str::random();
return new User($array);
}
};
$import->import('mapped-import.xlsx');
$this->assertDatabaseHas('users', [
'name' => 'Patrick Brouwers',
'email' => 'patrick@maatwebsite.nl',
]);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/WithBackgroundColorTest.php | tests/Concerns/WithBackgroundColorTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithBackgroundColor;
use Maatwebsite\Excel\Tests\TestCase;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Fill;
class WithBackgroundColorTest extends TestCase
{
public function test_can_configure_background_color_from_rgb_string()
{
$export = new class implements WithBackgroundColor
{
use Exportable;
public function backgroundColor()
{
return '000000';
}
};
$export->store('background-styles.xlsx');
$spreadsheet = $this->read(__DIR__ . '/../Data/Disks/Local/background-styles.xlsx', 'Xlsx');
$sheet = $spreadsheet->getDefaultStyle();
$this->assertEquals(Fill::FILL_SOLID, $sheet->getFill()->getFillType());
$this->assertEquals('000000', $sheet->getFill()->getStartColor()->getRGB());
}
public function test_can_configure_background_color_as_array()
{
$export = new class implements WithBackgroundColor
{
use Exportable;
public function backgroundColor()
{
return [
'fillType' => Fill::FILL_GRADIENT_LINEAR,
'startColor' => ['argb' => Color::COLOR_RED],
];
}
};
$export->store('background-styles.xlsx');
$spreadsheet = $this->read(__DIR__ . '/../Data/Disks/Local/background-styles.xlsx', 'Xlsx');
$sheet = $spreadsheet->getDefaultStyle();
$this->assertEquals(Fill::FILL_GRADIENT_LINEAR, $sheet->getFill()->getFillType());
$this->assertEquals(Color::COLOR_RED, $sheet->getFill()->getStartColor()->getARGB());
}
public function test_can_configure_background_color_with_color_instance()
{
$export = new class implements WithBackgroundColor
{
use Exportable;
public function backgroundColor()
{
return new Color(Color::COLOR_BLUE);
}
};
$export->store('background-styles.xlsx');
$spreadsheet = $this->read(__DIR__ . '/../Data/Disks/Local/background-styles.xlsx', 'Xlsx');
$sheet = $spreadsheet->getDefaultStyle();
$this->assertEquals(Fill::FILL_SOLID, $sheet->getFill()->getFillType());
$this->assertEquals(Color::COLOR_BLUE, $sheet->getFill()->getStartColor()->getARGB());
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/FromGeneratorTest.php | tests/Concerns/FromGeneratorTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Generator;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromGenerator;
use Maatwebsite\Excel\Tests\TestCase;
class FromGeneratorTest extends TestCase
{
public function test_can_export_from_generator()
{
$export = new class implements FromGenerator
{
use Exportable;
/**
* @return Generator;
*/
public function generator(): Generator
{
for ($i = 1; $i <= 2; $i++) {
yield ['test', 'test'];
}
}
};
$response = $export->store('from-generator-store.xlsx');
$this->assertTrue($response);
$contents = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/from-generator-store.xlsx', 'Xlsx');
$this->assertEquals(iterator_to_array($export->generator()), $contents);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/WithUpsertsTest.php | tests/Concerns/WithUpsertsTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Maatwebsite\Excel\Concerns\WithUpsertColumns;
use Maatwebsite\Excel\Concerns\WithUpserts;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
use Maatwebsite\Excel\Tests\TestCase;
class WithUpsertsTest extends TestCase
{
/**
* Setup the test environment.
*/
protected function setUp(): void
{
if (!method_exists(Builder::class, 'upsert')) {
$this->markTestSkipped('The upsert feature is available on Laravel 8.10+');
}
parent::setUp();
$this->loadLaravelMigrations(['--database' => 'testing']);
}
public function test_can_upsert_models_in_batches()
{
User::create([
'name' => 'Funny Banana',
'email' => 'patrick@maatwebsite.nl',
'password' => 'password',
]);
DB::connection()->enableQueryLog();
$import = new class implements ToModel, WithBatchInserts, WithUpserts
{
use Importable;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
/**
* @return string|array
*/
public function uniqueBy()
{
return 'email';
}
/**
* @return int
*/
public function batchSize(): int
{
return 2;
}
};
$import->import('import-users.xlsx');
$this->assertCount(1, DB::getQueryLog());
DB::connection()->disableQueryLog();
$this->assertDatabaseHas('users', [
'name' => 'Patrick Brouwers',
'email' => 'patrick@maatwebsite.nl',
'password' => 'secret',
]);
$this->assertDatabaseHas('users', [
'name' => 'Taylor Otwell',
'email' => 'taylor@laravel.com',
'password' => 'secret',
]);
$this->assertEquals(2, User::count());
}
public function test_can_upsert_models_in_rows()
{
User::create([
'name' => 'Funny Potato',
'email' => 'patrick@maatwebsite.nl',
'password' => 'password',
]);
DB::connection()->enableQueryLog();
$import = new class implements ToModel, WithUpserts
{
use Importable;
/**
* @param array $row
* @return Model|Model[]|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
/**
* @return string|array
*/
public function uniqueBy()
{
return 'email';
}
};
$import->import('import-users.xlsx');
$this->assertCount(2, DB::getQueryLog());
DB::connection()->disableQueryLog();
$this->assertDatabaseHas('users', [
'name' => 'Patrick Brouwers',
'email' => 'patrick@maatwebsite.nl',
'password' => 'secret',
]);
$this->assertDatabaseHas('users', [
'name' => 'Taylor Otwell',
'email' => 'taylor@laravel.com',
'password' => 'secret',
]);
$this->assertEquals(2, User::count());
}
public function test_can_upsert_models_in_batches_with_defined_upsert_columns()
{
User::create([
'name' => 'Funny Banana',
'email' => 'patrick@maatwebsite.nl',
'password' => 'password',
]);
DB::connection()->enableQueryLog();
$import = new class implements ToModel, WithBatchInserts, WithUpserts, WithUpsertColumns
{
use Importable;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
/**
* @return string|array
*/
public function uniqueBy()
{
return 'email';
}
/**
* @return array
*/
public function upsertColumns()
{
return ['name'];
}
/**
* @return int
*/
public function batchSize(): int
{
return 2;
}
};
$import->import('import-users.xlsx');
$this->assertCount(1, DB::getQueryLog());
DB::connection()->disableQueryLog();
$this->assertDatabaseHas('users', [
'name' => 'Patrick Brouwers',
'email' => 'patrick@maatwebsite.nl',
'password' => 'password',
]);
$this->assertDatabaseHas('users', [
'name' => 'Taylor Otwell',
'email' => 'taylor@laravel.com',
'password' => 'secret',
]);
$this->assertEquals(2, User::count());
}
public function test_can_upsert_models_in_rows_with_defined_upsert_columns()
{
User::create([
'name' => 'Funny Potato',
'email' => 'patrick@maatwebsite.nl',
'password' => 'password',
]);
DB::connection()->enableQueryLog();
$import = new class implements ToModel, WithUpserts, WithUpsertColumns
{
use Importable;
/**
* @param array $row
* @return Model|Model[]|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
/**
* @return string|array
*/
public function uniqueBy()
{
return 'email';
}
/**
* @return array
*/
public function upsertColumns()
{
return ['name'];
}
};
$import->import('import-users.xlsx');
$this->assertCount(2, DB::getQueryLog());
DB::connection()->disableQueryLog();
$this->assertDatabaseHas('users', [
'name' => 'Patrick Brouwers',
'email' => 'patrick@maatwebsite.nl',
'password' => 'password',
]);
$this->assertDatabaseHas('users', [
'name' => 'Taylor Otwell',
'email' => 'taylor@laravel.com',
'password' => 'secret',
]);
$this->assertEquals(2, User::count());
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/SkipsOnErrorTest.php | tests/Concerns/SkipsOnErrorTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\QueryException;
use Illuminate\Validation\Rule;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\OnEachRow;
use Maatwebsite\Excel\Concerns\SkipsErrors;
use Maatwebsite\Excel\Concerns\SkipsOnError;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithValidation;
use Maatwebsite\Excel\Row;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
use Maatwebsite\Excel\Tests\TestCase;
use Maatwebsite\Excel\Validators\ValidationException;
use PHPUnit\Framework\Assert;
use Throwable;
class SkipsOnErrorTest extends TestCase
{
/**
* Setup the test environment.
*/
protected function setUp(): void
{
parent::setUp();
$this->loadLaravelMigrations(['--database' => 'testing']);
}
public function test_can_skip_on_error()
{
$import = new class implements ToModel, SkipsOnError
{
use Importable;
public $errors = 0;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
/**
* @param Throwable $e
*/
public function onError(Throwable $e)
{
Assert::assertInstanceOf(QueryException::class, $e);
Assert::stringContains($e->getMessage(), 'Duplicate entry \'patrick@maatwebsite.nl\'');
$this->errors++;
}
};
$import->import('import-users-with-duplicates.xlsx');
$this->assertEquals(1, $import->errors);
// Shouldn't have rollbacked other imported rows.
$this->assertDatabaseHas('users', [
'email' => 'patrick@maatwebsite.nl',
]);
// Should have skipped inserting
$this->assertDatabaseMissing('users', [
'email' => 'taylor@laravel.com',
]);
}
public function test_can_skip_errors_and_collect_all_errors_at_the_end()
{
$import = new class implements ToModel, SkipsOnError
{
use Importable, SkipsErrors;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
};
$import->import('import-users-with-duplicates.xlsx');
$this->assertCount(1, $import->errors());
/** @var Throwable $e */
$e = $import->errors()->first();
$this->assertInstanceOf(QueryException::class, $e);
$this->stringContains($e->getMessage(), 'Duplicate entry \'patrick@maatwebsite.nl\'');
// Shouldn't have rollbacked other imported rows.
$this->assertDatabaseHas('users', [
'email' => 'patrick@maatwebsite.nl',
]);
// Should have skipped inserting
$this->assertDatabaseMissing('users', [
'email' => 'taylor@laravel.com',
]);
}
public function test_can_skip_on_error_when_using_oneachrow_with_validation()
{
$import = new class implements OnEachRow, WithValidation, SkipsOnError
{
use Importable;
public $errors = 0;
public $processedRows = 0;
/**
* @param Row $row
*/
public function onRow(Row $row)
{
$this->processedRows++;
// This will be called for valid rows
$rowArray = $row->toArray();
User::create([
'name' => $rowArray[0],
'email' => $rowArray[1],
'password' => 'secret',
]);
}
/**
* @return array
*/
public function rules(): array
{
return [
'1' => Rule::in(['patrick@maatwebsite.nl']),
];
}
/**
* @param Throwable $e
*/
public function onError(Throwable $e)
{
Assert::assertInstanceOf(ValidationException::class, $e);
Assert::stringContains($e->getMessage(), 'The selected 1 is invalid');
$this->errors++;
}
};
$import->import('import-users.xlsx');
$this->assertEquals(1, $import->errors);
$this->assertEquals(1, $import->processedRows); // Only the valid row should be processed
// Should have inserted the valid row
$this->assertDatabaseHas('users', [
'email' => 'patrick@maatwebsite.nl',
]);
// Should have skipped inserting the invalid row
$this->assertDatabaseMissing('users', [
'email' => 'taylor@laravel.com',
]);
}
public function test_can_skip_errors_and_collect_all_errors_when_using_oneachrow_with_validation()
{
$import = new class implements OnEachRow, WithValidation, SkipsOnError
{
use Importable, SkipsErrors;
public $processedRows = 0;
/**
* @param Row $row
*/
public function onRow(Row $row)
{
$this->processedRows++;
// This will be called for valid rows
$rowArray = $row->toArray();
User::create([
'name' => $rowArray[0],
'email' => $rowArray[1],
'password' => 'secret',
]);
}
/**
* @return array
*/
public function rules(): array
{
return [
'1' => Rule::in(['patrick@maatwebsite.nl']),
];
}
};
$import->import('import-users.xlsx');
$this->assertCount(1, $import->errors());
$this->assertEquals(1, $import->processedRows); // Only the valid row should be processed
/** @var Throwable $e */
$e = $import->errors()->first();
$this->assertInstanceOf(ValidationException::class, $e);
$this->stringContains($e->getMessage(), 'The selected 1 is invalid');
// Should have inserted the valid row
$this->assertDatabaseHas('users', [
'email' => 'patrick@maatwebsite.nl',
]);
// Should have skipped inserting the invalid row
$this->assertDatabaseMissing('users', [
'email' => 'taylor@laravel.com',
]);
}
public function test_can_skip_on_error_when_exception_thrown_in_onrow()
{
$import = new class implements OnEachRow, SkipsOnError
{
use Importable;
public $errors = 0;
public $processedRows = 0;
/**
* @param Row $row
*/
public function onRow(Row $row)
{
$this->processedRows++;
$rowArray = $row->toArray();
// Throw an exception for the second row (Taylor Otwell)
if ($rowArray[1] === 'taylor@laravel.com') {
throw new \Exception('Custom error in onRow for Taylor');
}
User::create([
'name' => $rowArray[0],
'email' => $rowArray[1],
'password' => 'secret',
]);
}
/**
* @param Throwable $e
*/
public function onError(Throwable $e)
{
Assert::assertInstanceOf(\Exception::class, $e);
Assert::assertEquals('Custom error in onRow for Taylor', $e->getMessage());
$this->errors++;
}
};
$import->import('import-users.xlsx');
$this->assertEquals(1, $import->errors);
$this->assertEquals(2, $import->processedRows); // Both rows should be processed, but one throws exception
// Should have inserted the valid row
$this->assertDatabaseHas('users', [
'email' => 'patrick@maatwebsite.nl',
]);
// Should have skipped inserting the row that threw exception
$this->assertDatabaseMissing('users', [
'email' => 'taylor@laravel.com',
]);
}
public function test_can_skip_errors_and_collect_all_errors_when_exception_thrown_in_onrow()
{
$import = new class implements OnEachRow, SkipsOnError
{
use Importable, SkipsErrors;
public $processedRows = 0;
/**
* @param Row $row
*/
public function onRow(Row $row)
{
$this->processedRows++;
$rowArray = $row->toArray();
// Throw an exception for the second row (Taylor Otwell)
if ($rowArray[1] === 'taylor@laravel.com') {
throw new \RuntimeException('Runtime error in onRow for Taylor');
}
User::create([
'name' => $rowArray[0],
'email' => $rowArray[1],
'password' => 'secret',
]);
}
};
$import->import('import-users.xlsx');
$this->assertCount(1, $import->errors());
$this->assertEquals(2, $import->processedRows); // Both rows should be processed, but one throws exception
/** @var Throwable $e */
$e = $import->errors()->first();
$this->assertInstanceOf(\RuntimeException::class, $e);
$this->assertEquals('Runtime error in onRow for Taylor', $e->getMessage());
// Should have inserted the valid row
$this->assertDatabaseHas('users', [
'email' => 'patrick@maatwebsite.nl',
]);
// Should have skipped inserting the row that threw exception
$this->assertDatabaseMissing('users', [
'email' => 'taylor@laravel.com',
]);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/FromCollectionTest.php | tests/Concerns/FromCollectionTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Illuminate\Foundation\Bus\PendingDispatch;
use Maatwebsite\Excel\Tests\Data\Stubs\EloquentLazyCollectionExport;
use Maatwebsite\Excel\Tests\Data\Stubs\EloquentLazyCollectionQueuedExport;
use Maatwebsite\Excel\Tests\Data\Stubs\QueuedExport;
use Maatwebsite\Excel\Tests\Data\Stubs\SheetWith100Rows;
use Maatwebsite\Excel\Tests\TestCase;
class FromCollectionTest extends TestCase
{
public function test_can_export_from_collection()
{
$export = new SheetWith100Rows('A');
$response = $export->store('from-collection-store.xlsx');
$this->assertTrue($response);
$contents = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/from-collection-store.xlsx', 'Xlsx');
$this->assertEquals($export->collection()->toArray(), $contents);
}
public function test_can_export_with_multiple_sheets_from_collection()
{
$export = new QueuedExport();
$response = $export->store('multiple-sheets-collection-store.xlsx');
$this->assertTrue($response);
foreach ($export->sheets() as $sheetIndex => $sheet) {
$spreadsheet = $this->read(
__DIR__ . '/../Data/Disks/Local/multiple-sheets-collection-store.xlsx',
'Xlsx'
);
$worksheet = $spreadsheet->getSheet($sheetIndex);
$this->assertEquals($sheet->collection()->toArray(), $worksheet->toArray());
$this->assertEquals($sheet->title(), $worksheet->getTitle());
}
}
public function test_can_export_from_lazy_collection()
{
if (!class_exists('\Illuminate\Support\LazyCollection')) {
$this->markTestSkipped('Skipping test because LazyCollection is not supported');
return;
}
$export = new EloquentLazyCollectionExport();
$export->store('from-lazy-collection-store.xlsx');
$contents = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/from-lazy-collection-store.xlsx', 'Xlsx');
$this->assertEquals(
$export->collection()->map(
function (array $item) {
return array_values($item);
}
)->toArray(),
$contents
);
}
public function test_can_export_from_lazy_collection_with_queue()
{
if (!class_exists('\Illuminate\Support\LazyCollection')) {
$this->markTestSkipped('Skipping test because LazyCollection is not supported');
return;
}
$export = new EloquentLazyCollectionQueuedExport();
$response = $export->queue('from-lazy-collection-store.xlsx');
$this->assertTrue($response instanceof PendingDispatch);
// Force dispatching via __destruct.
unset($response);
$contents = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/from-lazy-collection-store.xlsx', 'Xlsx');
$this->assertEquals(
$export->collection()->map(
function (array $item) {
return array_values($item);
}
)->toArray(),
$contents
);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/ToArrayTest.php | tests/Concerns/ToArrayTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Tests\TestCase;
use PHPUnit\Framework\Assert;
class ToArrayTest extends TestCase
{
public function test_can_import_to_array()
{
$import = new class implements ToArray
{
use Importable;
public $called = false;
/**
* @param array $array
*/
public function array(array $array)
{
$this->called = true;
Assert::assertEquals([
['test', 'test'],
['test', 'test'],
], $array);
}
};
$import->import('import.xlsx');
$this->assertTrue($import->called);
}
public function test_can_import_multiple_sheets_to_array()
{
$import = new class implements ToArray
{
use Importable;
public $called = 0;
/**
* @param array $array
*/
public function array(array $array)
{
$this->called++;
$sheetNumber = $this->called;
Assert::assertEquals([
[$sheetNumber . '.A1', $sheetNumber . '.B1'],
[$sheetNumber . '.A2', $sheetNumber . '.B2'],
], $array);
}
};
$import->import('import-multiple-sheets.xlsx');
$this->assertEquals(2, $import->called);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/FromQueryTest.php | tests/Concerns/FromQueryTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\Group;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
use Maatwebsite\Excel\Tests\Data\Stubs\FromGroupUsersQueuedQueryExport;
use Maatwebsite\Excel\Tests\Data\Stubs\FromNestedArraysQueryExport;
use Maatwebsite\Excel\Tests\Data\Stubs\FromNonEloquentQueryExport;
use Maatwebsite\Excel\Tests\Data\Stubs\FromUsersQueryExport;
use Maatwebsite\Excel\Tests\Data\Stubs\FromUsersQueryExportWithEagerLoad;
use Maatwebsite\Excel\Tests\Data\Stubs\FromUsersQueryExportWithPrepareRows;
use Maatwebsite\Excel\Tests\Data\Stubs\FromUsersQueryWithJoinExport;
use Maatwebsite\Excel\Tests\Data\Stubs\FromUsersScoutExport;
use Maatwebsite\Excel\Tests\TestCase;
class FromQueryTest extends TestCase
{
/**
* Setup the test environment.
*/
protected function setUp(): void
{
parent::setUp();
$this->loadLaravelMigrations(['--database' => 'testing']);
$this->withFactories(__DIR__ . '/../Data/Stubs/Database/Factories');
$this->loadMigrationsFrom(dirname(__DIR__) . '/Data/Stubs/Database/Migrations');
$group = factory(Group::class)->create([
'name' => 'Group 1',
]);
factory(User::class)->times(100)->create()->each(function (User $user) use ($group) {
$user->groups()->save($group);
});
$group_two = factory(Group::class)->create([
'name' => 'Group 2',
]);
factory(User::class)->times(5)->create()->each(function (User $user) use ($group_two) {
$user->groups()->save($group_two);
});
}
public function test_can_export_from_query()
{
$export = new FromUsersQueryExport;
$response = $export->store('from-query-store.xlsx');
$this->assertTrue($response);
$contents = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/from-query-store.xlsx', 'Xlsx');
$allUsers = $export->query()->get()->map(function (User $user) {
return array_values($user->toArray());
})->toArray();
$this->assertEquals($allUsers, $contents);
}
public function test_can_export_from_query_with_join()
{
$export = new FromUsersQueryWithJoinExport();
$response = $export->store('from-query-store.xlsx');
$this->assertTrue($response);
$contents = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/from-query-store.xlsx', 'Xlsx');
$allUsers = $export->query->get()->map(function (User $user) {
return array_values($user->toArray());
})->toArray();
$this->assertEquals($allUsers, $contents);
}
public function test_can_export_from_relation_query_queued()
{
$export = new FromGroupUsersQueuedQueryExport();
$export->queue('from-query-store.xlsx');
$contents = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/from-query-store.xlsx', 'Xlsx');
$allUsers = $export->query()->get()->map(function ($row) use ($export) {
return $export->map($row);
})->toArray();
$this->assertEquals($allUsers, $contents);
}
public function test_can_export_from_query_with_eager_loads()
{
DB::connection()->enableQueryLog();
$export = new FromUsersQueryExportWithEagerLoad();
$response = $export->store('from-query-with-eager-loads.xlsx');
$this->assertTrue($response);
// Should be 2 queries:
// 1) select all users
// 2) eager load query for groups
$this->assertCount(2, DB::getQueryLog());
DB::connection()->disableQueryLog();
$contents = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/from-query-with-eager-loads.xlsx', 'Xlsx');
$allUsers = $export->query()->get()->map(function (User $user) use ($export) {
return $export->map($user);
})->toArray();
$this->assertEquals($allUsers, $contents);
}
public function test_can_export_from_query_with_eager_loads_and_queued()
{
DB::connection()->enableQueryLog();
$export = new FromUsersQueryExportWithEagerLoad();
$export->queue('from-query-with-eager-loads.xlsx');
// Should be 3 queries:
// 1) Count users to create chunked queues
// 2) select all users
// 3) eager load query for groups
$this->assertCount(3, DB::getQueryLog());
DB::connection()->disableQueryLog();
$contents = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/from-query-with-eager-loads.xlsx', 'Xlsx');
$allUsers = $export->query()->get()->map(function (User $user) use ($export) {
return $export->map($user);
})->toArray();
$this->assertEquals($allUsers, $contents);
}
public function test_can_export_from_query_builder_without_using_eloquent()
{
$export = new FromNonEloquentQueryExport();
$response = $export->store('from-query-without-eloquent.xlsx');
$this->assertTrue($response);
$contents = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/from-query-without-eloquent.xlsx', 'Xlsx');
$allUsers = $export->query()->get()->map(function ($row) {
return array_values((array) $row);
})->all();
$this->assertEquals($allUsers, $contents);
}
public function test_can_export_from_query_builder_without_using_eloquent_and_queued()
{
$export = new FromNonEloquentQueryExport();
$export->queue('from-query-without-eloquent.xlsx');
$contents = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/from-query-without-eloquent.xlsx', 'Xlsx');
$allUsers = $export->query()->get()->map(function ($row) {
return array_values((array) $row);
})->all();
$this->assertEquals($allUsers, $contents);
}
public function test_can_export_from_query_builder_with_nested_arrays()
{
$export = new FromNestedArraysQueryExport();
$response = $export->store('from-query-with-nested-arrays.xlsx');
$this->assertTrue($response);
$contents = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/from-query-with-nested-arrays.xlsx', 'Xlsx');
$this->assertEquals($this->format_nested_arrays_expected_data($export->query()->get()), $contents);
}
public function test_can_export_from_query_builder_with_nested_arrays_queued()
{
$export = new FromNestedArraysQueryExport();
$export->queue('from-query-with-nested-arrays.xlsx');
$contents = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/from-query-with-nested-arrays.xlsx', 'Xlsx');
$this->assertEquals($this->format_nested_arrays_expected_data($export->query()->get()), $contents);
}
public function test_can_export_from_query_with_batch_caching()
{
config()->set('excel.cache.driver', 'batch');
$export = new FromUsersQueryExport;
$response = $export->store('from-query-store.xlsx');
$this->assertTrue($response);
$contents = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/from-query-store.xlsx', 'Xlsx');
$allUsers = $export->query()->get()->map(function (User $user) {
return array_values($user->toArray());
})->toArray();
$this->assertEquals($allUsers, $contents);
}
public function test_can_export_from_query_with_prepare_rows()
{
$export = new FromUsersQueryExportWithPrepareRows;
$this->assertTrue(method_exists($export, 'prepareRows'));
$response = $export->store('from-query-store.xlsx');
$this->assertTrue($response);
$contents = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/from-query-store.xlsx', 'Xlsx');
$allUsers = $export->query()->get()->map(function (User $user) {
$user->name .= '_prepared_name';
return array_values($user->toArray());
})->toArray();
$this->assertEquals($allUsers, $contents);
}
public function test_can_export_from_scout()
{
if (!class_exists('\Laravel\Scout\Engines\DatabaseEngine')) {
$this->markTestSkipped('Laravel Scout is too old');
return;
}
$export = new FromUsersScoutExport;
$response = $export->store('from-scout-store.xlsx');
$this->assertTrue($response);
$contents = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/from-scout-store.xlsx', 'Xlsx');
$allUsers = $export->query()->get()->map(function (User $user) {
return array_values($user->toArray());
})->toArray();
$this->assertEquals($allUsers, $contents);
}
protected function format_nested_arrays_expected_data($groups)
{
$expected = [];
foreach ($groups as $group) {
$group_row = [$group->name, ''];
foreach ($group->users as $key => $user) {
if ($key === 0) {
$group_row[1] = $user->email;
$expected[] = $group_row;
continue;
}
$expected[] = ['', $user->email];
}
}
return $expected;
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/WithHeadingsTest.php | tests/Concerns/WithHeadingsTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithCustomStartCell;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Tests\TestCase;
class WithHeadingsTest extends TestCase
{
public function test_can_export_from_collection_with_heading_row()
{
$export = new class implements FromCollection, WithHeadings
{
use Exportable;
/**
* @return Collection
*/
public function collection()
{
return collect([
['A1', 'B1', 'C1'],
['A2', 'B2', 'C2'],
]);
}
/**
* @return array
*/
public function headings(): array
{
return ['A', 'B', 'C'];
}
};
$response = $export->store('with-heading-store.xlsx');
$this->assertTrue($response);
$actual = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/with-heading-store.xlsx', 'Xlsx');
$expected = [
['A', 'B', 'C'],
['A1', 'B1', 'C1'],
['A2', 'B2', 'C2'],
];
$this->assertEquals($expected, $actual);
}
public function test_can_export_from_collection_with_multiple_heading_rows()
{
$export = new class implements FromCollection, WithHeadings
{
use Exportable;
/**
* @return Collection
*/
public function collection()
{
return collect([
['A1', 'B1', 'C1'],
['A2', 'B2', 'C2'],
]);
}
/**
* @return array
*/
public function headings(): array
{
return [
['A', 'B', 'C'],
['Aa', 'Bb', 'Cc'],
];
}
};
$response = $export->store('with-heading-store.xlsx');
$this->assertTrue($response);
$actual = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/with-heading-store.xlsx', 'Xlsx');
$expected = [
['A', 'B', 'C'],
['Aa', 'Bb', 'Cc'],
['A1', 'B1', 'C1'],
['A2', 'B2', 'C2'],
];
$this->assertEquals($expected, $actual);
}
public function test_can_export_from_collection_with_heading_row_with_custom_start_cell()
{
$export = new class implements FromCollection, WithHeadings, WithCustomStartCell
{
use Exportable;
/**
* @return Collection
*/
public function collection()
{
return collect([
['A1', 'B1', 'C1'],
['A2', 'B2', 'C2'],
]);
}
/**
* @return array
*/
public function headings(): array
{
return ['A', 'B', 'C'];
}
/**
* @return string
*/
public function startCell(): string
{
return 'B2';
}
};
$response = $export->store('with-heading-store.xlsx');
$this->assertTrue($response);
$actual = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/with-heading-store.xlsx', 'Xlsx');
$expected = [
[null, null, null, null],
[null, 'A', 'B', 'C'],
[null, 'A1', 'B1', 'C1'],
[null, 'A2', 'B2', 'C2'],
];
$this->assertEquals($expected, $actual);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/ToCollectionTest.php | tests/Concerns/ToCollectionTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Tests\TestCase;
use PHPUnit\Framework\Assert;
class ToCollectionTest extends TestCase
{
public function test_can_import_to_collection()
{
$import = new class implements ToCollection
{
use Importable;
public $called = false;
/**
* @param Collection $collection
*/
public function collection(Collection $collection)
{
$this->called = true;
Assert::assertEquals([
['test', 'test'],
['test', 'test'],
], $collection->toArray());
}
};
$import->import('import.xlsx');
$this->assertTrue($import->called);
}
public function test_can_import_multiple_sheets_to_collection()
{
$import = new class implements ToCollection
{
use Importable;
public $called = 0;
/**
* @param Collection $collection
*/
public function collection(Collection $collection)
{
$this->called++;
$sheetNumber = $this->called;
Assert::assertEquals([
[$sheetNumber . '.A1', $sheetNumber . '.B1'],
[$sheetNumber . '.A2', $sheetNumber . '.B2'],
], $collection->toArray());
}
};
$import->import('import-multiple-sheets.xlsx');
$this->assertEquals(2, $import->called);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/WithChunkReadingTest.php | tests/Concerns/WithChunkReadingTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use DateTime;
use Exception;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithFormatData;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Maatwebsite\Excel\Events\AfterImport;
use Maatwebsite\Excel\Events\BeforeImport;
use Maatwebsite\Excel\Events\ImportFailed;
use Maatwebsite\Excel\Reader;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\Group;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
use Maatwebsite\Excel\Tests\TestCase;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PHPUnit\Framework\Assert;
use Throwable;
class WithChunkReadingTest extends TestCase
{
/**
* Setup the test environment.
*/
protected function setUp(): void
{
parent::setUp();
$this->loadLaravelMigrations(['--database' => 'testing']);
$this->loadMigrationsFrom(dirname(__DIR__) . '/Data/Stubs/Database/Migrations');
}
public function test_can_import_to_model_in_chunks_un()
{
DB::connection()->enableQueryLog();
$import = new class implements ToModel, WithChunkReading, WithEvents
{
use Importable;
public $before = 0;
public $after = 0;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
/**
* @return int
*/
public function chunkSize(): int
{
return 1;
}
/**
* @return array
*/
public function registerEvents(): array
{
return [
BeforeImport::class => function (BeforeImport $event) {
Assert::assertInstanceOf(Reader::class, $event->reader);
$this->before++;
},
AfterImport::class => function (AfterImport $event) {
Assert::assertInstanceOf(Reader::class, $event->reader);
$this->after++;
},
];
}
};
$import->import('import-users.xlsx');
$this->assertCount(2, DB::getQueryLog());
DB::connection()->disableQueryLog();
$this->assertEquals(1, $import->before, 'BeforeImport was not called or more than once.');
$this->assertEquals(1, $import->after, 'AfterImport was not called or more than once.');
}
public function test_can_import_to_model_in_chunks_and_insert_in_batches()
{
DB::connection()->enableQueryLog();
$import = new class implements ToModel, WithChunkReading, WithBatchInserts
{
use Importable;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new Group([
'name' => $row[0],
]);
}
/**
* @return int
*/
public function chunkSize(): int
{
return 1000;
}
/**
* @return int
*/
public function batchSize(): int
{
return 1000;
}
};
$import->import('import-batches.xlsx');
$this->assertCount(5000 / $import->batchSize(), DB::getQueryLog());
DB::connection()->disableQueryLog();
}
public function test_can_import_to_model_in_chunks_and_insert_in_batches_with_heading_row()
{
DB::connection()->enableQueryLog();
$import = new class implements ToModel, WithChunkReading, WithBatchInserts, WithHeadingRow
{
use Importable;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new Group([
'name' => $row['name'],
]);
}
/**
* @return int
*/
public function chunkSize(): int
{
return 1000;
}
/**
* @return int
*/
public function batchSize(): int
{
return 1000;
}
};
$import->import('import-batches-with-heading-row.xlsx');
$this->assertCount(5000 / $import->batchSize(), DB::getQueryLog());
DB::connection()->disableQueryLog();
}
public function test_can_import_csv_in_chunks_and_insert_in_batches()
{
DB::connection()->enableQueryLog();
$import = new class implements ToModel, WithChunkReading, WithBatchInserts
{
use Importable;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new Group([
'name' => $row[0],
]);
}
/**
* @return int
*/
public function chunkSize(): int
{
return 1000;
}
/**
* @return int
*/
public function batchSize(): int
{
return 1000;
}
};
$import->import('import-batches.csv');
$this->assertCount(10, DB::getQueryLog());
DB::connection()->disableQueryLog();
}
public function test_can_import_to_model_in_chunks_and_insert_in_batches_with_multiple_sheets()
{
DB::connection()->enableQueryLog();
$import = new class implements ToModel, WithChunkReading, WithBatchInserts
{
use Importable;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new Group([
'name' => $row[0],
]);
}
/**
* @return int
*/
public function chunkSize(): int
{
return 1000;
}
/**
* @return int
*/
public function batchSize(): int
{
return 1000;
}
};
$import->import('import-batches-multiple-sheets.xlsx');
$this->assertCount(10, DB::getQueryLog());
DB::connection()->disableQueryLog();
}
public function test_can_import_to_array_in_chunks()
{
$import = new class implements ToArray, WithChunkReading, WithFormatData
{
use Importable;
public $called = 0;
/**
* @param array $array
*/
public function array(array $array)
{
$this->called++;
Assert::assertCount(100, $array);
}
/**
* @return int
*/
public function chunkSize(): int
{
return 100;
}
};
$import->import('import-batches.xlsx');
$this->assertEquals(50, $import->called);
}
public function test_can_import_to_model_in_chunks_and_insert_in_batches_with_multiple_sheets_objects_by_index()
{
DB::connection()->enableQueryLog();
$import = new class implements WithMultipleSheets, WithChunkReading
{
use Importable;
/**
* @return int
*/
public function chunkSize(): int
{
return 1000;
}
/**
* @return array
*/
public function sheets(): array
{
return [
new class implements ToModel, WithBatchInserts
{
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new Group([
'name' => $row[0],
]);
}
/**
* @return int
*/
public function batchSize(): int
{
return 1000;
}
},
new class implements ToModel, WithBatchInserts
{
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new Group([
'name' => $row[0],
]);
}
/**
* @return int
*/
public function batchSize(): int
{
return 2000;
}
},
];
}
};
$import->import('import-batches-multiple-sheets.xlsx');
$this->assertCount(10, DB::getQueryLog());
DB::connection()->disableQueryLog();
}
public function test_can_import_to_model_in_chunks_and_insert_in_batches_with_multiple_sheets_objects_by_name()
{
DB::connection()->enableQueryLog();
$import = new class implements WithMultipleSheets, WithChunkReading
{
use Importable;
/**
* @return int
*/
public function chunkSize(): int
{
return 1000;
}
/**
* @return array
*/
public function sheets(): array
{
return [
'Worksheet' => new class implements ToModel, WithBatchInserts
{
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new Group([
'name' => $row[0],
]);
}
/**
* @return int
*/
public function batchSize(): int
{
return 1000;
}
},
'Worksheet2' => new class implements ToModel, WithBatchInserts
{
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new Group([
'name' => $row[0],
]);
}
/**
* @return int
*/
public function batchSize(): int
{
return 2000;
}
},
];
}
};
$import->import('import-batches-multiple-sheets.xlsx');
$this->assertCount(10, DB::getQueryLog());
DB::connection()->disableQueryLog();
}
public function test_can_catch_job_failed_in_chunks()
{
$import = new class implements ToModel, WithChunkReading, WithEvents
{
use Importable;
public $failed = false;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
throw new Exception('Something went wrong in the chunk');
}
/**
* @return int
*/
public function chunkSize(): int
{
return 1;
}
/**
* @return array
*/
public function registerEvents(): array
{
return [
ImportFailed::class => function (ImportFailed $event) {
Assert::assertInstanceOf(Throwable::class, $event->getException());
Assert::assertEquals('Something went wrong in the chunk', $event->e->getMessage());
$this->failed = true;
},
];
}
};
try {
$import->import('import-users.xlsx');
} catch (Throwable $e) {
$this->assertInstanceOf(Exception::class, $e);
$this->assertEquals('Something went wrong in the chunk', $e->getMessage());
}
$this->assertTrue($import->failed, 'ImportFailed event was not called.');
}
public function test_can_import_to_array_and_format_in_chunks()
{
config()->set('excel.imports.read_only', false);
$import = new class implements ToArray, WithChunkReading, WithFormatData
{
use Importable;
/**
* @param array $array
*/
public function array(array $array)
{
Assert::assertCount(2, $array);
Assert::assertCount(1, $array[0]);
Assert::assertCount(1, $array[1]);
Assert::assertIsString($array[0][0]);
Assert::assertIsString($array[1][0]);
Assert::assertEquals('01/12/22', $array[0][0]);
Assert::assertEquals('2023-02-20', $array[1][0]);
}
/**
* @return int
*/
public function chunkSize(): int
{
return 2;
}
};
$import->import('import-batches-with-date.xlsx');
}
public function test_can_import_to_array_in_chunks_without_formatting()
{
config()->set('excel.imports.read_only', true);
$import = new class implements ToArray, WithChunkReading
{
use Importable;
/**
* @param array $array
*/
public function array(array $array)
{
Assert::assertCount(2, $array);
Assert::assertCount(1, $array[0]);
Assert::assertCount(1, $array[1]);
Assert::assertIsInt($array[0][0]);
Assert::assertIsInt($array[1][0]);
Assert::assertEquals((int) Date::dateTimeToExcel(DateTime::createFromFormat('Y-m-d', '2022-12-01')->setTime(0, 0, 0, 0)), $array[0][0]);
Assert::assertEquals((int) Date::dateTimeToExcel(DateTime::createFromFormat('Y-m-d', '2023-02-20')->setTime(0, 0, 0, 0)), $array[1][0]);
}
/**
* @return int
*/
public function chunkSize(): int
{
return 2;
}
};
$import->import('import-batches-with-date.xlsx');
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Concerns/SkipsEmptyRowsTest.php | tests/Concerns/SkipsEmptyRowsTest.php | <?php
namespace Maatwebsite\Excel\Tests\Concerns;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\OnEachRow;
use Maatwebsite\Excel\Concerns\SkipsEmptyRows;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Row;
use Maatwebsite\Excel\Tests\TestCase;
use PHPUnit\Framework\Assert;
class SkipsEmptyRowsTest extends TestCase
{
public function test_skips_empty_rows_when_importing_to_collection()
{
$import = new class implements ToCollection, SkipsEmptyRows
{
use Importable;
public $called = false;
/**
* @param Collection $collection
*/
public function collection(Collection $collection)
{
$this->called = true;
Assert::assertEquals([
['Test1', 'Test2'],
['Test3', 'Test4'],
['Test5', 'Test6'],
], $collection->toArray());
}
};
$import->import('import-empty-rows.xlsx');
$this->assertTrue($import->called);
}
public function test_skips_empty_rows_when_importing_on_each_row()
{
$import = new class implements OnEachRow, SkipsEmptyRows
{
use Importable;
public $rows = 0;
/**
* @param Row $row
*/
public function onRow(Row $row)
{
Assert::assertFalse($row->isEmpty());
$this->rows++;
}
};
$import->import('import-empty-rows.xlsx');
$this->assertEquals(3, $import->rows);
}
public function test_skips_empty_rows_when_importing_to_model()
{
$import = new class implements ToModel, SkipsEmptyRows
{
use Importable;
public $rows = 0;
/**
* @param array $row
* @return Model|Model[]|null
*/
public function model(array $row)
{
$this->rows++;
return null;
}
};
$import->import('import-empty-rows.xlsx');
$this->assertEquals(3, $import->rows);
}
public function test_custom_skips_rows_when_importing_to_collection()
{
$import = new class implements SkipsEmptyRows, ToCollection
{
use Importable;
public $called = false;
/**
* @param Collection $collection
*/
public function collection(Collection $collection)
{
$this->called = true;
Assert::assertEquals([
['Test1', 'Test2'],
['Test3', 'Test4'],
], $collection->toArray());
}
public function isEmptyWhen(array $row)
{
return $row[0] == 'Test5' && $row[1] == 'Test6';
}
};
$import->import('import-empty-rows.xlsx');
$this->assertTrue($import->called);
}
public function test_custom_skips_rows_when_importing_to_model()
{
$import = new class implements SkipsEmptyRows, ToModel
{
use Importable;
public $called = false;
/**
* @param array $row
*/
public function model(array $row)
{
Assert::assertEquals('Not empty', $row[0]);
}
public function isEmptyWhen(array $row): bool
{
$this->called = true;
return $row[0] === 'Empty';
}
};
$import->import('skip-empty-rows-with-is-empty-when.xlsx');
$this->assertTrue($import->called);
}
public function test_custom_skips_rows_when_using_oneachrow()
{
$import = new class implements SkipsEmptyRows, OnEachRow
{
use Importable;
public $called = false;
/**
* @param array $row
*/
public function onRow(Row $row)
{
Assert::assertEquals('Not empty', $row[0]);
}
public function isEmptyWhen(array $row): bool
{
$this->called = true;
return $row[0] === 'Empty';
}
};
$import->import('skip-empty-rows-with-is-empty-when.xlsx');
$this->assertTrue($import->called);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Validators/RowValidatorTest.php | tests/Validators/RowValidatorTest.php | <?php
namespace Maatwebsite\Excel\Tests\Validators;
use Illuminate\Contracts\Validation\Factory;
use Maatwebsite\Excel\Tests\TestCase;
use Maatwebsite\Excel\Validators\RowValidator;
class RowValidatorTest extends TestCase
{
/**
* The RowValidator instance.
*/
protected $validator;
/**
* Set up the test.
*/
public function setUp(): void
{
parent::setUp();
$this->validator = new RowValidator(app(Factory::class));
}
public function test_format_rule_with_array_input()
{
$rules = ['rule1', 'rule2'];
$result = $this->callPrivateMethod('formatRule', [$rules]);
$this->assertEquals($rules, $result);
}
public function test_format_rule_with_object_input()
{
$rule = new \stdClass();
$result = $this->callPrivateMethod('formatRule', [$rule]);
$this->assertEquals($rule, $result);
}
public function test_format_rule_with_callable_input()
{
$rule = function () {
return 'callable';
};
$result = $this->callPrivateMethod('formatRule', [$rule]);
$this->assertEquals($rule, $result);
}
public function test_format_rule_with_required_without_all()
{
$rule = 'required_without_all:first_name,last_name';
$result = $this->callPrivateMethod('formatRule', [$rule]);
$this->assertEquals('required_without_all:*.first_name,*.last_name', $result);
}
public function test_format_rule_with_required_without()
{
$rule = 'required_without:first_name';
$result = $this->callPrivateMethod('formatRule', [$rule]);
$this->assertEquals('required_without:*.first_name', $result);
}
public function test_format_rule_with_string_input_not_matching_pattern()
{
$rule = 'rule';
$result = $this->callPrivateMethod('formatRule', [$rule]);
$this->assertEquals($rule, $result);
}
/**
* Call a private function.
*
* @param string $name
* @param array $args
* @return mixed
*/
public function callPrivateMethod(string $name, array $args)
{
$method = new \ReflectionMethod(RowValidator::class, $name);
$method->setAccessible(true);
return $method->invokeArgs($this->validator, $args);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/FromUsersQueryExportWithPrepareRows.php | tests/Data/Stubs/FromUsersQueryExportWithPrepareRows.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithCustomChunkSize;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
class FromUsersQueryExportWithPrepareRows implements FromQuery, WithCustomChunkSize
{
use Exportable;
/**
* @return Builder|EloquentBuilder|Relation
*/
public function query()
{
return User::query();
}
/**
* @return int
*/
public function chunkSize(): int
{
return 10;
}
/**
* @param iterable $rows
* @return iterable
*/
public function prepareRows($rows)
{
return (new Collection($rows))->map(function ($user) {
$user->name .= '_prepared_name';
return $user;
})->toArray();
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/AfterQueueImportJob.php | tests/Data/Stubs/AfterQueueImportJob.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\DB;
use PHPUnit\Framework\Assert;
class AfterQueueImportJob implements ShouldQueue
{
use Queueable;
/**
* @var int
*/
private $totalRows;
/**
* @param int $totalRows
*/
public function __construct(int $totalRows)
{
$this->totalRows = $totalRows;
}
public function handle()
{
Assert::assertEquals($this->totalRows, DB::table('groups')->count('id'));
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/WithMappingExport.php | tests/Data/Stubs/WithMappingExport.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithMapping;
class WithMappingExport implements FromCollection, WithMapping
{
use Exportable;
/**
* @return Collection
*/
public function collection()
{
return collect([
['A1', 'B1', 'C1'],
['A2', 'B2', 'C2'],
]);
}
/**
* @param mixed $row
* @return array
*/
public function map($row): array
{
return [
'mapped-' . $row[0],
'mapped-' . $row[1],
'mapped-' . $row[2],
];
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/QueuedExportWithFailedEvents.php | tests/Data/Stubs/QueuedExportWithFailedEvents.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
use Exception;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Maatwebsite\Excel\Events\BeforeExport;
use PHPUnit\Framework\Assert;
use Throwable;
class QueuedExportWithFailedEvents implements WithMultipleSheets, WithEvents
{
use Exportable;
/**
* @return SheetWith100Rows[]
*/
public function sheets(): array
{
return [
new SheetWith100Rows('A'),
new SheetWith100Rows('B'),
new SheetWith100Rows('C'),
];
}
/**
* @param Throwable $exception
*/
public function failed(Throwable $exception)
{
Assert::assertEquals('catch exception from QueueExport job', $exception->getMessage());
app()->bind('queue-has-failed-from-queue-export-job', function () {
return true;
});
}
/**
* @return array
*/
public function registerEvents(): array
{
return [
BeforeExport::class => function () {
throw new Exception('catch exception from QueueExport job');
},
];
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/FromUsersQueryExport.php | tests/Data/Stubs/FromUsersQueryExport.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Query\Builder;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithCustomChunkSize;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
class FromUsersQueryExport implements FromQuery, WithCustomChunkSize
{
use Exportable;
/**
* @return Builder|EloquentBuilder|Relation
*/
public function query()
{
return User::query();
}
/**
* @return int
*/
public function chunkSize(): int
{
return 10;
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/FromNestedArraysQueryExport.php | tests/Data/Stubs/FromNestedArraysQueryExport.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Query\Builder;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\Group;
class FromNestedArraysQueryExport implements FromQuery, WithMapping
{
use Exportable;
/**
* @return Builder|EloquentBuilder|Relation
*/
public function query()
{
$query = Group::with('users');
return $query;
}
/**
* @param Group $row
* @return array
*/
public function map($row): array
{
$rows = [];
$sub_row = [$row->name, ''];
$count = 0;
foreach ($row->users as $user) {
if ($count === 0) {
$sub_row[1] = $user['email'];
} else {
$sub_row = ['', $user['email']];
}
$rows[] = $sub_row;
$count++;
}
if ($count === 0) {
$rows[] = $sub_row;
}
return $rows;
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/SheetForUsersFromView.php | tests/Data/Stubs/SheetForUsersFromView.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromView;
class SheetForUsersFromView implements FromView
{
use Exportable;
/**
* @var Collection
*/
protected $users;
/**
* @param Collection $users
*/
public function __construct(Collection $users)
{
$this->users = $users;
}
/**
* @return View
*/
public function view(): View
{
return view('users', [
'users' => $this->users,
]);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/FromQueryWithCustomQuerySize.php | tests/Data/Stubs/FromQueryWithCustomQuerySize.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithCustomQuerySize;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\Group;
class FromQueryWithCustomQuerySize implements FromQuery, WithCustomQuerySize, WithMapping, ShouldQueue
{
use Exportable;
/**
* @return Builder|EloquentBuilder|Relation
*/
public function query()
{
$query = Group::with('users')
->join('group_user', 'groups.id', '=', 'group_user.group_id')
->select('groups.*', DB::raw('count(group_user.user_id) as number_of_users'))
->groupBy('groups.id')
->orderBy('number_of_users');
return $query;
}
/**
* @return int
*/
public function querySize(): int
{
return Group::has('users')->count();
}
/**
* @param Group $row
* @return array
*/
public function map($row): array
{
return [
$row->id,
$row->name,
$row->number_of_users,
];
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/FromGroupUsersQueuedQueryExport.php | tests/Data/Stubs/FromGroupUsersQueuedQueryExport.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Query\Builder;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithCustomChunkSize;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\Group;
class FromGroupUsersQueuedQueryExport implements FromQuery, WithCustomChunkSize, ShouldQueue, WithMapping
{
use Exportable;
/**
* @return Builder|EloquentBuilder|Relation
*/
public function query()
{
return Group::first()->users();
}
/**
* @param mixed $row
* @return array
*/
public function map($row): array
{
return [
$row->name,
$row->email,
];
}
/**
* @return int
*/
public function chunkSize(): int
{
return 10;
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/CustomTransactionHandler.php | tests/Data/Stubs/CustomTransactionHandler.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
use Maatwebsite\Excel\Transactions\TransactionHandler;
class CustomTransactionHandler implements TransactionHandler
{
public function __invoke(callable $callback)
{
return $callback();
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/QueuedExport.php | tests/Data/Stubs/QueuedExport.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
class QueuedExport implements WithMultipleSheets
{
use Exportable;
/**
* @return SheetWith100Rows[]
*/
public function sheets(): array
{
return [
new SheetWith100Rows('A'),
new SheetWith100Rows('B'),
new SheetWith100Rows('C'),
];
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/QueuedExportWithLocalePreferences.php | tests/Data/Stubs/QueuedExportWithLocalePreferences.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
use Illuminate\Contracts\Translation\HasLocalePreference;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
use PHPUnit\Framework\Assert;
class QueuedExportWithLocalePreferences implements FromCollection, HasLocalePreference
{
use Exportable;
/**
* @var string
*/
protected $locale;
/**
* QueuedExportWithLocalePreferences constructor.
*
* @param string $locale
*/
public function __construct(string $locale)
{
$this->locale = $locale;
}
/**
* @return Collection
*/
public function collection()
{
return collect([
new User([
'firstname' => 'Patrick',
'lastname' => 'Brouwers',
]),
]);
}
/**
* @return string|null
*/
public function preferredLocale()
{
return $this->locale;
}
/**
* @param iterable $rows
* @return iterable
*/
public function prepareRows($rows)
{
Assert::assertEquals('ru', app()->getLocale());
app()->bind('queue-has-correct-locale', function () {
return true;
});
return $rows;
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/QueueImportWithoutJobChaining.php | tests/Data/Stubs/QueueImportWithoutJobChaining.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\ShouldQueueWithoutChain;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterImport;
use Maatwebsite\Excel\Events\BeforeImport;
use Maatwebsite\Excel\Reader;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
use PHPUnit\Framework\Assert;
class QueueImportWithoutJobChaining implements ToModel, WithChunkReading, WithEvents, ShouldQueueWithoutChain
{
use Importable;
public $queue;
public $before = false;
public $after = false;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
'password' => 'secret',
]);
}
/**
* @return int
*/
public function chunkSize(): int
{
return 1;
}
/**
* @return array
*/
public function registerEvents(): array
{
return [
BeforeImport::class => function (BeforeImport $event) {
Assert::assertInstanceOf(Reader::class, $event->reader);
$this->before = true;
},
AfterImport::class => function (AfterImport $event) {
Assert::assertInstanceOf(Reader::class, $event->reader);
$this->after = true;
},
];
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/ChainedJobStub.php | tests/Data/Stubs/ChainedJobStub.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
class ChainedJobStub implements ShouldQueue
{
use Queueable;
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/ShouldQueueExport.php | tests/Data/Stubs/ShouldQueueExport.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
use Illuminate\Contracts\Queue\ShouldQueue;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
class ShouldQueueExport implements WithMultipleSheets, ShouldQueue
{
use Exportable;
/**
* @return SheetWith100Rows[]
*/
public function sheets(): array
{
return [
new SheetWith100Rows('A'),
new SheetWith100Rows('B'),
new SheetWith100Rows('C'),
];
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/ExportWithEventsChunks.php | tests/Data/Stubs/ExportWithEventsChunks.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Builder;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithCustomChunkSize;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterChunk;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
use PHPUnit\Framework\Assert;
class ExportWithEventsChunks implements WithEvents, FromQuery, ShouldQueue, WithCustomChunkSize
{
use Exportable;
public static $calledEvent = 0;
public function registerEvents(): array
{
return [
AfterChunk::class => function (AfterChunk $event) {
ExportWithEventsChunks::$calledEvent++;
Assert::assertInstanceOf(ExportWithEventsChunks::class, $event->getConcernable());
},
];
}
public function query(): Builder
{
return User::query();
}
public function chunkSize(): int
{
return 1;
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/ImportWithEventsChunksAndBatches.php | tests/Data/Stubs/ImportWithEventsChunksAndBatches.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Events\AfterBatch;
use Maatwebsite\Excel\Events\AfterChunk;
class ImportWithEventsChunksAndBatches extends ImportWithEvents implements WithBatchInserts, ToModel, WithChunkReading
{
/**
* @var callable
*/
public $afterBatch;
/**
* @var callable
*/
public $afterChunk;
/**
* @return array
*/
public function registerEvents(): array
{
return parent::registerEvents() + [
AfterBatch::class => $this->afterBatch ?? function () {
},
AfterChunk::class => $this->afterChunk ?? function () {
},
];
}
public function model(array $row)
{
}
public function batchSize(): int
{
return 100;
}
public function chunkSize(): int
{
return 500;
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/EloquentLazyCollectionQueuedExport.php | tests/Data/Stubs/EloquentLazyCollectionQueuedExport.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\LazyCollection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
class EloquentLazyCollectionQueuedExport implements FromCollection, ShouldQueue
{
use Exportable;
public function collection(): LazyCollection
{
return collect([
[
'firstname' => 'Patrick',
'lastname' => 'Brouwers',
],
[
'firstname' => 'Patrick',
'lastname' => 'Brouwers',
],
[
'firstname' => 'Patrick',
'lastname' => 'Brouwers',
],
[
'firstname' => 'Patrick',
'lastname' => 'Brouwers',
],
])->lazy();
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/ImportWithEvents.php | tests/Data/Stubs/ImportWithEvents.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterImport;
use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Events\BeforeImport;
use Maatwebsite\Excel\Events\BeforeSheet;
class ImportWithEvents implements WithEvents
{
use Importable;
/**
* @var callable
*/
public $beforeImport;
/**
* @var callable
*/
public $afterImport;
/**
* @var callable
*/
public $beforeSheet;
/**
* @var callable
*/
public $afterSheet;
/**
* @return array
*/
public function registerEvents(): array
{
return [
BeforeImport::class => $this->beforeImport ?? function () {
},
AfterImport::class => $this->afterImport ?? function () {
},
BeforeSheet::class => $this->beforeSheet ?? function () {
},
AfterSheet::class => $this->afterSheet ?? function () {
},
];
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/QueuedImportWithFailure.php | tests/Data/Stubs/QueuedImportWithFailure.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Model;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\Group;
class QueuedImportWithFailure implements ShouldQueue, ToModel, WithChunkReading
{
use Importable;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
throw new \Exception('Something went wrong in the chunk');
return new Group([
'name' => $row[0],
]);
}
/**
* @return int
*/
public function chunkSize(): int
{
return 100;
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/ExportWithEvents.php | tests/Data/Stubs/ExportWithEvents.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Events\BeforeExport;
use Maatwebsite\Excel\Events\BeforeSheet;
use Maatwebsite\Excel\Events\BeforeWriting;
class ExportWithEvents implements WithEvents
{
use Exportable;
/**
* @var callable
*/
public $beforeExport;
/**
* @var callable
*/
public $beforeWriting;
/**
* @var callable
*/
public $beforeSheet;
/**
* @var callable
*/
public $afterSheet;
/**
* @return array
*/
public function registerEvents(): array
{
return [
BeforeExport::class => $this->beforeExport ?? function () {
},
BeforeWriting::class => $this->beforeWriting ?? function () {
},
BeforeSheet::class => $this->beforeSheet ?? function () {
},
AfterSheet::class => $this->afterSheet ?? function () {
},
];
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/FromUsersQueryExportWithEagerLoad.php | tests/Data/Stubs/FromUsersQueryExportWithEagerLoad.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Query\Builder;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
class FromUsersQueryExportWithEagerLoad implements FromQuery, WithMapping
{
use Exportable;
/**
* @return Builder|EloquentBuilder|Relation
*/
public function query()
{
return User::query()->with([
'groups' => function ($query) {
$query->where('name', 'Group 1');
},
])->withCount('groups');
}
/**
* @param mixed $row
* @return array
*/
public function map($row): array
{
return [
$row->name,
$row->groups_count,
$row->groups->implode('name', ', '),
];
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/FromUsersScoutExport.php | tests/Data/Stubs/FromUsersScoutExport.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Query\Builder;
use Laravel\Scout\Builder as ScoutBuilder;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithCustomChunkSize;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
class FromUsersScoutExport implements FromQuery, WithCustomChunkSize
{
use Exportable;
/**
* @return Builder|EloquentBuilder|Relation|ScoutBuilder
*/
public function query()
{
return new ScoutBuilder(new User, '');
}
/**
* @return int
*/
public function chunkSize(): int
{
return 10;
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/QueuedImport.php | tests/Data/Stubs/QueuedImport.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Model;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\Group;
class QueuedImport implements ShouldQueue, ToModel, WithChunkReading, WithBatchInserts
{
use Importable;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new Group([
'name' => $row[0],
]);
}
/**
* @return int
*/
public function batchSize(): int
{
return 100;
}
/**
* @return int
*/
public function chunkSize(): int
{
return 100;
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/EloquentLazyCollectionExport.php | tests/Data/Stubs/EloquentLazyCollectionExport.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
use Illuminate\Support\LazyCollection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
class EloquentLazyCollectionExport implements FromCollection
{
use Exportable;
public function collection(): LazyCollection
{
return collect([
[
'firstname' => 'Patrick',
'lastname' => 'Brouwers',
],
[
'firstname' => 'Patrick',
'lastname' => 'Brouwers',
],
[
'firstname' => 'Patrick',
'lastname' => 'Brouwers',
],
[
'firstname' => 'Patrick',
'lastname' => 'Brouwers',
],
])->lazy();
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/SheetWith100Rows.php | tests/Data/Stubs/SheetWith100Rows.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\RegistersEventListeners;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithTitle;
use Maatwebsite\Excel\Events\BeforeWriting;
use Maatwebsite\Excel\Tests\TestCase;
use Maatwebsite\Excel\Writer;
class SheetWith100Rows implements FromCollection, WithTitle, ShouldAutoSize, WithEvents
{
use Exportable, RegistersEventListeners;
/**
* @var string
*/
private $title;
/**
* @param string $title
*/
public function __construct(string $title)
{
$this->title = $title;
}
/**
* @return Collection
*/
public function collection()
{
$collection = new Collection;
for ($i = 0; $i < 100; $i++) {
$row = new Collection();
for ($j = 0; $j < 5; $j++) {
$row[] = $this->title() . '-' . $i . '-' . $j;
}
$collection->push($row);
}
return $collection;
}
/**
* @return string
*/
public function title(): string
{
return $this->title;
}
/**
* @param BeforeWriting $event
*/
public static function beforeWriting(BeforeWriting $event)
{
TestCase::assertInstanceOf(Writer::class, $event->writer);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/FromUsersQueryWithJoinExport.php | tests/Data/Stubs/FromUsersQueryWithJoinExport.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Query\Builder;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithCustomChunkSize;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
class FromUsersQueryWithJoinExport implements FromQuery, WithCustomChunkSize
{
use Exportable;
public $query;
public function __construct()
{
$this->query = User::query();
}
/**
* @return Builder|EloquentBuilder|Relation
*/
public function query()
{
return $this->query
->join(
'group_user',
'group_user.user_id',
'=',
'users.id'
)
->select('users.*', 'group_user.group_id as gid');
}
/**
* @return int
*/
public function chunkSize(): int
{
return 10;
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/QueuedImportWithRetryUntil.php | tests/Data/Stubs/QueuedImportWithRetryUntil.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Model;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\Group;
class QueuedImportWithRetryUntil implements ShouldQueue, ToModel, WithChunkReading
{
use Importable;
/**
* @param array $row
* @return Model|null
*/
public function model(array $row)
{
return new Group([
'name' => $row[0],
]);
}
/**
* @return int
*/
public function chunkSize(): int
{
return 100;
}
/**
* Determine the time at which the job should timeout.
*
* @return \DateTime
*/
public function retryUntil()
{
throw new \Exception('Job reached retryUntil method');
return now()->addSeconds(5);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/BeforeExportListener.php | tests/Data/Stubs/BeforeExportListener.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
class BeforeExportListener
{
/**
* @var callable
*/
private $assertions;
/**
* @param callable $assertions
*/
public function __construct(callable $assertions)
{
$this->assertions = $assertions;
}
public function __invoke()
{
($this->assertions)(...func_get_args());
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/FromViewExportWithMultipleSheets.php | tests/Data/Stubs/FromViewExportWithMultipleSheets.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
class FromViewExportWithMultipleSheets implements WithMultipleSheets
{
use Exportable;
/**
* @var Collection
*/
protected $users;
/**
* @param Collection $users
*/
public function __construct(Collection $users)
{
$this->users = $users;
}
/**
* @return SheetForUsersFromView[]
*/
public function sheets(): array
{
return [
new SheetForUsersFromView($this->users->forPage(1, 100)),
new SheetForUsersFromView($this->users->forPage(2, 100)),
new SheetForUsersFromView($this->users->forPage(3, 100)),
];
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/WithTitleExport.php | tests/Data/Stubs/WithTitleExport.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithTitle;
class WithTitleExport implements WithTitle
{
use Exportable;
/**
* @return string
*/
public function title(): string
{
return 'given-title';
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/QueuedExportWithFailedHook.php | tests/Data/Stubs/QueuedExportWithFailedHook.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
use Exception;
use Illuminate\Database\Eloquent\Collection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
use PHPUnit\Framework\Assert;
class QueuedExportWithFailedHook implements FromCollection, WithMapping
{
use Exportable;
/**
* @var bool
*/
public $failed = false;
/**
* @return Collection
*/
public function collection()
{
return collect([
new User([
'firstname' => 'Patrick',
'lastname' => 'Brouwers',
]),
]);
}
/**
* @param User $user
* @return array
*/
public function map($user): array
{
throw new Exception('we expect this');
}
/**
* @param Exception $exception
*/
public function failed(Exception $exception)
{
Assert::assertEquals('we expect this', $exception->getMessage());
app()->bind('queue-has-failed', function () {
return true;
});
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/CustomSheetConcern.php | tests/Data/Stubs/CustomSheetConcern.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
interface CustomSheetConcern
{
public function custom();
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
SpartnerNL/Laravel-Excel | https://github.com/SpartnerNL/Laravel-Excel/blob/b31b6f4eabd8b5ff3f873e808abd183d3f5cb244/tests/Data/Stubs/AfterQueueExportJob.php | tests/Data/Stubs/AfterQueueExportJob.php | <?php
namespace Maatwebsite\Excel\Tests\Data\Stubs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Maatwebsite\Excel\Tests\TestCase;
class AfterQueueExportJob implements ShouldQueue
{
use Queueable;
/**
* @var string
*/
private $filePath;
/**
* @param string $filePath
*/
public function __construct(string $filePath)
{
$this->filePath = $filePath;
}
public function handle()
{
TestCase::assertFileExists($this->filePath);
}
}
| php | MIT | b31b6f4eabd8b5ff3f873e808abd183d3f5cb244 | 2026-01-04T15:03:06.866936Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.