Cells.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. <?php
  2. namespace PhpOffice\PhpSpreadsheet\Collection;
  3. use PhpOffice\PhpSpreadsheet\Cell\Cell;
  4. use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
  5. use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
  6. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  7. use Psr\SimpleCache\CacheInterface;
  8. class Cells
  9. {
  10. /**
  11. * @var \Psr\SimpleCache\CacheInterface
  12. */
  13. private $cache;
  14. /**
  15. * Parent worksheet.
  16. *
  17. * @var Worksheet
  18. */
  19. private $parent;
  20. /**
  21. * The currently active Cell.
  22. *
  23. * @var Cell
  24. */
  25. private $currentCell;
  26. /**
  27. * Coordinate of the currently active Cell.
  28. *
  29. * @var string
  30. */
  31. private $currentCoordinate;
  32. /**
  33. * Flag indicating whether the currently active Cell requires saving.
  34. *
  35. * @var bool
  36. */
  37. private $currentCellIsDirty = false;
  38. /**
  39. * An index of existing cells. Booleans indexed by their coordinate.
  40. *
  41. * @var bool[]
  42. */
  43. private $index = [];
  44. /**
  45. * Prefix used to uniquely identify cache data for this worksheet.
  46. *
  47. * @var string
  48. */
  49. private $cachePrefix;
  50. /**
  51. * Initialise this new cell collection.
  52. *
  53. * @param Worksheet $parent The worksheet for this cell collection
  54. * @param CacheInterface $cache
  55. */
  56. public function __construct(Worksheet $parent, CacheInterface $cache)
  57. {
  58. // Set our parent worksheet.
  59. // This is maintained here to facilitate re-attaching it to Cell objects when
  60. // they are woken from a serialized state
  61. $this->parent = $parent;
  62. $this->cache = $cache;
  63. $this->cachePrefix = $this->getUniqueID();
  64. }
  65. /**
  66. * Return the parent worksheet for this cell collection.
  67. *
  68. * @return Worksheet
  69. */
  70. public function getParent()
  71. {
  72. return $this->parent;
  73. }
  74. /**
  75. * Whether the collection holds a cell for the given coordinate.
  76. *
  77. * @param string $pCoord Coordinate of the cell to check
  78. *
  79. * @return bool
  80. */
  81. public function has($pCoord)
  82. {
  83. if ($pCoord === $this->currentCoordinate) {
  84. return true;
  85. }
  86. // Check if the requested entry exists in the index
  87. return isset($this->index[$pCoord]);
  88. }
  89. /**
  90. * Add or update a cell in the collection.
  91. *
  92. * @param Cell $cell Cell to update
  93. *
  94. * @throws PhpSpreadsheetException
  95. *
  96. * @return Cell
  97. */
  98. public function update(Cell $cell)
  99. {
  100. return $this->add($cell->getCoordinate(), $cell);
  101. }
  102. /**
  103. * Delete a cell in cache identified by coordinate.
  104. *
  105. * @param string $pCoord Coordinate of the cell to delete
  106. */
  107. public function delete($pCoord)
  108. {
  109. if ($pCoord === $this->currentCoordinate && $this->currentCell !== null) {
  110. $this->currentCell->detach();
  111. $this->currentCoordinate = null;
  112. $this->currentCell = null;
  113. $this->currentCellIsDirty = false;
  114. }
  115. unset($this->index[$pCoord]);
  116. // Delete the entry from cache
  117. $this->cache->delete($this->cachePrefix . $pCoord);
  118. }
  119. /**
  120. * Get a list of all cell coordinates currently held in the collection.
  121. *
  122. * @return string[]
  123. */
  124. public function getCoordinates()
  125. {
  126. return array_keys($this->index);
  127. }
  128. /**
  129. * Get a sorted list of all cell coordinates currently held in the collection by row and column.
  130. *
  131. * @return string[]
  132. */
  133. public function getSortedCoordinates()
  134. {
  135. $sortKeys = [];
  136. foreach ($this->getCoordinates() as $coord) {
  137. sscanf($coord, '%[A-Z]%d', $column, $row);
  138. $sortKeys[sprintf('%09d%3s', $row, $column)] = $coord;
  139. }
  140. ksort($sortKeys);
  141. return array_values($sortKeys);
  142. }
  143. /**
  144. * Get highest worksheet column and highest row that have cell records.
  145. *
  146. * @return array Highest column name and highest row number
  147. */
  148. public function getHighestRowAndColumn()
  149. {
  150. // Lookup highest column and highest row
  151. $col = ['A' => '1A'];
  152. $row = [1];
  153. foreach ($this->getCoordinates() as $coord) {
  154. sscanf($coord, '%[A-Z]%d', $c, $r);
  155. $row[$r] = $r;
  156. $col[$c] = strlen($c) . $c;
  157. }
  158. if (!empty($row)) {
  159. // Determine highest column and row
  160. $highestRow = max($row);
  161. $highestColumn = substr(max($col), 1);
  162. }
  163. return [
  164. 'row' => $highestRow,
  165. 'column' => $highestColumn,
  166. ];
  167. }
  168. /**
  169. * Return the cell coordinate of the currently active cell object.
  170. *
  171. * @return string
  172. */
  173. public function getCurrentCoordinate()
  174. {
  175. return $this->currentCoordinate;
  176. }
  177. /**
  178. * Return the column coordinate of the currently active cell object.
  179. *
  180. * @return string
  181. */
  182. public function getCurrentColumn()
  183. {
  184. sscanf($this->currentCoordinate, '%[A-Z]%d', $column, $row);
  185. return $column;
  186. }
  187. /**
  188. * Return the row coordinate of the currently active cell object.
  189. *
  190. * @return int
  191. */
  192. public function getCurrentRow()
  193. {
  194. sscanf($this->currentCoordinate, '%[A-Z]%d', $column, $row);
  195. return (int) $row;
  196. }
  197. /**
  198. * Get highest worksheet column.
  199. *
  200. * @param string $row Return the highest column for the specified row,
  201. * or the highest column of any row if no row number is passed
  202. *
  203. * @return string Highest column name
  204. */
  205. public function getHighestColumn($row = null)
  206. {
  207. if ($row == null) {
  208. $colRow = $this->getHighestRowAndColumn();
  209. return $colRow['column'];
  210. }
  211. $columnList = [1];
  212. foreach ($this->getCoordinates() as $coord) {
  213. sscanf($coord, '%[A-Z]%d', $c, $r);
  214. if ($r != $row) {
  215. continue;
  216. }
  217. $columnList[] = Coordinate::columnIndexFromString($c);
  218. }
  219. return Coordinate::stringFromColumnIndex(max($columnList) + 1);
  220. }
  221. /**
  222. * Get highest worksheet row.
  223. *
  224. * @param string $column Return the highest row for the specified column,
  225. * or the highest row of any column if no column letter is passed
  226. *
  227. * @return int Highest row number
  228. */
  229. public function getHighestRow($column = null)
  230. {
  231. if ($column == null) {
  232. $colRow = $this->getHighestRowAndColumn();
  233. return $colRow['row'];
  234. }
  235. $rowList = [0];
  236. foreach ($this->getCoordinates() as $coord) {
  237. sscanf($coord, '%[A-Z]%d', $c, $r);
  238. if ($c != $column) {
  239. continue;
  240. }
  241. $rowList[] = $r;
  242. }
  243. return max($rowList);
  244. }
  245. /**
  246. * Generate a unique ID for cache referencing.
  247. *
  248. * @return string Unique Reference
  249. */
  250. private function getUniqueID()
  251. {
  252. return uniqid('phpspreadsheet-', true) . '-';
  253. }
  254. /**
  255. * Clone the cell collection.
  256. *
  257. * @param Worksheet $parent The new worksheet that we're copying to
  258. *
  259. * @return self
  260. */
  261. public function cloneCellCollection(Worksheet $parent)
  262. {
  263. $this->storeCurrentCell();
  264. $newCollection = clone $this;
  265. $newCollection->parent = $parent;
  266. if (($newCollection->currentCell !== null) && (is_object($newCollection->currentCell))) {
  267. $newCollection->currentCell->attach($this);
  268. }
  269. // Get old values
  270. $oldKeys = $newCollection->getAllCacheKeys();
  271. $oldValues = $newCollection->cache->getMultiple($oldKeys);
  272. $newValues = [];
  273. $oldCachePrefix = $newCollection->cachePrefix;
  274. // Change prefix
  275. $newCollection->cachePrefix = $newCollection->getUniqueID();
  276. foreach ($oldValues as $oldKey => $value) {
  277. $newValues[str_replace($oldCachePrefix, $newCollection->cachePrefix, $oldKey)] = clone $value;
  278. }
  279. // Store new values
  280. $stored = $newCollection->cache->setMultiple($newValues);
  281. if (!$stored) {
  282. $newCollection->__destruct();
  283. throw new PhpSpreadsheetException('Failed to copy cells in cache');
  284. }
  285. return $newCollection;
  286. }
  287. /**
  288. * Remove a row, deleting all cells in that row.
  289. *
  290. * @param string $row Row number to remove
  291. */
  292. public function removeRow($row)
  293. {
  294. foreach ($this->getCoordinates() as $coord) {
  295. sscanf($coord, '%[A-Z]%d', $c, $r);
  296. if ($r == $row) {
  297. $this->delete($coord);
  298. }
  299. }
  300. }
  301. /**
  302. * Remove a column, deleting all cells in that column.
  303. *
  304. * @param string $column Column ID to remove
  305. */
  306. public function removeColumn($column)
  307. {
  308. foreach ($this->getCoordinates() as $coord) {
  309. sscanf($coord, '%[A-Z]%d', $c, $r);
  310. if ($c == $column) {
  311. $this->delete($coord);
  312. }
  313. }
  314. }
  315. /**
  316. * Store cell data in cache for the current cell object if it's "dirty",
  317. * and the 'nullify' the current cell object.
  318. *
  319. * @throws PhpSpreadsheetException
  320. */
  321. private function storeCurrentCell()
  322. {
  323. if ($this->currentCellIsDirty && !empty($this->currentCoordinate)) {
  324. $this->currentCell->detach();
  325. $stored = $this->cache->set($this->cachePrefix . $this->currentCoordinate, $this->currentCell);
  326. if (!$stored) {
  327. $this->__destruct();
  328. throw new PhpSpreadsheetException("Failed to store cell {$this->currentCoordinate} in cache");
  329. }
  330. $this->currentCellIsDirty = false;
  331. }
  332. $this->currentCoordinate = null;
  333. $this->currentCell = null;
  334. }
  335. /**
  336. * Add or update a cell identified by its coordinate into the collection.
  337. *
  338. * @param string $pCoord Coordinate of the cell to update
  339. * @param Cell $cell Cell to update
  340. *
  341. * @throws PhpSpreadsheetException
  342. *
  343. * @return \PhpOffice\PhpSpreadsheet\Cell\Cell
  344. */
  345. public function add($pCoord, Cell $cell)
  346. {
  347. if ($pCoord !== $this->currentCoordinate) {
  348. $this->storeCurrentCell();
  349. }
  350. $this->index[$pCoord] = true;
  351. $this->currentCoordinate = $pCoord;
  352. $this->currentCell = $cell;
  353. $this->currentCellIsDirty = true;
  354. return $cell;
  355. }
  356. /**
  357. * Get cell at a specific coordinate.
  358. *
  359. * @param string $pCoord Coordinate of the cell
  360. *
  361. * @throws PhpSpreadsheetException
  362. *
  363. * @return \PhpOffice\PhpSpreadsheet\Cell\Cell Cell that was found, or null if not found
  364. */
  365. public function get($pCoord)
  366. {
  367. if ($pCoord === $this->currentCoordinate) {
  368. return $this->currentCell;
  369. }
  370. $this->storeCurrentCell();
  371. // Return null if requested entry doesn't exist in collection
  372. if (!$this->has($pCoord)) {
  373. return null;
  374. }
  375. // Check if the entry that has been requested actually exists
  376. $cell = $this->cache->get($this->cachePrefix . $pCoord);
  377. if ($cell === null) {
  378. throw new PhpSpreadsheetException("Cell entry {$pCoord} no longer exists in cache. This probably means that the cache was cleared by someone else.");
  379. }
  380. // Set current entry to the requested entry
  381. $this->currentCoordinate = $pCoord;
  382. $this->currentCell = $cell;
  383. // Re-attach this as the cell's parent
  384. $this->currentCell->attach($this);
  385. // Return requested entry
  386. return $this->currentCell;
  387. }
  388. /**
  389. * Clear the cell collection and disconnect from our parent.
  390. */
  391. public function unsetWorksheetCells()
  392. {
  393. if ($this->currentCell !== null) {
  394. $this->currentCell->detach();
  395. $this->currentCell = null;
  396. $this->currentCoordinate = null;
  397. }
  398. // Flush the cache
  399. $this->__destruct();
  400. $this->index = [];
  401. // detach ourself from the worksheet, so that it can then delete this object successfully
  402. $this->parent = null;
  403. }
  404. /**
  405. * Destroy this cell collection.
  406. */
  407. public function __destruct()
  408. {
  409. $this->cache->deleteMultiple($this->getAllCacheKeys());
  410. }
  411. /**
  412. * Returns all known cache keys.
  413. *
  414. * @return string[]
  415. */
  416. private function getAllCacheKeys()
  417. {
  418. $keys = [];
  419. foreach ($this->getCoordinates() as $coordinate) {
  420. $keys[] = $this->cachePrefix . $coordinate;
  421. }
  422. return $keys;
  423. }
  424. }