Cells.php 13 KB

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