WithStartRowTest.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. namespace Maatwebsite\Excel\Tests\Concerns;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Maatwebsite\Excel\Concerns\Importable;
  5. use Maatwebsite\Excel\Concerns\ToArray;
  6. use Maatwebsite\Excel\Concerns\ToModel;
  7. use Maatwebsite\Excel\Concerns\WithStartRow;
  8. use Maatwebsite\Excel\Tests\Data\Stubs\Database\User;
  9. use Maatwebsite\Excel\Tests\TestCase;
  10. use PHPUnit\Framework\Assert;
  11. class WithStartRowTest extends TestCase
  12. {
  13. /**
  14. * Setup the test environment.
  15. */
  16. protected function setUp(): void
  17. {
  18. parent::setUp();
  19. $this->loadLaravelMigrations(['--database' => 'testing']);
  20. }
  21. /**
  22. * @test
  23. */
  24. public function can_import_each_row_to_model_with_different_start_row()
  25. {
  26. $import = new class implements ToModel, WithStartRow
  27. {
  28. use Importable;
  29. /**
  30. * @param array $row
  31. * @return Model
  32. */
  33. public function model(array $row): Model
  34. {
  35. return new User([
  36. 'name' => $row[0],
  37. 'email' => $row[1],
  38. 'password' => 'secret',
  39. ]);
  40. }
  41. /**
  42. * @return int
  43. */
  44. public function startRow(): int
  45. {
  46. return 5;
  47. }
  48. };
  49. $import->import('import-users-with-different-heading-row.xlsx');
  50. $this->assertDatabaseHas('users', [
  51. 'name' => 'Patrick Brouwers',
  52. 'email' => 'patrick@maatwebsite.nl',
  53. ]);
  54. $this->assertDatabaseHas('users', [
  55. 'name' => 'Taylor Otwell',
  56. 'email' => 'taylor@laravel.com',
  57. ]);
  58. }
  59. /**
  60. * @test
  61. */
  62. public function can_import_to_array_with_start_row()
  63. {
  64. $import = new class implements ToArray, WithStartRow
  65. {
  66. use Importable;
  67. /**
  68. * @param array $array
  69. */
  70. public function array(array $array)
  71. {
  72. Assert::assertEquals([
  73. [
  74. 'Patrick Brouwers',
  75. 'patrick@maatwebsite.nl',
  76. ],
  77. [
  78. 'Taylor Otwell',
  79. 'taylor@laravel.com',
  80. ],
  81. ], $array);
  82. }
  83. /**
  84. * @return int
  85. */
  86. public function startRow(): int
  87. {
  88. return 5;
  89. }
  90. };
  91. $import->import('import-users-with-different-heading-row.xlsx');
  92. }
  93. }