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