WithMappingTest.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. <?php
  2. namespace Maatwebsite\Excel\Tests\Concerns;
  3. use Maatwebsite\Excel\Concerns\Exportable;
  4. use Maatwebsite\Excel\Concerns\FromArray;
  5. use Maatwebsite\Excel\Concerns\WithMapping;
  6. use Maatwebsite\Excel\Tests\Data\Stubs\WithMappingExport;
  7. use Maatwebsite\Excel\Tests\TestCase;
  8. class WithMappingTest extends TestCase
  9. {
  10. /**
  11. * @test
  12. */
  13. public function can_export_with_heading()
  14. {
  15. $export = new WithMappingExport();
  16. $response = $export->store('with-mapping-store.xlsx');
  17. $this->assertTrue($response);
  18. $actual = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/with-mapping-store.xlsx', 'Xlsx');
  19. $expected = [
  20. [
  21. 'mapped-A1',
  22. 'mapped-B1',
  23. 'mapped-C1',
  24. ],
  25. [
  26. 'mapped-A2',
  27. 'mapped-B2',
  28. 'mapped-C2',
  29. ],
  30. ];
  31. $this->assertEquals($expected, $actual);
  32. }
  33. /**
  34. * @test
  35. */
  36. public function can_return_multiple_rows_in_map()
  37. {
  38. $export = new class implements FromArray, WithMapping
  39. {
  40. use Exportable;
  41. /**
  42. * @return array
  43. */
  44. public function array(): array
  45. {
  46. return [
  47. ['id' => 1],
  48. ['id' => 2],
  49. ['id' => 3],
  50. ];
  51. }
  52. /**
  53. * @param mixed $row
  54. * @return array
  55. */
  56. public function map($row): array
  57. {
  58. return [
  59. [$row['id']],
  60. [$row['id']],
  61. ];
  62. }
  63. };
  64. $response = $export->store('with-mapping-store.xlsx');
  65. $this->assertTrue($response);
  66. $actual = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/with-mapping-store.xlsx', 'Xlsx');
  67. $this->assertCount(6, $actual);
  68. }
  69. /**
  70. * @test
  71. */
  72. public function json_array_columns_shouldnt_be_detected_as_multiple_rows()
  73. {
  74. $export = new class implements FromArray
  75. {
  76. use Exportable;
  77. /**
  78. * @return array
  79. */
  80. public function array(): array
  81. {
  82. return [
  83. ['id' => 1, 'json' => ['other_id' => 1]],
  84. ['id' => 2, 'json' => ['other_id' => 2]],
  85. ['id' => 3, 'json' => ['other_id' => 3]],
  86. ];
  87. }
  88. };
  89. $response = $export->store('with-mapping-store.xlsx');
  90. $this->assertTrue($response);
  91. $actual = $this->readAsArray(__DIR__ . '/../Data/Disks/Local/with-mapping-store.xlsx', 'Xlsx');
  92. $this->assertCount(3, $actual);
  93. $this->assertEquals([
  94. [1, \json_encode(['other_id' => 1])],
  95. [2, \json_encode(['other_id' => 2])],
  96. [3, \json_encode(['other_id' => 3])],
  97. ], $actual);
  98. }
  99. }