Move entities and managers back to Common (#431)

This commit is contained in:
Adrien Loison authored and GitHub committed 2017-05-29 23:28:10 +02:00
1 parent 878c4a9c8b
commit c4e25a168e
32 files changed
+79 -80

No files matched your search

@@ -0,0 +1,34 @@
<?php
namespace Box\Spout\Writer\Common\Creator;
use Box\Spout\Writer\Common\Sheet;
use Box\Spout\Writer\Common\Entity\Workbook;
use Box\Spout\Writer\Common\Entity\Worksheet;
/**
* Class EntityFactory
* Factory to create entities
*
* @package Box\Spout\Writer\Common\Creator
*/
class EntityFactory
{
/**
* @return Workbook
*/
public function createWorkbook()
{
return new Workbook();
}
/**
* @param string $worksheetFilePath
* @param Sheet $externalSheet
* @return Worksheet
*/
public function createWorksheet($worksheetFilePath, Sheet $externalSheet)
{
return new Worksheet($worksheetFilePath, $externalSheet);
}
}
@@ -0,0 +1,20 @@
<?php
namespace Box\Spout\Writer\Common\Creator;
use Box\Spout\Writer\Common\Manager\OptionsManagerInterface;
use Box\Spout\Writer\Common\Manager\WorkbookManagerInterface;
/**
* Interface GeneralFactoryInterface
*
* @package Box\Spout\Writer\Common\Creator
*/
interface InternalFactoryInterface
{
/**
* @param OptionsManagerInterface $optionsManager
* @return WorkbookManagerInterface
*/
public function createWorkbookManager(OptionsManagerInterface $optionsManager);
}
+167
View File
@@ -0,0 +1,167 @@
<?php
namespace Box\Spout\Writer\Common\Entity;
use Box\Spout\Writer\Common\Helper\CellHelper;
/**
* Class Cell
*
* @package Box\Spout\Writer\Common\Entity
*/
class Cell
{
/**
* Numeric cell type (whole numbers, fractional numbers, dates)
*/
const TYPE_NUMERIC = 0;
/**
* String (text) cell type
*/
const TYPE_STRING = 1;
/**
* Formula cell type
* Not used at the moment
*/
const TYPE_FORMULA = 2;
/**
* Empty cell type
*/
const TYPE_EMPTY = 3;
/**
* Boolean cell type
*/
const TYPE_BOOLEAN = 4;
/**
* Error cell type
*/
const TYPE_ERROR = 5;
/**
* The value of this cell
* @var mixed|null
*/
protected $value = null;
/**
* The cell type
* @var int|null
*/
protected $type = null;
/**
* Cell constructor.
* @param $value mixed
*/
public function __construct($value)
{
$this->setValue($value);
}
/**
* @param $value mixed|null
*/
public function setValue($value)
{
$this->value = $value;
$this->type = $this->detectType($value);
}
/**
* @return mixed|null
*/
public function getValue()
{
return $this->value;
}
/**
* @return int|null
*/
public function getType()
{
return $this->type;
}
/**
* Get the current value type
* @param mixed|null $value
* @return int
*/
protected function detectType($value)
{
if (CellHelper::isBoolean($value)) {
return self::TYPE_BOOLEAN;
} elseif (CellHelper::isEmpty($value)) {
return self::TYPE_EMPTY;
} elseif (CellHelper::isNumeric($this->getValue())) {
return self::TYPE_NUMERIC;
} elseif (CellHelper::isNonEmptyString($value)) {
return self::TYPE_STRING;
} else {
return self::TYPE_ERROR;
}
}
/**
* @return bool
*/
public function isBoolean()
{
return $this->type === self::TYPE_BOOLEAN;
}
/**
* @return bool
*/
public function isEmpty()
{
return $this->type === self::TYPE_EMPTY;
}
/**
* Not used at the moment
* @return bool
*/
public function isFormula()
{
return $this->type === self::TYPE_FORMULA;
}
/**
* @return bool
*/
public function isNumeric()
{
return $this->type === self::TYPE_NUMERIC;
}
/**
* @return bool
*/
public function isString()
{
return $this->type === self::TYPE_STRING;
}
/**
* @return bool
*/
public function isError()
{
return $this->type === self::TYPE_ERROR;
}
/**
* @return string
*/
public function __toString()
{
return (string)$this->value;
}
}
@@ -0,0 +1,25 @@
<?php
namespace Box\Spout\Writer\Common\Entity;
/**
* Class Options
* Writer' options holder
*
* @package Box\Spout\Writer\Common\Entity
*/
abstract class Options
{
// CSV specific options
const FIELD_DELIMITER = 'fieldDelimiter';
const FIELD_ENCLOSURE = 'fieldEnclosure';
const SHOULD_ADD_BOM = 'shouldAddBOM';
// Multisheets options
const TEMP_FOLDER = 'tempFolder';
const DEFAULT_ROW_STYLE = 'defaultRowStyle';
const SHOULD_CREATE_NEW_SHEETS_AUTOMATICALLY = 'shouldCreateNewSheetsAutomatically';
// XLSX specific options
const SHOULD_USE_INLINE_STRINGS = 'shouldUseInlineStrings';
}
@@ -0,0 +1,50 @@
<?php
namespace Box\Spout\Writer\Common\Entity;
/**
* Class Workbook
* Entity describing a workbook
*
* @package Box\Spout\Writer\Common\Entity
*/
class Workbook
{
/** @var Worksheet[] List of the workbook's sheets */
private $worksheets = [];
/** @var string Timestamp based unique ID identifying the workbook */
private $internalId;
/**
* Workbook constructor.
*/
public function __construct()
{
$this->internalId = uniqid();
}
/**
* @return Worksheet[]
*/
public function getWorksheets()
{
return $this->worksheets;
}
/**
* @param Worksheet[] $worksheets
*/
public function setWorksheets($worksheets)
{
$this->worksheets = $worksheets;
}
/**
* @return string
*/
public function getInternalId()
{
return $this->internalId;
}
}
@@ -0,0 +1,117 @@
<?php
namespace Box\Spout\Writer\Common\Entity;
use Box\Spout\Writer\Common\Sheet;
/**
* Class Worksheet
* Entity describing a Worksheet
*
* @package Box\Spout\Writer\Common\Entity
*/
class Worksheet
{
/** @var string Path to the XML file that will contain the sheet data */
private $filePath;
/** @var Resource Pointer to the sheet data file (e.g. xl/worksheets/sheet1.xml) */
private $filePointer;
/** @var Sheet The "external" sheet */
private $externalSheet;
/** @var int Maximum number of columns among all the written rows */
private $maxNumColumns;
/** @var int Index of the last written row */
private $lastWrittenRowIndex;
/**
* Worksheet constructor.
*
* @param string $worksheetFilePath
* @param Sheet $externalSheet
*/
public function __construct($worksheetFilePath, Sheet $externalSheet)
{
$this->filePath = $worksheetFilePath;
$this->filePointer = null;
$this->externalSheet = $externalSheet;
$this->maxNumColumns = 0;
$this->lastWrittenRowIndex = 0;
}
/**
* @return string
*/
public function getFilePath()
{
return $this->filePath;
}
/**
* @return Resource
*/
public function getFilePointer()
{
return $this->filePointer;
}
/**
* @param Resource $filePointer
*/
public function setFilePointer($filePointer)
{
$this->filePointer = $filePointer;
}
/**
* @return Sheet
*/
public function getExternalSheet()
{
return $this->externalSheet;
}
/**
* @return int
*/
public function getMaxNumColumns()
{
return $this->maxNumColumns;
}
/**
* @param int $maxNumColumns
*/
public function setMaxNumColumns($maxNumColumns)
{
$this->maxNumColumns = $maxNumColumns;
}
/**
* @return int
*/
public function getLastWrittenRowIndex()
{
return $this->lastWrittenRowIndex;
}
/**
* @param int $lastWrittenRowIndex
*/
public function setLastWrittenRowIndex($lastWrittenRowIndex)
{
$this->lastWrittenRowIndex = $lastWrittenRowIndex;
}
/**
* @return int The ID of the worksheet
*/
public function getId()
{
// sheet index is zero-based, while ID is 1-based
return $this->externalSheet->getIndex() + 1;
}
}
@@ -0,0 +1,71 @@
<?php
namespace Box\Spout\Writer\Common\Manager;
/**
* Class OptionsManager
* Writer' options manager
*
* @package Box\Spout\Writer\Common\Manager
*/
abstract class OptionsManagerAbstract implements OptionsManagerInterface
{
const PREFIX_OPTION = 'OPTION_';
/** @var string[] List of all supported option names */
private $supportedOptions = [];
/** @var array Associative array [OPTION_NAME => OPTION_VALUE] */
private $options = [];
/**
* WriterOptions constructor.
*/
public function __construct()
{
$this->supportedOptions = $this->getSupportedOptions();
$this->setDefaultOptions();
}
/**
* @return array List of supported options
*/
abstract protected function getSupportedOptions();
/**
* Sets the default options.
* To be overriden by child classes
*
* @return void
*/
abstract protected function setDefaultOptions();
/**
* Sets the given option, if this option is supported.
*
* @param string $optionName
* @param mixed $optionValue
* @return void
*/
public function setOption($optionName, $optionValue)
{
if (in_array($optionName, $this->supportedOptions)) {
$this->options[$optionName] = $optionValue;
}
}
/**
* @param string $optionName
* @return mixed|null The set option or NULL if no option with given name found
*/
public function getOption($optionName)
{
$optionValue = null;
if (isset($this->options[$optionName])) {
$optionValue = $this->options[$optionName];
}
return $optionValue;
}
}
@@ -0,0 +1,25 @@
<?php
namespace Box\Spout\Writer\Common\Manager;
/**
* Interface OptionsManagerInterface
* Writer' options interface
*
* @package Box\Spout\Writer\Common\Manager
*/
interface OptionsManagerInterface
{
/**
* @param string $optionName
* @param mixed $optionValue
* @return void
*/
public function setOption($optionName, $optionValue);
/**
* @param string $optionName
* @return mixed|null The set option or NULL if no option with given name found
*/
public function getOption($optionName);
}
@@ -0,0 +1,315 @@
<?php
namespace Box\Spout\Writer\Common\Manager;
use Box\Spout\Common\Exception\IOException;
use Box\Spout\Writer\Common\Helper\FileSystemWithRootFolderHelperInterface;
use Box\Spout\Writer\Common\Helper\StyleHelperInterface;
use Box\Spout\Writer\Common\Entity\Options;
use Box\Spout\Writer\Common\Sheet;
use Box\Spout\Writer\Common\Entity\Workbook;
use Box\Spout\Writer\Common\Entity\Worksheet;
use Box\Spout\Writer\Exception\SheetNotFoundException;
use Box\Spout\Writer\Exception\WriterException;
use Box\Spout\Writer\Common\Creator\EntityFactory;
use Box\Spout\Writer\Style\Style;
/**
* Class WorkbookManagerAbstract
* Abstract workbook manager, providing the generic interfaces to work with workbook.
*
* @package Box\Spout\Writer\Common\Manager
*/
abstract class WorkbookManagerAbstract implements WorkbookManagerInterface
{
/** @var Workbook The workbook to manage */
protected $workbook;
/** @var OptionsManagerInterface */
protected $optionManager;
/** @var WorksheetManagerInterface */
protected $worksheetManager;
/** @var StyleHelperInterface */
protected $styleHelper;
/** @var FileSystemWithRootFolderHelperInterface Helper to perform file system operations */
protected $fileSystemHelper;
/** @var EntityFactory Factory to create entities */
private $entityFactory;
/** @var Worksheet The worksheet where data will be written to */
protected $currentWorksheet;
/**
* @param Workbook $workbook
* @param OptionsManagerInterface $optionsManager
* @param WorksheetManagerInterface $worksheetManager
* @param StyleHelperInterface $styleHelper
* @param FileSystemWithRootFolderHelperInterface $fileSystemHelper
* @param EntityFactory $entityFactory
*/
public function __construct(
Workbook $workbook,
OptionsManagerInterface $optionsManager,
WorksheetManagerInterface $worksheetManager,
StyleHelperInterface $styleHelper,
FileSystemWithRootFolderHelperInterface $fileSystemHelper,
EntityFactory $entityFactory)
{
$this->workbook = $workbook;
$this->optionManager = $optionsManager;
$this->worksheetManager = $worksheetManager;
$this->styleHelper = $styleHelper;
$this->fileSystemHelper = $fileSystemHelper;
$this->entityFactory = $entityFactory;
}
/**
* @return int Maximum number of rows/columns a sheet can contain
*/
abstract protected function getMaxRowsPerWorksheet();
/**
* @param Sheet $sheet
* @return string The file path where the data for the given sheet will be stored
*/
abstract protected function getWorksheetFilePath(Sheet $sheet);
/**
* @return Workbook
*/
public function getWorkbook()
{
return $this->workbook;
}
/**
* Creates a new sheet in the workbook and make it the current sheet.
* The writing will resume where it stopped (i.e. data won't be truncated).
*
* @return Worksheet The created sheet
* @throws IOException If unable to open the sheet for writing
*/
public function addNewSheetAndMakeItCurrent()
{
$worksheet = $this->addNewSheet();
$this->setCurrentWorksheet($worksheet);
return $worksheet;
}
/**
* Creates a new sheet in the workbook. The current sheet remains unchanged.
*
* @return Worksheet The created sheet
* @throws \Box\Spout\Common\Exception\IOException If unable to open the sheet for writing
*/
private function addNewSheet()
{
$worksheets = $this->getWorksheets();
$newSheetIndex = count($worksheets);
$sheet = new Sheet($newSheetIndex, $this->workbook->getInternalId());
$worksheetFilePath = $this->getWorksheetFilePath($sheet);
$worksheet = $this->entityFactory->createWorksheet($worksheetFilePath, $sheet);
$this->worksheetManager->startSheet($worksheet);
$worksheets[] = $worksheet;
$this->workbook->setWorksheets($worksheets);
return $worksheet;
}
/**
* @return Worksheet[] All the workbook's sheets
*/
public function getWorksheets()
{
return $this->workbook->getWorksheets();
}
/**
* Returns the current sheet
*
* @return Worksheet The current sheet
*/
public function getCurrentWorksheet()
{
return $this->currentWorksheet;
}
/**
* Sets the given sheet as the current one. New data will be written to this sheet.
* The writing will resume where it stopped (i.e. data won't be truncated).
*
* @param Sheet $sheet The "external" sheet to set as current
* @return void
* @throws SheetNotFoundException If the given sheet does not exist in the workbook
*/
public function setCurrentSheet(Sheet $sheet)
{
$worksheet = $this->getWorksheetFromExternalSheet($sheet);
if ($worksheet !== null) {
$this->currentWorksheet = $worksheet;
} else {
throw new SheetNotFoundException('The given sheet does not exist in the workbook.');
}
}
/**
* @param Worksheet $worksheet
* @return void
*/
private function setCurrentWorksheet($worksheet)
{
$this->currentWorksheet = $worksheet;
}
/**
* Returns the worksheet associated to the given external sheet.
*
* @param Sheet $sheet
* @return Worksheet|null The worksheet associated to the given external sheet or null if not found.
*/
private function getWorksheetFromExternalSheet($sheet)
{
$worksheetFound = null;
foreach ($this->getWorksheets() as $worksheet) {
if ($worksheet->getExternalSheet() === $sheet) {
$worksheetFound = $worksheet;
break;
}
}
return $worksheetFound;
}
/**
* Adds data to the current sheet.
* If shouldCreateNewSheetsAutomatically option is set to true, it will handle pagination
* with the creation of new worksheets if one worksheet has reached its maximum capicity.
*
* @param array $dataRow Array containing data to be written. Cannot be empty.
* Example $dataRow = ['data1', 1234, null, '', 'data5'];
* @param Style $style Style to be applied to the row.
* @return void
* @throws IOException If trying to create a new sheet and unable to open the sheet for writing
* @throws WriterException If unable to write data
*/
public function addRowToCurrentWorksheet($dataRow, Style $style)
{
$currentWorksheet = $this->getCurrentWorksheet();
$hasReachedMaxRows = $this->hasCurrentWorkseetReachedMaxRows();
// if we reached the maximum number of rows for the current sheet...
if ($hasReachedMaxRows) {
// ... continue writing in a new sheet if option set
if ($this->optionManager->getOption(Options::SHOULD_CREATE_NEW_SHEETS_AUTOMATICALLY)) {
$currentWorksheet = $this->addNewSheetAndMakeItCurrent();
$this->addRowWithStyleToWorksheet($currentWorksheet, $dataRow, $style);
} else {
// otherwise, do nothing as the data won't be written anyways
}
} else {
$this->addRowWithStyleToWorksheet($currentWorksheet, $dataRow, $style);
}
}
/**
* @return bool Whether the current worksheet has reached the maximum number of rows per sheet.
*/
private function hasCurrentWorkseetReachedMaxRows()
{
$currentWorksheet = $this->getCurrentWorksheet();
return ($currentWorksheet->getLastWrittenRowIndex() >= $this->getMaxRowsPerWorksheet());
}
/**
* Adds data with the given style to the given sheet.
*
* @param Worksheet $worksheet Worksheet to write the row to
* @param array $dataRow Array containing data to be written. Cannot be empty.
* Example $dataRow = ['data1', 1234, null, '', 'data5'];
* @param Style $style Style to be applied to the row.
* @return void
* @throws WriterException If unable to write data
*/
private function addRowWithStyleToWorksheet(Worksheet $worksheet, $dataRow, Style $style)
{
$updatedStyle = $this->styleHelper->applyExtraStylesIfNeeded($style, $dataRow);
$registeredStyle = $this->styleHelper->registerStyle($updatedStyle);
$this->worksheetManager->addRow($worksheet, $dataRow, $registeredStyle);
// update max num columns for the worksheet
$currentMaxNumColumns = $worksheet->getMaxNumColumns();
$cellsCount = count($dataRow);
$worksheet->setMaxNumColumns(max($currentMaxNumColumns, $cellsCount));
}
/**
* Closes the workbook and all its associated sheets.
* All the necessary files are written to disk and zipped together to create the final file.
* All the temporary files are then deleted.
*
* @param resource $finalFilePointer Pointer to the spreadsheet that will be created
* @return void
*/
public function close($finalFilePointer)
{
$this->closeAllWorksheets();
$this->closeRemainingObjects();
$this->writeAllFilesToDiskAndZipThem($finalFilePointer);
$this->cleanupTempFolder();
}
/**
* Closes custom objects that are still opened
*
* @return void
*/
protected function closeRemainingObjects()
{
// do nothing by default
}
/**
* Writes all the necessary files to disk and zip them together to create the final file.
*
* @param resource $finalFilePointer Pointer to the spreadsheet that will be created
* @return void
*/
abstract protected function writeAllFilesToDiskAndZipThem($finalFilePointer);
/**
* Closes all workbook's associated sheets.
*
* @return void
*/
private function closeAllWorksheets()
{
$worksheets = $this->getWorksheets();
foreach ($worksheets as $worksheet) {
$this->worksheetManager->close($worksheet);
}
}
/**
* Deletes the root folder created in the temp folder and all its contents.
*
* @return void
*/
protected function cleanupTempFolder()
{
$rootFolder = $this->fileSystemHelper->getRootFolder();
$this->fileSystemHelper->deleteFolderRecursively($rootFolder);
}
}
@@ -0,0 +1,80 @@
<?php
namespace Box\Spout\Writer\Common\Manager;
use Box\Spout\Common\Exception\IOException;
use Box\Spout\Writer\Common\Sheet;
use Box\Spout\Writer\Common\Entity\Workbook;
use Box\Spout\Writer\Common\Entity\Worksheet;
use Box\Spout\Writer\Exception\SheetNotFoundException;
use Box\Spout\Writer\Exception\WriterException;
use Box\Spout\Writer\Style\Style;
/**
* Interface WorkbookManagerInterface
* workbook manager interface, providing the generic interfaces to work with workbook.
*
* @package Box\Spout\Writer\Common\Manager
*/
interface WorkbookManagerInterface
{
/**
* @return Workbook
*/
public function getWorkbook();
/**
* Creates a new sheet in the workbook and make it the current sheet.
* The writing will resume where it stopped (i.e. data won't be truncated).
*
* @return Worksheet The created sheet
* @throws IOException If unable to open the sheet for writing
*/
public function addNewSheetAndMakeItCurrent();
/**
* @return Worksheet[] All the workbook's sheets
*/
public function getWorksheets();
/**
* Returns the current sheet
*
* @return Worksheet The current sheet
*/
public function getCurrentWorksheet();
/**
* Sets the given sheet as the current one. New data will be written to this sheet.
* The writing will resume where it stopped (i.e. data won't be truncated).
*
* @param Sheet $sheet The "external" sheet to set as current
* @return void
* @throws SheetNotFoundException If the given sheet does not exist in the workbook
*/
public function setCurrentSheet(Sheet $sheet);
/**
* Adds data to the current sheet.
* If shouldCreateNewSheetsAutomatically option is set to true, it will handle pagination
* with the creation of new worksheets if one worksheet has reached its maximum capicity.
*
* @param array $dataRow Array containing data to be written. Cannot be empty.
* Example $dataRow = ['data1', 1234, null, '', 'data5'];
* @param Style $style Style to be applied to the row.
* @return void
* @throws IOException If trying to create a new sheet and unable to open the sheet for writing
* @throws WriterException If unable to write data
*/
public function addRowToCurrentWorksheet($dataRow, Style $style);
/**
* Closes the workbook and all its associated sheets.
* All the necessary files are written to disk and zipped together to create the final file.
* All the temporary files are then deleted.
*
* @param resource $finalFilePointer Pointer to the spreadsheet that will be created
* @return void
*/
public function close($finalFilePointer);
}
@@ -0,0 +1,45 @@
<?php
namespace Box\Spout\Writer\Common\Manager;
use Box\Spout\Writer\Common\Entity\Worksheet;
use Box\Spout\Writer\Style\Style;
/**
* Interface WorksheetManagerInterface
* Inteface for worksheet managers, providing the generic interfaces to work with worksheets.
*
* @package Box\Spout\Writer\Common\Manager
*/
interface WorksheetManagerInterface
{
/**
* Adds data to the worksheet.
*
* @param Worksheet $worksheet The worksheet to add the row to
* @param array $dataRow Array containing data to be written. Cannot be empty.
* Example $dataRow = ['data1', 1234, null, '', 'data5'];
* @param Style $rowStyle Style to be applied to the row. NULL means use default style.
* @return void
* @throws \Box\Spout\Common\Exception\IOException If the data cannot be written
* @throws \Box\Spout\Common\Exception\InvalidArgumentException If a cell value's type is not supported
*/
public function addRow(Worksheet $worksheet, $dataRow, $rowStyle);
/**
* Prepares the worksheet to accept data
*
* @param Worksheet $worksheet The worksheet to start
* @return void
* @throws \Box\Spout\Common\Exception\IOException If the sheet data file cannot be opened for writing
*/
public function startSheet(Worksheet $worksheet);
/**
* Closes the worksheet
*
* @param Worksheet $worksheet
* @return void
*/
public function close(Worksheet $worksheet);
}