Exporter.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace Tests\Exporters;
  3. use Dcat\EasyExcel\Excel;
  4. trait Exporter
  5. {
  6. protected $tempFiles = [];
  7. protected function assertSingleSheet(string $file, $key, array $compares)
  8. {
  9. // 读取
  10. $sheetsArray = Excel::import($file)->toArray();
  11. $this->assertIsArray($sheetsArray);
  12. $this->assertEquals(count($sheetsArray), 1);
  13. $this->assertTrue(isset($sheetsArray[$key]));
  14. $this->assertEquals(array_values($sheetsArray[$key]), $compares);
  15. }
  16. /**
  17. * @param string $storePath
  18. * @param array $users1
  19. * @param array $users2
  20. *
  21. * @throws \Box\Spout\Common\Exception\IOException
  22. * @throws \Box\Spout\Common\Exception\UnsupportedTypeException
  23. * @throws \League\Flysystem\FileNotFoundException
  24. */
  25. protected function assertSheets($storePath, $users1, $users2)
  26. {
  27. // 读取
  28. $sheetsArray = Excel::import($storePath)->toArray();
  29. $this->assertIsArray($sheetsArray);
  30. $this->assertEquals(count($sheetsArray), 2);
  31. $this->assertTrue(isset($sheetsArray['sheet1']));
  32. $this->assertTrue(isset($sheetsArray['sheet2']));
  33. $this->assertEquals(array_values($sheetsArray['sheet1']), $users1);
  34. $this->assertEquals(array_values($sheetsArray['sheet2']), $users2);
  35. }
  36. protected function generateTempFilePath(string $type)
  37. {
  38. return $this->tempFiles[] = __DIR__.'/../resources/'
  39. .uniqid(microtime(true).mt_rand(0, 1000))
  40. .'.'.$type;
  41. }
  42. public function tearDown(): void
  43. {
  44. parent::tearDown();
  45. // 删除临时文件
  46. foreach ($this->tempFiles as $file) {
  47. if (is_file($file)) {
  48. @unlink($file);
  49. }
  50. }
  51. }
  52. }