Cells.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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. $column = '';
  138. $row = 0;
  139. sscanf($coord, '%[A-Z]%d', $column, $row);
  140. $sortKeys[sprintf('%09d%3s', $row, $column)] = $coord;
  141. }
  142. ksort($sortKeys);
  143. return array_values($sortKeys);
  144. }
  145. /**
  146. * Get highest worksheet column and highest row that have cell records.
  147. *
  148. * @return array Highest column name and highest row number
  149. */
  150. public function getHighestRowAndColumn()
  151. {
  152. // Lookup highest column and highest row
  153. $col = ['A' => '1A'];
  154. $row = [1];
  155. foreach ($this->getCoordinates() as $coord) {
  156. $c = '';
  157. $r = 0;
  158. sscanf($coord, '%[A-Z]%d', $c, $r);
  159. $row[$r] = $r;
  160. $col[$c] = strlen($c) . $c;
  161. }
  162. // Determine highest column and row
  163. $highestRow = max($row);
  164. $highestColumn = substr(max($col), 1);
  165. return [
  166. 'row' => $highestRow,
  167. 'column' => $highestColumn,
  168. ];
  169. }
  170. /**
  171. * Return the cell coordinate of the currently active cell object.
  172. *
  173. * @return string
  174. */
  175. public function getCurrentCoordinate()
  176. {
  177. return $this->currentCoordinate;
  178. }
  179. /**
  180. * Return the column coordinate of the currently active cell object.
  181. *
  182. * @return string
  183. */
  184. public function getCurrentColumn()
  185. {
  186. $column = '';
  187. $row = 0;
  188. sscanf($this->currentCoordinate, '%[A-Z]%d', $column, $row);
  189. return $column;
  190. }
  191. /**
  192. * Return the row coordinate of the currently active cell object.
  193. *
  194. * @return int
  195. */
  196. public function getCurrentRow()
  197. {
  198. $column = '';
  199. $row = 0;
  200. sscanf($this->currentCoordinate, '%[A-Z]%d', $column, $row);
  201. return (int) $row;
  202. }
  203. /**
  204. * Get highest worksheet column.
  205. *
  206. * @param string $row Return the highest column for the specified row,
  207. * or the highest column of any row if no row number is passed
  208. *
  209. * @return string Highest column name
  210. */
  211. public function getHighestColumn($row = null)
  212. {
  213. if ($row == null) {
  214. $colRow = $this->getHighestRowAndColumn();
  215. return $colRow['column'];
  216. }
  217. $columnList = [1];
  218. foreach ($this->getCoordinates() as $coord) {
  219. $c = '';
  220. $r = 0;
  221. sscanf($coord, '%[A-Z]%d', $c, $r);
  222. if ($r != $row) {
  223. continue;
  224. }
  225. $columnList[] = Coordinate::columnIndexFromString($c);
  226. }
  227. return Coordinate::stringFromColumnIndex(max($columnList));
  228. }
  229. /**
  230. * Get highest worksheet row.
  231. *
  232. * @param string $column Return the highest row for the specified column,
  233. * or the highest row of any column if no column letter is passed
  234. *
  235. * @return int Highest row number
  236. */
  237. public function getHighestRow($column = null)
  238. {
  239. if ($column == null) {
  240. $colRow = $this->getHighestRowAndColumn();
  241. return $colRow['row'];
  242. }
  243. $rowList = [0];
  244. foreach ($this->getCoordinates() as $coord) {
  245. $c = '';
  246. $r = 0;
  247. sscanf($coord, '%[A-Z]%d', $c, $r);
  248. if ($c != $column) {
  249. continue;
  250. }
  251. $rowList[] = $r;
  252. }
  253. return max($rowList);
  254. }
  255. /**
  256. * Generate a unique ID for cache referencing.
  257. *
  258. * @return string Unique Reference
  259. */
  260. private function getUniqueID()
  261. {
  262. return uniqid('phpspreadsheet.', true) . '.';
  263. }
  264. /**
  265. * Clone the cell collection.
  266. *
  267. * @param Worksheet $parent The new worksheet that we're copying to
  268. *
  269. * @return self
  270. */
  271. public function cloneCellCollection(Worksheet $parent)
  272. {
  273. $this->storeCurrentCell();
  274. $newCollection = clone $this;
  275. $newCollection->parent = $parent;
  276. if (($newCollection->currentCell !== null) && (is_object($newCollection->currentCell))) {
  277. $newCollection->currentCell->attach($this);
  278. }
  279. // Get old values
  280. $oldKeys = $newCollection->getAllCacheKeys();
  281. $oldValues = $newCollection->cache->getMultiple($oldKeys);
  282. $newValues = [];
  283. $oldCachePrefix = $newCollection->cachePrefix;
  284. // Change prefix
  285. $newCollection->cachePrefix = $newCollection->getUniqueID();
  286. foreach ($oldValues as $oldKey => $value) {
  287. $newValues[str_replace($oldCachePrefix, $newCollection->cachePrefix, $oldKey)] = clone $value;
  288. }
  289. // Store new values
  290. $stored = $newCollection->cache->setMultiple($newValues);
  291. if (!$stored) {
  292. $newCollection->__destruct();
  293. throw new PhpSpreadsheetException('Failed to copy cells in cache');
  294. }
  295. return $newCollection;
  296. }
  297. /**
  298. * Remove a row, deleting all cells in that row.
  299. *
  300. * @param string $row Row number to remove
  301. */
  302. public function removeRow($row)
  303. {
  304. foreach ($this->getCoordinates() as $coord) {
  305. $c = '';
  306. $r = 0;
  307. sscanf($coord, '%[A-Z]%d', $c, $r);
  308. if ($r == $row) {
  309. $this->delete($coord);
  310. }
  311. }
  312. }
  313. /**
  314. * Remove a column, deleting all cells in that column.
  315. *
  316. * @param string $column Column ID to remove
  317. */
  318. public function removeColumn($column)
  319. {
  320. foreach ($this->getCoordinates() as $coord) {
  321. $c = '';
  322. $r = 0;
  323. sscanf($coord, '%[A-Z]%d', $c, $r);
  324. if ($c == $column) {
  325. $this->delete($coord);
  326. }
  327. }
  328. }
  329. /**
  330. * Store cell data in cache for the current cell object if it's "dirty",
  331. * and the 'nullify' the current cell object.
  332. *
  333. * @throws PhpSpreadsheetException
  334. */
  335. private function storeCurrentCell()
  336. {
  337. if ($this->currentCellIsDirty && !empty($this->currentCoordinate)) {
  338. $this->currentCell->detach();
  339. $stored = $this->cache->set($this->cachePrefix . $this->currentCoordinate, $this->currentCell);
  340. if (!$stored) {
  341. $this->__destruct();
  342. throw new PhpSpreadsheetException("Failed to store cell {$this->currentCoordinate} in cache");
  343. }
  344. $this->currentCellIsDirty = false;
  345. }
  346. $this->currentCoordinate = null;
  347. $this->currentCell = null;
  348. }
  349. /**
  350. * Add or update a cell identified by its coordinate into the collection.
  351. *
  352. * @param string $pCoord Coordinate of the cell to update
  353. * @param Cell $cell Cell to update
  354. *
  355. * @throws PhpSpreadsheetException
  356. *
  357. * @return \PhpOffice\PhpSpreadsheet\Cell\Cell
  358. */
  359. public function add($pCoord, Cell $cell)
  360. {
  361. if ($pCoord !== $this->currentCoordinate) {
  362. $this->storeCurrentCell();
  363. }
  364. $this->index[$pCoord] = true;
  365. $this->currentCoordinate = $pCoord;
  366. $this->currentCell = $cell;
  367. $this->currentCellIsDirty = true;
  368. return $cell;
  369. }
  370. /**
  371. * Get cell at a specific coordinate.
  372. *
  373. * @param string $pCoord Coordinate of the cell
  374. *
  375. * @throws PhpSpreadsheetException
  376. *
  377. * @return \PhpOffice\PhpSpreadsheet\Cell\Cell Cell that was found, or null if not found
  378. */
  379. public function get($pCoord)
  380. {
  381. if ($pCoord === $this->currentCoordinate) {
  382. return $this->currentCell;
  383. }
  384. $this->storeCurrentCell();
  385. // Return null if requested entry doesn't exist in collection
  386. if (!$this->has($pCoord)) {
  387. return null;
  388. }
  389. // Check if the entry that has been requested actually exists
  390. $cell = $this->cache->get($this->cachePrefix . $pCoord);
  391. if ($cell === null) {
  392. throw new PhpSpreadsheetException("Cell entry {$pCoord} no longer exists in cache. This probably means that the cache was cleared by someone else.");
  393. }
  394. // Set current entry to the requested entry
  395. $this->currentCoordinate = $pCoord;
  396. $this->currentCell = $cell;
  397. // Re-attach this as the cell's parent
  398. $this->currentCell->attach($this);
  399. // Return requested entry
  400. return $this->currentCell;
  401. }
  402. /**
  403. * Clear the cell collection and disconnect from our parent.
  404. */
  405. public function unsetWorksheetCells()
  406. {
  407. if ($this->currentCell !== null) {
  408. $this->currentCell->detach();
  409. $this->currentCell = null;
  410. $this->currentCoordinate = null;
  411. }
  412. // Flush the cache
  413. $this->__destruct();
  414. $this->index = [];
  415. // detach ourself from the worksheet, so that it can then delete this object successfully
  416. $this->parent = null;
  417. }
  418. /**
  419. * Destroy this cell collection.
  420. */
  421. public function __destruct()
  422. {
  423. $this->cache->deleteMultiple($this->getAllCacheKeys());
  424. }
  425. /**
  426. * Returns all known cache keys.
  427. *
  428. * @return \Generator|string[]
  429. */
  430. private function getAllCacheKeys()
  431. {
  432. foreach ($this->getCoordinates() as $coordinate) {
  433. yield $this->cachePrefix . $coordinate;
  434. }
  435. }
  436. }