1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Box\Spout\Reader\Common\Manager; |
4
|
|
|
|
5
|
|
|
use Box\Spout\Common\Entity\Row; |
6
|
|
|
use Box\Spout\Reader\Common\Creator\InternalEntityFactoryInterface; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Class RowManager |
10
|
|
|
*/ |
11
|
|
|
class RowManager |
12
|
|
|
{ |
13
|
|
|
/** @var InternalEntityFactoryInterface Factory to create entities */ |
14
|
|
|
private $entityFactory; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @param InternalEntityFactoryInterface $entityFactory Factory to create entities |
18
|
|
|
*/ |
19
|
76 |
|
public function __construct(InternalEntityFactoryInterface $entityFactory) |
20
|
|
|
{ |
21
|
76 |
|
$this->entityFactory = $entityFactory; |
22
|
76 |
|
} |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* Detect whether a row is considered empty. |
26
|
|
|
* An empty row has all of its cells empty. |
27
|
|
|
* |
28
|
|
|
* @param Row $row |
29
|
|
|
* @return bool |
30
|
|
|
*/ |
31
|
66 |
|
public function isEmpty(Row $row) |
32
|
|
|
{ |
33
|
66 |
|
foreach ($row->getCells() as $cell) { |
34
|
59 |
|
if (!$cell->isEmpty()) { |
35
|
57 |
|
return false; |
36
|
|
|
} |
37
|
|
|
} |
38
|
|
|
|
39
|
17 |
|
return true; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Fills the missing indexes of a row with empty cells. |
44
|
|
|
* |
45
|
|
|
* @param Row $row |
46
|
|
|
* @return Row |
47
|
|
|
*/ |
48
|
25 |
|
public function fillMissingIndexesWithEmptyCells(Row $row) |
49
|
|
|
{ |
50
|
25 |
|
$numCells = $row->getNumCells(); |
51
|
|
|
|
52
|
25 |
|
if ($numCells === 0) { |
53
|
1 |
|
return $row; |
54
|
|
|
} |
55
|
|
|
|
56
|
24 |
|
$rowCells = $row->getCells(); |
57
|
24 |
|
$maxCellIndex = $numCells; |
58
|
|
|
|
59
|
|
|
// If the row has empty cells, calling "setCellAtIndex" will add the cell |
60
|
|
|
// but in the wrong place (the new cell is added at the end of the array). |
61
|
|
|
// Therefore, we need to sort the array using keys to have proper order. |
62
|
|
|
// @see https://github.com/box/spout/issues/740 |
63
|
24 |
|
$needsSorting = false; |
64
|
|
|
|
65
|
24 |
|
for ($cellIndex = 0; $cellIndex < $maxCellIndex; $cellIndex++) { |
66
|
24 |
|
if (!isset($rowCells[$cellIndex])) { |
67
|
3 |
|
$row->setCellAtIndex($this->entityFactory->createCell(''), $cellIndex); |
68
|
3 |
|
$needsSorting = true; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|
72
|
24 |
|
if ($needsSorting) { |
73
|
3 |
|
$rowCells = $row->getCells(); |
74
|
3 |
|
ksort($rowCells); |
75
|
3 |
|
$row->setCells($rowCells); |
76
|
|
|
} |
77
|
|
|
|
78
|
24 |
|
return $row; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|