-
-
Notifications
You must be signed in to change notification settings - Fork 247
/
Importable.php
81 lines (72 loc) · 2.2 KB
/
Importable.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
namespace Rap2hpoutre\FastExcel;
use Box\Spout\Reader\ReaderFactory;
use Illuminate\Support\Collection;
/**
* Trait Importable.
*
* @property bool $with_header
*/
trait Importable
{
/**
* @var int
*/
private $sheet_number = 1;
/**
* @param string $path
*
* @return mixed
*/
abstract protected function getType($path);
/**
* @param \Box\Spout\Reader\ReaderInterface|\Box\Spout\Writer\WriterInterface $reader_or_writer
*
* @return mixed
*/
abstract protected function setOptions(&$reader_or_writer);
/**
* @param string $path
* @param callable|null $callback
*
* @throws \Box\Spout\Common\Exception\IOException
* @throws \Box\Spout\Common\Exception\UnsupportedTypeException
* @throws \Box\Spout\Reader\Exception\ReaderNotOpenedException
*
* @return Collection
*/
public function import($path, callable $callback = null)
{
$headers = [];
$collection = [];
$count_header = 0;
$reader = ReaderFactory::create($this->getType($path));
$this->setOptions($reader);
/* @var \Box\Spout\Reader\ReaderInterface $reader */
$reader->open($path);
foreach ($reader->getSheetIterator() as $key => $sheet) {
if ($this->sheet_number != $key) {
continue;
}
if ($this->with_header) {
foreach ($sheet->getRowIterator() as $k => $row) {
if ($k == 1) {
$headers = $row;
$count_header = count($headers);
continue;
}
if ($count_header > $count_row = count($row)) {
$row = array_merge($row, array_fill(0, $count_header - $count_row, null));
}
$collection[] = $callback ? $callback(array_combine($headers, $row)) : array_combine($headers, $row);
}
} else {
foreach ($sheet->getRowIterator() as $row) {
$collection[] = $row;
}
}
}
$reader->close();
return collect($collection);
}
}