PHP and Javascript implementations of a simple markdown parser
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

spreadsheet.php 92KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858
  1. <?php
  2. /**
  3. * Base spreadsheet calculation error class.
  4. */
  5. class CellException extends Error {
  6. /**
  7. * Brief symbol to show in the cell to signify an error occurred during
  8. * evaluation.
  9. *
  10. * @$string
  11. */
  12. public string $errorSymbol;
  13. /**
  14. * @param string $message error message
  15. * @param string $errorSymbol symbol to show in the cell to indicate an error
  16. */
  17. public function __construct(string $message, string $errorSymbol='#ERROR') {
  18. parent::__construct($message);
  19. $this->errorSymbol = $errorSymbol;
  20. }
  21. }
  22. /**
  23. * Exception thrown when a spreadsheet expression is invalid.
  24. */
  25. class CellSyntaxException extends CellException {
  26. public function __construct(string $message, string $errorSymbol='#SYNTAX') {
  27. parent::__construct($message, $errorSymbol);
  28. }
  29. }
  30. /**
  31. * Exception thrown when a problem occurrs during evaluation.
  32. */
  33. class CellEvaluationException extends CellException {}
  34. /**
  35. * Exception thrown when cell dependencies cannot be resolved.
  36. */
  37. class CellDependencyException extends CellException {
  38. public function __construct(string $message, string $errorSymbol='#REF') {
  39. parent::__construct($message, $errorSymbol);
  40. }
  41. }
  42. /**
  43. * Expression parsing token types.
  44. */
  45. enum CellExpressionTokenType {
  46. case Name;
  47. case Address;
  48. case NameOrAddress;
  49. case String;
  50. case Number;
  51. case OpenParen;
  52. case CloseParen;
  53. case Colon;
  54. case Plus;
  55. case Minus;
  56. case Multiply;
  57. case Divide;
  58. case Comma;
  59. case Semicolon;
  60. case Ampersand;
  61. case LessThan;
  62. case LessThanEqual;
  63. case GreaterThan;
  64. case GreaterThanEqual;
  65. case Equal;
  66. case Unequal;
  67. case Not;
  68. public function isPotentialName(): bool {
  69. return $this === self::Name || $this === self::NameOrAddress;
  70. }
  71. public function isPotentialAddress(): bool {
  72. return $this === self::Address || $this === self::NameOrAddress;
  73. }
  74. }
  75. /**
  76. * Type of operation for a `CellExpression`. Named functions all fall under
  77. * `Function`.
  78. */
  79. enum CellExpressionOperation {
  80. /** Arg is `number` */
  81. case Number;
  82. /** Arg is `string` without quotes */
  83. case String;
  84. /** Arg is `boolean` */
  85. case Boolean;
  86. /** Arg is `CellAddress` */
  87. case Reference;
  88. /** Args are start and end `CellAddress`es (e.g. "A5", "C7") */
  89. case Range;
  90. /** Args are two operand `CellExpression`s. */
  91. case Add;
  92. /** Args are two operand `CellExpression`s */
  93. case Subtract;
  94. /** Args are two operand `CellExpression`s */
  95. case Multiply;
  96. /** Args are two operand `CellExpression`s */
  97. case Divide;
  98. /** Args are two operand `CellExpression`s. */
  99. case Concatenate;
  100. /** Arg is operand `CellExpression` */
  101. case UnaryMinus;
  102. /** Args are two operand `CellExpression`s. */
  103. case GreaterThan;
  104. /** Args are two operand `CellExpression`s. */
  105. case GreaterThanEqual;
  106. /** Args are two operand `CellExpression`s. */
  107. case LessThan;
  108. /** Args are two operand `CellExpression`s. */
  109. case LessThanEqual;
  110. /** Args are two operand `CellExpression`s. */
  111. case Equal;
  112. /** Args are two operand `CellExpression`s. */
  113. case Unequal;
  114. /** Arg is operand `CellExpression`. */
  115. case UnaryNot;
  116. /** Args are 0+ `CellExpression`s */
  117. case Function;
  118. }
  119. /**
  120. * Collection of all calculated cells in a table. Evaluates formulas.
  121. */
  122. class CellExpressionSet {
  123. private SpreadsheetGrid $grid;
  124. public function __construct(SpreadsheetGrid $grid) {
  125. $this->grid = $grid;
  126. }
  127. /**
  128. * Populates the `outputValue` fields of every cell in the table. Cells
  129. * with formulas will attempt to be calculated or populated with error
  130. * values.
  131. */
  132. public function calculateCells() {
  133. $rowCount = $this->grid->rowCount;
  134. $colCount = $this->grid->columnCount;
  135. // Make queue of cell addresses with expressions in them
  136. /** @$CellAddress[] */
  137. $expressionAddressQueue = [];
  138. $range = new CellAddressRange(new CellAddress(0, 0), new CellAddress($colCount - 1, $rowCount - 1));
  139. foreach ($range->cellsIn($this->grid) as $address) {
  140. $cell = $this->grid->cellAt($address);
  141. $value = $cell->originalValue;
  142. if ($value->type != CellValue::TYPE_FORMULA) {
  143. $cell->outputValue = $value;
  144. $cell->isCalculated = false;
  145. continue;
  146. }
  147. try {
  148. $expression = CellExpression::parse($value->formattedValue, $address);
  149. if (!$expression) {
  150. throw new CellSyntaxException("Invalid expression");
  151. }
  152. $cell->parsedExpression = $expression;
  153. $cell->isCalculated = true;
  154. array_push($expressionAddressQueue, $address);
  155. $this->enqueueFilledBlanks($expression, $expressionAddressQueue);
  156. } catch (CellException $e) {
  157. $cell->outputValue = CellValue::fromValue($e);
  158. }
  159. }
  160. // Try to evaluate each cell. If one depends on cells not yet calculated,
  161. // move it to the back of the queue and try again later.
  162. $this->processExpressionQueue($expressionAddressQueue);
  163. // Anything left in the queue is a circular reference.
  164. $this->processCircularReferences($expressionAddressQueue);
  165. }
  166. /**
  167. * Attempts to evaluate expressions at the given `addresses`. If an
  168. * expression has unevaluated references, the expression is moved to the
  169. * end of the queue and tried again later. When this method returns, any
  170. * elements left in `addresses` can be considered circular references.
  171. *
  172. * @param CellAddress[] $addresses mutable queue of formula addresses
  173. */
  174. private function processExpressionQueue(array &$addresses) {
  175. $requeueCount = 0;
  176. while (sizeof($addresses) > 0 && $requeueCount < sizeof($addresses)) {
  177. $address = $addresses[0];
  178. array_splice($addresses, 0, 1);
  179. $cell = $this->grid->cellAt($address);
  180. try {
  181. $result = $this->evaluate($cell->parsedExpression, $address);
  182. $cell->isCalculated = true;
  183. if ($result instanceof CellValue) {
  184. $cell->outputValue = $result;
  185. $requeueCount = 0;
  186. } elseif (is_array($result)) {
  187. if (sizeof($result) == 1) {
  188. $cell->outputValue = $result[0];
  189. $requeueCount = 0;
  190. } else {
  191. throw new CellEvaluationException("Expression resolved to " . sizeof($result) . " values, single value expected");
  192. }
  193. } else {
  194. $typename = gettype($result) == 'object' ? get_class($result) : gettype($result);
  195. throw new CellEvaluationException("Expression resolved to {$typename}, expected CellValue");
  196. }
  197. } catch (CellDependencyException $e) {
  198. // Depends on a value that hasn't been calculated yet
  199. array_push($addresses, $address);
  200. $requeueCount++;
  201. } catch (CellSyntaxException | CellEvaluationException $e) {
  202. $cell->outputValue = CellValue::fromValue($e);
  203. $requeueCount = 0;
  204. }
  205. }
  206. }
  207. /**
  208. * Autofills a formula, transposing the formula to each affected cell and
  209. * stored in `parsedExpression`, and each address is queued in `addresses`
  210. * for evaluation.
  211. *
  212. * @param CellExpression $expression autofilled formula
  213. * @param CellAddress[] $addresses mutable address queue
  214. */
  215. private function enqueueFilledBlanks(CellExpression $expression, array &$addresses) {
  216. foreach ($expression->fillRanges ?? [] as $range) {
  217. foreach ($range->cellsIn($this->grid) as $filledAddress) {
  218. $filledCell = $this->grid->cellAt($filledAddress);
  219. if ($filledCell->originalValue->type === CellValue::TYPE_BLANK &&
  220. (!$filledCell->outputValue ||
  221. $filledCell->outputValue->type === CellValue::TYPE_BLANK)) {
  222. $filledCell->parsedExpression = $expression->transpose($expression->location, $filledAddress);
  223. $filledCell->isCalculated = true;
  224. array_push($addresses, $filledAddress);
  225. }
  226. }
  227. }
  228. }
  229. /**
  230. * Marks all cells at the given addresses as circular references.
  231. *
  232. * @param CellAddress[] $addresses mutable address queue
  233. */
  234. private function processCircularReferences(array $addresses) {
  235. foreach ($addresses as $address) {
  236. $cell = $this->grid->cellAt($address);
  237. $cell->outputValue = CellValue::fromValue(new CellDependencyException("Circular reference at {$address->name}"));
  238. }
  239. }
  240. /**
  241. * Evaluates an expression if possible.
  242. *
  243. * @param CellExpression $expr expression to evaluate
  244. * @param CellAddress $address location of expression
  245. * @return CellValue|CellValue[] results
  246. */
  247. private function evaluate(CellExpression $expr, CellAddress $address) {
  248. $result = $this->preevaluate($expr, $address);
  249. if ($result instanceof CellValue) {
  250. // Expression included formatting override. Apply it to value.
  251. if ($expr->outputType !== null) {
  252. return CellValue::fromValue($result->value, $expr->outputType ??
  253. $result->type, $expr->outputDecimals);
  254. }
  255. }
  256. return $result;
  257. }
  258. /**
  259. * Evaluates an expression if possible. No custom formatting is applied to
  260. * result.
  261. *
  262. * @param CellExpression $expr expression to evaluate
  263. * @param CellAddress $address location of expression
  264. * @return CellValue|CellValue[] results
  265. * @throws CellException if evaluation fails for any reason
  266. */
  267. private function preevaluate(CellExpression $expr, CellAddress $address) {
  268. switch ($expr->op) {
  269. case CellExpressionOperation::Number:
  270. case CellExpressionOperation::String:
  271. case CellExpressionOperation::Boolean:
  272. return $expr->arguments[0];
  273. case CellExpressionOperation::Reference: {
  274. $refAddress = $expr->arguments[0];
  275. $cell = $this->grid->cellAt($refAddress);
  276. if ($cell === null) {
  277. throw new CellEvaluationException("No cell at {$refAddress->name}", '#REF');
  278. }
  279. if ($cell->outputValue === null) {
  280. throw new CellDependencyException("Need calculated value for {$refAddress} to evaluate");
  281. }
  282. return $cell->outputValue;
  283. }
  284. case CellExpressionOperation::Range: {
  285. $range = $expr->arguments[0];
  286. $values = [];
  287. foreach ($range->cellsIn($this->grid) as $rAddress) {
  288. $cell = $this->grid->cellAt($rAddress);
  289. if ($rAddress->equals($address)) continue;
  290. $val = $this->grid->outputValueAt($rAddress);
  291. if ($val === null) {
  292. throw new CellDependencyException("Need calculated value for {$rAddress->name} to evaluate");
  293. }
  294. array_push($values, $val);
  295. }
  296. return $values;
  297. }
  298. case CellExpressionOperation::Add: {
  299. $op1 = $this->evaluate($expr->arguments[0], $address);
  300. $op2 = $this->evaluate($expr->arguments[1], $address);
  301. return $op1->add($op2);
  302. }
  303. case CellExpressionOperation::Subtract: {
  304. $op1 = $this->evaluate($expr->arguments[0], $address);
  305. $op2 = $this->evaluate($expr->arguments[1], $address);
  306. return $op1->subtract($op2);
  307. }
  308. case CellExpressionOperation::Multiply: {
  309. $op1 = $this->evaluate($expr->arguments[0], $address);
  310. $op2 = $this->evaluate($expr->arguments[1], $address);
  311. return $op1->multiply($op2);
  312. }
  313. case CellExpressionOperation::Divide: {
  314. $op1 = $this->evaluate($expr->arguments[0], $address);
  315. $op2 = $this->evaluate($expr->arguments[1], $address);
  316. return $op1->divide($op2);
  317. }
  318. case CellExpressionOperation::UnaryMinus: {
  319. $op = $this->evaluate($expr->arguments[0], $address);
  320. return CellValue::fromValue(0)->subtract($op);
  321. }
  322. case CellExpressionOperation::GreaterThan: {
  323. $op1 = $this->evaluate($expr->arguments[0], $address);
  324. $op2 = $this->evaluate($expr->arguments[1], $address);
  325. return $op1->gt($op2);
  326. }
  327. case CellExpressionOperation::GreaterThanEqual: {
  328. $op1 = $this->evaluate($expr->arguments[0], $address);
  329. $op2 = $this->evaluate($expr->arguments[1], $address);
  330. return $op1->gte($op2);
  331. }
  332. case CellExpressionOperation::LessThan: {
  333. $op1 = $this->evaluate($expr->arguments[0], $address);
  334. $op2 = $this->evaluate($expr->arguments[1], $address);
  335. return $op1->lt($op2);
  336. }
  337. case CellExpressionOperation::LessThanEqual: {
  338. $op1 = $this->evaluate($expr->arguments[0], $address);
  339. $op2 = $this->evaluate($expr->arguments[1], $address);
  340. return $op1->lte($op2);
  341. }
  342. case CellExpressionOperation::Equal: {
  343. $op1 = $this->evaluate($expr->arguments[0], $address);
  344. $op2 = $this->evaluate($expr->arguments[1], $address);
  345. return $op1->eq($op2);
  346. }
  347. case CellExpressionOperation::Unequal: {
  348. $op1 = $this->evaluate($expr->arguments[0], $address);
  349. $op2 = $this->evaluate($expr->arguments[1], $address);
  350. return $op1->neq($op2);
  351. }
  352. case CellExpressionOperation::UnaryNot: {
  353. $op = $this->evaluate($expr->arguments[0], $address);
  354. return $op->not();
  355. }
  356. case CellExpressionOperation::Concatenate: {
  357. $op1 = $this->evaluate($expr->arguments[0], $address);
  358. $op2 = $this->evaluate($expr->arguments[1], $address);
  359. return $op1->concatenate($op2);
  360. }
  361. case CellExpressionOperation::Function:
  362. return $this->callFunction($expr->qualifier, $expr->arguments, $address);
  363. }
  364. throw new CellSyntaxException("Unhandled operation {$expr->op->name}");
  365. }
  366. /**
  367. * Evaluates a named function, e.g. `ABS`, `SUM`, etc.
  368. *
  369. * @param string $functionName function name
  370. * @param array $args raw arguments
  371. * @param CellAddress $address location of the expression
  372. * @return CellValue result
  373. * @throws CellException if evaluation fails for any reason
  374. */
  375. private function callFunction(string $functionName, array $args, CellAddress $address): CellValue {
  376. switch (mb_strtoupper($functionName)) {
  377. case 'ABS': return $this->funcAbs($args, $address);
  378. case 'AND': return $this->funcAnd($args, $address);
  379. case 'AVERAGE': return $this->funcAverage($args, $address);
  380. case 'CEILING': return $this->funcCeiling($args, $address);
  381. case 'EXP': return $this->funcExp($args, $address);
  382. case 'FLOOR': return $this->funcFloor($args, $address);
  383. case 'IF': return $this->funcIf($args, $address);
  384. case 'IFS': return $this->funcIfs($args, $address);
  385. case 'LN': return $this->funcLn($args, $address);
  386. case 'LOG': return $this->funcLog($args, $address);
  387. case 'LOWER': return $this->funcLower($args, $address);
  388. case 'MAX': return $this->funcMax($args, $address);
  389. case 'MIN': return $this->funcMin($args, $address);
  390. case 'MOD': return $this->funcMod($args, $address);
  391. case 'NOT': return $this->funcNot($args, $address);
  392. case 'OR': return $this->funcOr($args, $address);
  393. case 'POWER': return $this->funcPower($args, $address);
  394. case 'ROUND': return $this->funcRound($args, $address);
  395. case 'SQRT': return $this->funcSqrt($args, $address);
  396. case 'SUBSTITUTE': return $this->funcSubstitute($args, $address);
  397. case 'SUM': return $this->funcSum($args, $address);
  398. case 'UPPER': return $this->funcUpper($args, $address);
  399. case 'XOR': return $this->funcXor($args, $address);
  400. default:
  401. throw new CellSyntaxException("Unknown function \"{$functionName}\"");
  402. }
  403. }
  404. /**
  405. * Checks and evaluates arguments for a numeric function. If successful,
  406. * an array of `CellValue`s with numeric values is returned.
  407. *
  408. * @param string $functionName name of the function (for debugging)
  409. * @param int $minArgs minimum required arguments
  410. * @param int $maxArgs maximum required arguments
  411. * @param array $args raw arguments
  412. * @param CellAddress $address address of the formula
  413. * @return CellValue[] numeric arguments
  414. * @throws CellSyntaxException if wrong number of arguments is passed
  415. * @throws CellEvaluationException if an argument does not resolve to a numeric value
  416. */
  417. private function assertNumericArguments(string $functionName, int $minArgs,
  418. int $maxArgs, array $args, CellAddress $address): array {
  419. $argCount = sizeof($args);
  420. if ($argCount < $minArgs || $argCount > $maxArgs) {
  421. if ($minArgs == $maxArgs) {
  422. throw new CellSyntaxException("{$functionName}() expects {$minArgs} arguments, got {$argCount}");
  423. }
  424. throw new CellSyntaxException("{$functionName}() expects between {$minArgs} and {$maxArgs} arguments, got {$argCount}");
  425. }
  426. $out = [];
  427. foreach ($args as $argument) {
  428. $evaled = $this->evaluate($argument, $address);
  429. if (!($evaled instanceof CellValue) || !$evaled->isNumeric()) {
  430. throw new CellEvaluationException("{$functionName}() expects numeric arguments");
  431. }
  432. array_push($out, $evaled);
  433. }
  434. return $out;
  435. }
  436. /**
  437. * Evaluates and flattens numeric arguments. For functions that can take
  438. * arbitrary numbers of values including whole cell ranges.
  439. *
  440. * @param string $functionName function name (for debugging)
  441. * @param array $args raw arguments
  442. * @param CellAddress $address location of expression
  443. * @param bool $errorOnNonnumeric whether to throw an exception if
  444. * non-numeric arguments are encountered, otherwise they're skipped silently
  445. * @return CellValue[] flattened array of numeric values
  446. */
  447. private function flattenedNumericArguments(string $functionName, array $args,
  448. CellAddress $address, bool $errorOnNonnumeric=true): array {
  449. $flattened = [];
  450. foreach ($args as $argument) {
  451. $evaled = $this->evaluate($argument, $address);
  452. if ($evaled instanceof CellValue) {
  453. if (!$evaled->isNumeric()) {
  454. if ($errorOnNonnumeric) {
  455. throw new CellEvaluationException("{$functionName} requires numeric arguments");
  456. }
  457. continue;
  458. }
  459. array_push($flattened, $evaled);
  460. } elseif (is_array($evaled)) {
  461. $arr = $evaled;
  462. foreach ($arr as $arrayArgument) {
  463. if ($arrayArgument instanceof CellValue) {
  464. if (!$arrayArgument->isNumeric()) {
  465. if ($errorOnNonnumeric) {
  466. throw new CellEvaluationException("{$functionName} requires numeric arguments");
  467. }
  468. continue;
  469. }
  470. array_push($flattened, $arrayArgument);
  471. }
  472. }
  473. }
  474. }
  475. return $flattened;
  476. }
  477. /**
  478. * `ABS(value)` - absolute value of a numeric argument
  479. *
  480. * @param array $args raw arguments
  481. * @param CellAddress $address expression location
  482. * @return CellValue result
  483. */
  484. private function funcAbs(array $args, CellAddress $address): CellValue {
  485. $arg = $this->assertNumericArguments('ABS', 1, 1, $args, $address)[0];
  486. if ($arg->value < 0.0) {
  487. return CellValue::fromValue(0)->subtract($arg);
  488. }
  489. return $arg;
  490. }
  491. /**
  492. * `AND(arg, arg, ..., arg)` - Boolean AND of any number of Boolean arguments
  493. *
  494. * @param array $args raw arguments
  495. * @param CellAddress $address expression location
  496. * @return CellValue result
  497. */
  498. private function funcAnd(array $args, CellAddress $address): CellValue {
  499. if (sizeof($args) == 0) {
  500. throw new CellEvaluationException("AND requires one or more arguments");
  501. }
  502. $values = array_map(fn($arg) => $this->evaluate($arg, $address), $args);
  503. foreach ($values as $value) {
  504. $result = $value->booleanValue();
  505. if ($result === null) {
  506. throw new CellEvaluationException("AND requires boolean arguments");
  507. }
  508. if (!$result) return CellValue::fromValue(false);
  509. }
  510. return CellValue::fromValue(true);
  511. }
  512. /**
  513. * `AVERAGE(arg, arg, ..., arg)` - Averages values. Non-numeric values are
  514. * omitted from the calculation.
  515. *
  516. * @param array $args raw arguments
  517. * @param CellAddress $address expression location
  518. * @return CellValue result
  519. */
  520. private function funcAverage(array $args, CellAddress $address): CellValue {
  521. $sum = CellValue::fromValue(0);
  522. $count = 0;
  523. foreach ($args as $arg) {
  524. $val = $this->evaluate($arg, $address);
  525. if (is_array($val)) {
  526. foreach ($val as $elem) {
  527. if (!$elem->isNumeric()) continue;
  528. $sum = $sum->add($elem);
  529. $count++;
  530. }
  531. } elseif ($val->isNumeric()) {
  532. $sum = $sum->add($val);
  533. $count++;
  534. }
  535. }
  536. return ($count > 0) ? $sum->divide(CellValue::fromValue($count)) : CellValue::fromValue(0);
  537. }
  538. /**
  539. * `CEILING(value)` - Ceiling of a numeric value.
  540. *
  541. * @param array $args raw arguments
  542. * @param CellAddress $address expression location
  543. * @return CellValue result
  544. */
  545. private function funcCeiling(array $args, CellAddress $address): CellValue {
  546. $arg = $this->assertNumericArguments('CEILING', 1, 1, $args, $address)[0];
  547. $newValue = ceil($arg->value);
  548. return CellValue::fromValue($newValue, $arg->type);
  549. }
  550. /**
  551. * `EXP(value)` - Computes _e_ raised to the given exponent.
  552. *
  553. * @param array $args raw arguments
  554. * @param CellAddress $address expression location
  555. * @return CellValue result
  556. */
  557. private function funcExp(array $args, CellAddress $address): CellValue {
  558. $arg = $this->assertNumericArguments('EXP', 1, 1, $args, $address)[0];
  559. $newValue = exp($arg->value);
  560. return CellValue::fromValue($newValue, $arg->type);
  561. }
  562. /**
  563. * `FLOOR(value)` - Numeric value rounded down.
  564. *
  565. * @param array $args raw arguments
  566. * @param CellAddress $address expression location
  567. * @return CellValue result
  568. */
  569. private function funcFloor(array $args, CellAddress $address): CellValue {
  570. $arg = $this->assertNumericArguments('FLOOR', 1, 1, $args, $address)[0];
  571. $newValue =floor($arg->value);
  572. return CellValue::fromValue($newValue, $arg->type);
  573. }
  574. /**
  575. * `IF(test, trueVal, falseVal)` - Conditional test.
  576. *
  577. * @param array $args raw arguments
  578. * @param CellAddress $address expression location
  579. * @return CellValue result
  580. */
  581. private function funcIf(array $args, CellAddress $address): CellValue {
  582. if (sizeof($args) != 3) {
  583. throw new CellEvaluationException("IF expects three arguments");
  584. }
  585. $evaled = array_map(fn($arg) => $this->evaluate($arg, $address), $args);
  586. $test = $evaled[0]->booleanValue();
  587. if ($test === null) {
  588. throw new CellEvaluationException("IF expects a boolean for the first argument");
  589. }
  590. if ($test) {
  591. return $evaled[1];
  592. } else {
  593. return $evaled[2];
  594. }
  595. }
  596. /**
  597. * `IFS(test1, result1, test2, result2, ..., fallbackResult)` - Multiple if
  598. * statement. Takes 3 or more arguments of an odd number consisting of pairs
  599. * of a Boolean test followed by the value to return if true. The very last
  600. * value is the fallback value to return if none of the Boolean tests are true.
  601. *
  602. * @param array $args raw arguments
  603. * @param CellAddress $address expression location
  604. * @return CellValue result
  605. */
  606. private function funcIfs(array $args, CellAddress $address): CellValue {
  607. if (sizeof($args) < 3) {
  608. throw new CellEvaluationException("IFS expects at least 3 arguments");
  609. }
  610. if ((sizeof($args) % 2) != 1) {
  611. throw new CellEvaluationException("IFS expects an odd number of arguments");
  612. }
  613. $evaled = array_map(fn($arg) => $this->evaluate($arg, $address), $args);
  614. for ($i = 0; $i < sizeof($evaled) - 1; $i += 2) {
  615. $test = $evaled[i].booleanValue();
  616. if ($test === null) {
  617. throw new CellEvaluationException("IFS expects a boolean for argument " . ($i + 1));
  618. }
  619. if ($test) {
  620. return $evaled[$i + 1];
  621. }
  622. }
  623. return $evaled[sizeof($evaled) - 1];
  624. }
  625. /**
  626. * `LN(value)` - Natural log.
  627. *
  628. * @param array $args raw arguments
  629. * @param CellAddress $address expression location
  630. * @return CellValue result
  631. */
  632. private function funcLn(array $args, CellAddress $address): CellValue {
  633. $arg = $this->assertNumericArguments('LN', 1, 1, $args, $address)[0];
  634. $newValue = log($arg->value);
  635. return CellValue::fromValue($newValue, $arg->type);
  636. }
  637. /**
  638. * `LOG(value, [base])` - Logarithm. Base is 10 if not provided.
  639. *
  640. * @param array $args raw arguments
  641. * @param CellAddress $address expression location
  642. * @return CellValue result
  643. */
  644. private function funcLog(array $args, CellAddress $address): CellValue {
  645. $evaled = $this->assertNumericArguments('LOG', 1, 2, $args, $address);
  646. $exponent = $evaled[0];
  647. $base = (sizeof($evaled) > 1) ? $evaled[1]->value : 10.0;
  648. $newValue = log($exponent->value) / log($base);
  649. return CellValue::fromValue($newValue, $exponent->type);
  650. }
  651. /**
  652. * `LOWER(text)` - Lowercase version of a string.
  653. *
  654. * @param array $args raw arguments
  655. * @param CellAddress $address expression location
  656. * @return CellValue result
  657. */
  658. private function funcLower(array $args, CellAddress $address): CellValue {
  659. if (sizeof($args) != 1) {
  660. throw new CellEvaluationException("LOWER requires one argument");
  661. }
  662. $evaled = array_map(fn($arg) => $this->evaluate($arg, $address), $args);
  663. $s = $evaled[0]->stringValue(true);
  664. if ($s === null) {
  665. throw new CellEvaluationException("LOWER requires one string argument");
  666. }
  667. return CellValue::fromValue(mb_strtolower($s));
  668. }
  669. /**
  670. * `MAX(arg, arg, ... arg)` - Returns the maximum numeric value.
  671. *
  672. * @param array $args raw arguments
  673. * @param CellAddress $address expression location
  674. * @return CellValue result
  675. */
  676. private function funcMax(array $args, CellAddress $address): CellValue {
  677. $maxValue = null;
  678. $flattened = $this->flattenedNumericArguments('MAX', $args, $address);
  679. if (sizeof($flattened) == 0) {
  680. throw new CellEvaluationException("MAX requires at least one numeric argument");
  681. }
  682. foreach ($flattened as $argument) {
  683. if ($maxValue === null || $argument->value > $maxValue->value) {
  684. $maxValue = $argument;
  685. }
  686. }
  687. return $maxValue ?? CellValue::fromValue(0);
  688. }
  689. /**
  690. * `MIN(arg, arg, ... arg)` - Returns the minimum numeric value.
  691. *
  692. * @param array $args raw arguments
  693. * @param CellAddress $address expression location
  694. * @return CellValue result
  695. */
  696. private function funcMin(array $args, CellAddress $address): CellValue {
  697. $minValue = null;
  698. $flattened = $this->flattenedNumericArguments('MIN', $args, $address);
  699. if (sizeof($flattened) == 0) {
  700. throw new CellEvaluationException("MIN requires at least one numeric argument");
  701. }
  702. foreach ($flattened as $argument) {
  703. if ($minValue === null || $argument->value < $minValue->value) {
  704. $minValue = $argument;
  705. }
  706. }
  707. return $minValue ?? CellValue::fromValue(0);
  708. }
  709. /**
  710. * `MOD(value, divisor)` - Returns the remainder after a division.
  711. *
  712. * @param array $args raw arguments
  713. * @param CellAddress $address expression location
  714. * @return CellValue result
  715. */
  716. private function funcMod(array $args, CellAddress $address): CellValue {
  717. if (sizeof($args) != 2) {
  718. throw new CellEvaluationException("MOD requires two numeric arguments");
  719. }
  720. $values = array_map(fn($arg) => $this->evaluate($arg, $address), $args);
  721. return $values[0]->modulo($values[1]);
  722. }
  723. /**
  724. * `NOT(value)` - Boolean NOT of a Boolean value.
  725. *
  726. * @param array $args raw arguments
  727. * @param CellAddress $address expression location
  728. * @return CellValue result
  729. */
  730. private function funcNot(array $args, CellAddress $address): CellValue {
  731. if (sizeof($args) != 1) {
  732. throw new CellEvaluationException("NOT expects one argument");
  733. }
  734. $evaled = array_map(fn($arg) => $this->evaluate($arg, $address), $args);
  735. $b = $evaled[0].booleanValue();
  736. if ($b === null) {
  737. throw new CellEvaluationException("NOT expects boolean argument");
  738. }
  739. return CellValue::fromValue(!$b);
  740. }
  741. /**
  742. * `OR(arg, arg, ... arg)` - Boolean OR of one or more Boolean arguments.
  743. *
  744. * @param array $args raw arguments
  745. * @param CellAddress $address expression location
  746. * @return CellValue result
  747. */
  748. private function funcOr(array $args, CellAddress $address): CellValue {
  749. if (sizeof($args) == 0) {
  750. throw new CellEvaluationException("OR requires one or more arguments");
  751. }
  752. $values = array_map(fn($arg) => $this->evaluate($arg, $address), $args);
  753. foreach ($values as $value) {
  754. $result = $value->booleanValue();
  755. if ($result === null) {
  756. throw new CellEvaluationException("OR requires boolean arguments");
  757. }
  758. if ($result) return CellValue::fromValue(true);
  759. }
  760. return CellValue::fromValue(false);
  761. }
  762. /**
  763. * `POWER(base, exponent)` - Raises a base to an exponent.
  764. *
  765. * @param array $args raw arguments
  766. * @param CellAddress $address expression location
  767. * @return CellValue result
  768. */
  769. private function funcPower(array $args, CellAddress $address): CellValue {
  770. $evaled = $this->assertNumericArguments('POWER', 2, 2, $args, $address);
  771. $base = $evaled[0];
  772. $exp = $evaled[1];
  773. $val = pow($base->value, $exp->value);
  774. return CellValue::fromValue($val, $base->type);
  775. }
  776. /**
  777. * `ROUND(value, [places])` - Rounds a number, optionally to the given number
  778. * of digits after the decimal place. Negative places round to the nearest
  779. * 10, 100, 1000, etc.
  780. *
  781. * @param array $args raw arguments
  782. * @param CellAddress $address expression location
  783. * @return CellValue result
  784. */
  785. private function funcRound(array $args, CellAddress $address): CellValue {
  786. $evaled = $this->assertNumericArguments('ROUND', 1, 2, $args, $address);
  787. $val = $evaled[0];
  788. $places = sizeof($evaled) > 1 ? $evaled[1]->value : 0;
  789. $divider = pow(10.0, $places);
  790. $newValue = round($val->value * $divider) / $divider;
  791. return CellValue::fromValue($newValue, $val->type);
  792. }
  793. /**
  794. * `SQRT(value)` - Square root.
  795. *
  796. * @param array $args raw arguments
  797. * @param CellAddress $address expression location
  798. * @return CellValue result
  799. */
  800. private function funcSqrt(array $args, CellAddress $address): CellValue {
  801. $arg = $this->assertNumericArguments('SQRT', 1, 1, $args, $address)[0];
  802. $val = $arg->numericValue();
  803. return CellValue::fromValue(sqrt($val));
  804. }
  805. /**
  806. * `SUBSTITUTE(text, pattern, replacement)` - Substitutes all occurrences of
  807. * `pattern` within `text` with `replacement`.
  808. *
  809. * @param array $args raw arguments
  810. * @param CellAddress $address expression location
  811. * @return CellValue result
  812. */
  813. private function funcSubstitute(array $args, CellAddress $address): CellValue {
  814. if (sizeof($args) != 3) {
  815. throw new CellEvaluationException("SUBSTITUTE expects 3 string arguments");
  816. }
  817. $values = array_map(fn($arg) => $this->evaluate($arg, $address), $args);
  818. $text = $values[0]->stringValue();
  819. $search = $values[1]->stringValue();
  820. $replace = $values[2]->stringValue();
  821. if ($text === null || $search === null || $replace === null) {
  822. throw new CellEvaluationException("SUBSTITUTE expects 3 string arguments");
  823. }
  824. $result = str_replace($search, $replace, $text);
  825. return CellValue::fromValue($result);
  826. }
  827. /**
  828. * `SUM(arg, arg, ... arg)` - Calculates the sum of numeric arguments.
  829. *
  830. * @param array $args raw arguments
  831. * @param CellAddress $address expression location
  832. * @return CellValue result
  833. */
  834. private function funcSum(array $args, CellAddress $address): CellValue {
  835. $sum = CellValue::fromValue(0);
  836. foreach ($args as $arg) {
  837. $val = $this->evaluate($arg, $address);
  838. if (is_array($val)) {
  839. foreach ($val as $elem) {
  840. if ($elem->isNumeric()) $sum = $sum->add($elem);
  841. }
  842. } elseif ($val->isNumeric()) {
  843. $sum = $sum->add($val);
  844. }
  845. }
  846. return $sum;
  847. }
  848. /**
  849. * `UPPER(text)` - Uppercase of a text argument.
  850. *
  851. * @param array $args raw arguments
  852. * @param CellAddress $address expression location
  853. * @return CellValue result
  854. */
  855. private function funcUpper(array $args, CellAddress $address): CellValue {
  856. if (sizeof($args) != 1) {
  857. throw new CellEvaluationException("UPPER requires one argument");
  858. }
  859. $evaled = array_map(fn($arg) => $this->evaluate($arg, $address), $args);
  860. $s = $evaled[0]->stringValue(true);
  861. if ($s === null) {
  862. throw new CellEvaluationException("UPPER requires one string argument");
  863. }
  864. return CellValue::fromValue(mb_strtoupper($s));
  865. }
  866. /**
  867. * `XOR(arg, arg, ... arg)` - Boolean XOR of one or more Boolean arguments.
  868. *
  869. * @param array $args raw arguments
  870. * @param CellAddress $address expression location
  871. * @return CellValue result
  872. */
  873. private function funcXor(array $args, CellAddress $address): CellValue {
  874. if (sizeof($args) == 0) {
  875. throw new CellEvaluationException("XOR requires one or more arguments");
  876. }
  877. $values = array_map(fn($arg) => $this->evaluate($arg, $address), $args);
  878. $result = null;
  879. foreach ($values as $value) {
  880. $b = $value->booleanValue();
  881. if ($b === null) {
  882. throw new CellEvaluationException("XOR requires boolean arguments");
  883. }
  884. $result = ($result === null) ? $b : ($result ^ $b);
  885. }
  886. return CellValue::fromValue($result != 0);
  887. }
  888. }
  889. /**
  890. * A spreadsheet formula expression. Evaluation is done by `CellExpressionSet`.
  891. */
  892. class CellExpression {
  893. /**
  894. * Operation.
  895. */
  896. public CellExpressionOperation $op;
  897. /**
  898. * Mixed array of `CellValue`, `CellAddress`, `CellAddressRange`,
  899. * `CellExpression`, perhaps more.
  900. */
  901. public array $arguments;
  902. /**
  903. * For `Function`, the function name.
  904. */
  905. public ?string $qualifier;
  906. /**
  907. * Optional format override. One of `number`, `currency`, `percent`.
  908. */
  909. public ?string $outputType = null;
  910. /**
  911. * Optional decimal place formatting override.
  912. */
  913. public ?int $outputDecimals = null;
  914. /**
  915. * Address ranges to copy this expression into for any blank cells. Used
  916. * by formulas with the `FILL` modifier.
  917. * @var CellAddressRange[]|null $fillRanges
  918. */
  919. public ?array $fillRanges = null;
  920. /**
  921. * Source address of the formula.
  922. */
  923. public ?CellAddress $location = null;
  924. /**
  925. * @param CellExpressionOperation $op
  926. * @param array $args
  927. * @param ?string $qualifier
  928. */
  929. public function __construct(CellExpressionOperation $op, array $args,
  930. ?string $qualifier = null) {
  931. $this->op = $op;
  932. $this->arguments = $args;
  933. $this->qualifier = $qualifier;
  934. }
  935. /**
  936. * Attempts to parse a formula expression.
  937. *
  938. * @param string $expression formula string, including leading `=`
  939. * @param CellAddress $address location of the formula
  940. * @return ?CellExpression parsed expression, or `null` if it failed
  941. */
  942. public static function parse(string $expression, CellAddress $address): ?CellExpression {
  943. $tokens = $this->expressionToTokens($expression);
  944. if (sizeof($tokens) == 0) return null;
  945. $expr = $this->expressionFromTokens($tokens, $address);
  946. $expr->location = $address;
  947. return $expr;
  948. }
  949. /**
  950. * Writes an expression tree to `error_log` for debugging purposes.
  951. *
  952. * @param CellExpression $expression
  953. * @param string $indent
  954. */
  955. public static function dumpExpression(CellExpression $expression, string $indent = '') {
  956. if (sizeof($expression->arguments) == 0) {
  957. error_log($indent . "expr " . $expression->op->name . "()");
  958. } else {
  959. error_log($indent . $expression->op->name . '(');
  960. foreach ($expression->arguments as $argument) {
  961. if (is_numeric($argument)) {
  962. error_log($indent . "\t{$argument}");
  963. } elseif (is_string($argument)) {
  964. error_log($indent . "\t\"{$argument}\"");
  965. } elseif (is_bool($argument)) {
  966. error_log($indent . "\t" . ($argument ? "true" : "false"));
  967. } elseif ($argument instanceof CellAddress) {
  968. error_log($indent . "\t" . $argument->name);
  969. } elseif ($argument instanceof CellAddressRange) {
  970. error_log($indent . "\t" . $argument->name);
  971. } elseif ($argument instanceof CellValue) {
  972. error_log($indent . "\t" . $argument->type . " " . $argument->formattedValue);
  973. } elseif ($argument instanceof CellExpression) {
  974. $this->dumpExpression($argument, $indent + "\t");
  975. } else {
  976. error_log($indent . "\t" . gettype($argument));
  977. }
  978. }
  979. error_log($indent . ')');
  980. }
  981. }
  982. private function clone(): CellExpression {
  983. $cp = new CellExpression();
  984. $cp->op = $this->op;
  985. $cp->arguments = array($this->arguments);
  986. $cp->qualifier = $this->qualifier;
  987. $cp->outputType = $this->outputType;
  988. $cp->outputDecimals = $this->outputDecimals;
  989. $cp->fillRanges = $this->fillRanges !== null ? array($this->fillRanges) : null;
  990. $cp->location = $this->location;
  991. return $cp;
  992. }
  993. /**
  994. * Returns a copy of this expression with cell references transposed by
  995. * the delta between `$start` and `$end` addresses. Used for repeating an
  996. * autofilled formula into blank cells.
  997. */
  998. public function transpose(CellAddress $start, CellAddress $end): ?CellExpression {
  999. $transposed = $this->clone(); // structuredClone makes a mess of typing
  1000. $transposed->arguments = [];
  1001. foreach ($this->arguments as $argument) {
  1002. if ($argument instanceof CellExpression) {
  1003. array_push($transposed->arguments, $argument->transpose($start, $end));
  1004. } elseif ($argument instanceof CellAddress) {
  1005. array_push($transposed->arguments, $argument->transpose($start, $end));
  1006. } elseif ($argument instanceof CellAddressRange) {
  1007. array_push($transposed->arguments, $argument->transpose($start, $end));
  1008. } else {
  1009. array_push($transposed->arguments, $argument);
  1010. }
  1011. }
  1012. return $transposed;
  1013. }
  1014. // -- Tokenizing --------------------------------------------------------
  1015. /**
  1016. * Converts an expression into an array of tokens.
  1017. * @param string $text expression
  1018. * @return CellExpressionToken[] tokens
  1019. */
  1020. public static function expressionToTokens(string $text): array {
  1021. $tokens = [];
  1022. $pos = [0];
  1023. $this->skipWhitespace($text, $pos);
  1024. if (mb_substr($text, $pos[0], 1) == '=') {
  1025. // Ignore equals
  1026. $pos[0]++;
  1027. }
  1028. $this->skipWhitespace($text, $pos);
  1029. $l = mb_strlen($text);
  1030. while ($pos[0] < $l) {
  1031. array_push($tokens, $this->readNextToken($text, $pos));
  1032. $this->skipWhitespace($text, $pos);
  1033. }
  1034. return $tokens;
  1035. }
  1036. /**
  1037. * @param string $text
  1038. * @param int $pos
  1039. * @return CellExpressionToken
  1040. */
  1041. private static function readNextToken(string $text, int &$pos): CellExpressionToken {
  1042. // Single char tokens
  1043. if ($token = $this->readNextSimpleToken($text, $pos, '==', CellExpressionTokenType::Equal)) return $token;
  1044. if ($token = $this->readNextSimpleToken($text, $pos, '!=', CellExpressionTokenType::Unequal)) return $token;
  1045. if ($token = $this->readNextSimpleToken($text, $pos, '<=', CellExpressionTokenType::LessThanEqual)) return $token;
  1046. if ($token = $this->readNextSimpleToken($text, $pos, '>=', CellExpressionTokenType::GreaterThanEqual)) return $token;
  1047. if ($token = $this->readNextSimpleToken($text, $pos, '<', CellExpressionTokenType::LessThan)) return $token;
  1048. if ($token = $this->readNextSimpleToken($text, $pos, '>', CellExpressionTokenType::GreaterThan)) return $token;
  1049. if ($token = $this->readNextSimpleToken($text, $pos, '!', CellExpressionTokenType::Not)) return $token;
  1050. if ($token = $this->readNextSimpleToken($text, $pos, '+', CellExpressionTokenType::Plus)) return $token;
  1051. if ($token = $this->readNextSimpleToken($text, $pos, '-', CellExpressionTokenType::Minus)) return $token;
  1052. if ($token = $this->readNextSimpleToken($text, $pos, '*', CellExpressionTokenType::Multiply)) return $token;
  1053. if ($token = $this->readNextSimpleToken($text, $pos, '/', CellExpressionTokenType::Divide)) return $token;
  1054. if ($token = $this->readNextSimpleToken($text, $pos, ',', CellExpressionTokenType::Comma)) return $token;
  1055. if ($token = $this->readNextSimpleToken($text, $pos, '(', CellExpressionTokenType::OpenParen)) return $token;
  1056. if ($token = $this->readNextSimpleToken($text, $pos, ')', CellExpressionTokenType::CloseParen)) return $token;
  1057. if ($token = $this->readNextSimpleToken($text, $pos, ':', CellExpressionTokenType::Colon)) return $token;
  1058. if ($token = $this->readNextSimpleToken($text, $pos, ';', CellExpressionTokenType::Semicolon)) return $token;
  1059. if ($token = $this->readNextSimpleToken($text, $pos, '&', CellExpressionTokenType::Ampersand)) return $token;
  1060. // Other tokens
  1061. if ($token = $this->readNextAddressToken($text, $pos)) return $token;
  1062. if ($token = $this->readNextNameToken($text, $pos)) return $token;
  1063. if ($token = $this->readNextNumberToken($text, $pos)) return $token;
  1064. if ($token = $this->readNextStringToken($text, $pos)) return $token;
  1065. $ch = mb_substr($text, $pos, 1);
  1066. throw new CellSyntaxException("Unexpected character \"{$ch}\" at {$pos}");
  1067. }
  1068. private static function skipWhitespace(string $text, int &$pos) {
  1069. $l = mb_strlen($text);
  1070. while ($pos < $l) {
  1071. $ch = mb_substr($text, $pos, 1);
  1072. if ($ch == ' ' || $ch == "\t" || $ch == "\n" || $ch == "\r") {
  1073. $pos++;
  1074. } else {
  1075. return;
  1076. }
  1077. }
  1078. }
  1079. private static function readNextSimpleToken(string $text, int &$pos,
  1080. string $target, CellExpressionTokenType $type): ?CellExpressionToken {
  1081. $remaining = mb_strlen($text) - $pos;
  1082. $l = mb_strlen($target);
  1083. if ($l > $remaining) return null;
  1084. $test = mb_substr($text, $pos, $l);
  1085. if (mb_strtoupper($test) != mb_strtoupper($target)) return null;
  1086. $pos += $l;
  1087. return new CellExpressionToken($type, $test);
  1088. }
  1089. private static function readNextAddressToken(string $text, int &$pos): ?CellExpressionToken {
  1090. $p = $pos;
  1091. $ch = mb_substr($text, $p, 1);
  1092. $address = '';
  1093. $isName = true;
  1094. if ($ch == '$') {
  1095. $address += $ch;
  1096. $isName = false;
  1097. $p++;
  1098. }
  1099. $col = $this->readChars($text, $p, fn($s) => $this->isLetter($s), 1, 2);
  1100. if ($col === null) return null;
  1101. $address += $col;
  1102. $ch = mb_substr($text, $p, 1);
  1103. if ($ch == '$') {
  1104. $address += $ch;
  1105. $isName = false;
  1106. $p++;
  1107. $row = $this->readChars($text, $p, $this->isDigit, 1);
  1108. if ($row === null) return null;
  1109. $address += $row;
  1110. } else {
  1111. $row = $this->readChars($text, $p, $this->isDigit, 0);
  1112. if ($row === null) return null;
  1113. $address += $row;
  1114. }
  1115. $pos = $p;
  1116. return new CellExpressionToken(
  1117. $isName ? CellExpressionTokenType::NameOrAddress : CellExpressionTokenType::Address,
  1118. $address);
  1119. }
  1120. private static function readNextNameToken(string $text, int &$pos): ?CellExpressionToken {
  1121. $p = $pos;
  1122. $name = $this->readChars($text, $p, fn($s) => $this->isLetter($s), 1);
  1123. if ($name === null) return null;
  1124. $pos = $p;
  1125. if (CellAddress::isAddress($name)) {
  1126. return new CellExpressionToken(CellExpressionTokenType::NameOrAddress, $name);
  1127. }
  1128. return new CellExpressionToken(CellExpressionTokenType::Name, $name);
  1129. }
  1130. private static function readNextNumberToken(string $text, int &$pos): ?CellExpressionToken {
  1131. $ch = mb_substr($text, $pos, 1);
  1132. if (!$this->isDigit($ch)) return null;
  1133. $l = mb_strlen($text);
  1134. $numStr = $ch;
  1135. $pos++;
  1136. while ($pos < $l) {
  1137. $ch = mb_substr($text, $pos, 1);
  1138. if ($this->isDigit($ch)) {
  1139. $pos++;
  1140. $numStr .= $ch;
  1141. } else {
  1142. break;
  1143. }
  1144. }
  1145. if ($pos < $l) {
  1146. $ch = mb_substr($text, $pos, 1);
  1147. if ($ch == '.') {
  1148. $numStr .= $ch;
  1149. $pos[0]++;
  1150. while ($pos < $l) {
  1151. $ch = mb_substr($text, $pos[0], 1);
  1152. if ($this->isDigit($ch)) {
  1153. $pos++;
  1154. $numStr .= $ch;
  1155. } else {
  1156. break;
  1157. }
  1158. }
  1159. }
  1160. }
  1161. return new CellExpressionToken(CellExpressionTokenType::Number, $numStr);
  1162. }
  1163. private static function readNextStringToken(string $text, int &$pos): ?CellExpressionToken {
  1164. $ch = mb_substr($text, $pos, 1);
  1165. if ($ch !== '"') return null;
  1166. $str = '';
  1167. $pos++;
  1168. $l = mb_strlen($text);
  1169. $inEscape = false;
  1170. while ($pos < $l) {
  1171. $ch = mb_substr($text, $pos[0], $pos[0] + 1);
  1172. $pos++;
  1173. if ($inEscape) {
  1174. $inEscape = false;
  1175. if ($ch == '\\' || $ch == '"') {
  1176. $str .= $ch;
  1177. } else {
  1178. throw new CellSyntaxException("Bad string escape sequence \"\\{$ch}\"");
  1179. }
  1180. } elseif ($ch == '\\') {
  1181. $inEscape = true;
  1182. } elseif ($ch == '"') {
  1183. return new CellExpressionToken(CellExpressionTokenType::String, $str);
  1184. } else {
  1185. $str += $ch;
  1186. }
  1187. }
  1188. throw new CellSyntaxException('Unterminated string');
  1189. }
  1190. /**
  1191. * Reads the next chars that pass a test function and returns the result.
  1192. *
  1193. * @param string $text
  1194. * @param int $pos
  1195. * @param callable $charTest
  1196. * @param ?int $minimumLength
  1197. * @param ?int $maximumLength
  1198. * @return ?string
  1199. */
  1200. private static function readChars(string $text, int &$pos, callable $charTest,
  1201. ?int $minimumLength = null, ?int $maximumLength = null): ?string {
  1202. $p = $pos;
  1203. $l = mb_strlen($text);
  1204. $s = '';
  1205. $sl = 0;
  1206. while ($p < $l && ($maximumLength === null || $sl < $maximumLength)) {
  1207. $ch = mb_substr($text, $p, 1);
  1208. if (!$charTest($ch)) break;
  1209. $s += $ch;
  1210. $sl++;
  1211. $p++;
  1212. }
  1213. if ($p < $l && $charTest(mb_substr($text, $p, $p + 1))) {
  1214. return null;
  1215. }
  1216. if ($minimumLength !== null && $sl < $minimumLength) {
  1217. return null;
  1218. }
  1219. $pos = $p;
  1220. return $s;
  1221. }
  1222. /**
  1223. * @param string $ch
  1224. * @return bool
  1225. */
  1226. private static function isLetter(string $ch): bool {
  1227. $ord = ord($ch);
  1228. return ($ord >= 65 && $ord <= 90) || ($ord >= 97 && $ord <= 122);
  1229. }
  1230. /**
  1231. * @param string $ch
  1232. * @return bool
  1233. */
  1234. private static function isDigit(string $ch): bool {
  1235. $ord = ord($ch);
  1236. return ($ord >= 48 && $ord <= 57);
  1237. }
  1238. // -- Parsing -----------------------------------------------------------
  1239. /**
  1240. * @param array $tokens
  1241. * @param CellAddress $address
  1242. * @return ?CellExpression
  1243. */
  1244. public static function expressionFromTokens(array $tokens, CellAddress $address): ?CellExpression {
  1245. if ($expr = $this->tryExpressionAndFormat($tokens, 0, sizeof($tokens) - 1, $address)) return $expr;
  1246. if ($expr = $this->tryExpressionAndFill($tokens, 0, sizeof($tokens) - 1, $address)) return $expr;
  1247. if ($expr = $this->tryExpression($tokens, 0, sizeof($tokens) - 1, $address)) return $expr;
  1248. return null;
  1249. }
  1250. /**
  1251. * @param array $tokens
  1252. * @param int $start
  1253. * @param int $end
  1254. * @param CellAddress $address
  1255. * @return ?CellExpression
  1256. */
  1257. private static function tryExpressionAndFormat(array $tokens, int $start,
  1258. int $end, CellAddress $address): ?CellExpression {
  1259. for ($t = $start + 1; $t < $end; $t++) {
  1260. if ($tokens[t]->type == CellExpressionTokenType::Semicolon) {
  1261. $expr = $this->tryExpressionAndFill($tokens, $start, $t - 1, $address) ??
  1262. $this->tryExpression($tokens, $start, $t - 1, $address);
  1263. if ($expr === null) return null;
  1264. $format = $this->tryFormat($tokens, $t + 1, $end, $address);
  1265. if ($format === null) return null;
  1266. [ $expr->outputType, $expr->outputDecimals ] = $format;
  1267. return $expr;
  1268. }
  1269. }
  1270. return null;
  1271. }
  1272. /**
  1273. * @param CellExpressionToken[] $tokens
  1274. * @param int $start
  1275. * @param int $end
  1276. * @param CellAddress $address
  1277. * @return ?CellExpression
  1278. */
  1279. private static function tryExpressionAndFill(array $tokens, int $start,
  1280. int $end, CellAddress $address): ?CellExpression {
  1281. $count = $end - $start + 1;
  1282. if ($count < 2) return null;
  1283. if (!$tokens[$end]->type->isPotentialName()) return null;
  1284. $name = mb_strtoupper($tokens[$end]->content);
  1285. if ($name != 'FILL') return null;
  1286. $exp = $this->tryExpression($tokens, $start, $end - 1, $address);
  1287. $columnIndex = $address->columnIndex;
  1288. $exp->fillRanges = [
  1289. new CellAddressRange(new CellAddress($columnIndex, -1), new CellAddress($columnIndex, -1)),
  1290. ];
  1291. return $exp;
  1292. }
  1293. /**
  1294. * Tries to parse a format suffix after a semicolon. Examples:
  1295. *
  1296. * ```
  1297. * ; number
  1298. * ; number 3
  1299. * ; currency 2
  1300. * ; percent 0
  1301. * ```
  1302. *
  1303. * @param CellExpressionToken[] $tokens
  1304. * @param int $start
  1305. * @param int $end
  1306. * @param CellAddress $address
  1307. * @return ?array CellValue type and decimal places
  1308. */
  1309. private static function tryFormat(array $tokens, int $start, int $end,
  1310. CellAddress $address): ?array {
  1311. $count = $end - $start + 1;
  1312. if ($count < 0 || $count > 2) return null;
  1313. if (!$tokens[$start]->type->isPotentialName()) return null;
  1314. $type = mb_strtolower($tokens[$start]);
  1315. if (!CellValue::isTypeNumeric($type)) return null;
  1316. if ($count > 1) {
  1317. if ($tokens[$start + 1]->type != CellExpressionTokenType::Number) return null;
  1318. $decimals = intval($tokens[$start + 1]->content);
  1319. } else {
  1320. $decimals = null;
  1321. }
  1322. return [ $type, $decimals ];
  1323. }
  1324. /**
  1325. * @param CellExpressionToken[] $tokens
  1326. * @param int $start
  1327. * @param int $end
  1328. * @param CellAddress $address
  1329. * @return CellExpression
  1330. */
  1331. private static function tryExpression(array $tokens, int $start, int $end,
  1332. CellAddress $address): CellExpression {
  1333. if ($expr = $this->tryParenExpression($tokens, $start, $end, $address)) return $expr;
  1334. if ($expr = $this->tryNumber($tokens, $start, $end, $address)) return $expr;
  1335. if ($expr = $this->tryString($tokens, $start, $end, $address)) return $expr;
  1336. if ($expr = $this->tryBoolean($tokens, $start, $end, $address)) return $expr;
  1337. if ($expr = $this->tryFunction($tokens, $start, $end, $address)) return $expr;
  1338. if ($expr = $this->tryRange($tokens, $start, $end, $address)) return $expr;
  1339. if ($expr = $this->tryReference($tokens, $start, $end, $address)) return $expr;
  1340. if ($expr = $this->tryInfix($tokens, $start, $end, $address)) return $expr;
  1341. if ($expr = $this->tryUnary($tokens, $start, $end, $address)) return $expr;
  1342. throw new CellSyntaxException("Invalid expression");
  1343. }
  1344. /**
  1345. * @param CellExpressionToken[] $tokens
  1346. * @param number $start
  1347. * @param number $end
  1348. * @param CellAddress $address
  1349. * @return CellExpression|null
  1350. */
  1351. private static function tryParenExpression(array $tokens, int $start,
  1352. int $end, CellAddress $address): ?CellExpression {
  1353. if ($tokens[$start]->type != CellExpressionTokenType::OpenParen) return null;
  1354. if ($tokens[$end]->type != CellExpressionTokenType::CloseParen) return null;
  1355. $parenLevel = 0;
  1356. for ($t = $start + 1; $t < $end; $t++) {
  1357. if ($tokens[$t]->type == CellExpressionTokenType::OpenParen) {
  1358. $parenLevel++;
  1359. } elseif ($tokens[$t]->type == CellExpressionTokenType::CloseParen) {
  1360. $parenLevel--;
  1361. }
  1362. if ($parenLevel < 0) return null;
  1363. }
  1364. if ($parenLevel != 0) return null;
  1365. return $this->tryExpression($tokens, $start + 1, $end - 1, $address);
  1366. }
  1367. /**
  1368. * @param CellExpressionToken[] $tokens
  1369. * @param number $start
  1370. * @param number $end
  1371. * @param CellAddress $address
  1372. * @return CellExpression|null
  1373. */
  1374. private static function tryNumber(array $tokens, int $start, int $end,
  1375. CellAddress $address): ?CellExpression {
  1376. if ($tokens[$end]->type != CellExpressionTokenType::Number) return null;
  1377. if ($end > $start + 1) return null;
  1378. $val = CellValue::fromCellString($tokens[$end]->content);
  1379. if ($end > $start) {
  1380. if ($tokens[$start]->type != CellExpressionTokenType::Minus) return null;
  1381. $val->value = -$val->value;
  1382. }
  1383. return new CellExpression(CellExpressionOperation::Number, [ $val ]);
  1384. }
  1385. /**
  1386. * @param CellExpressionToken[] $tokens
  1387. * @param number $start
  1388. * @param number $end
  1389. * @param CellAddress $address
  1390. * @return CellExpression|null
  1391. */
  1392. private static function tryString(array $tokens, int $start, int $end,
  1393. CellAddress $address): ?CellExpression {
  1394. if ($start != $end) return null;
  1395. if ($tokens[$start]->type != CellExpressionTokenType::String) return null;
  1396. $str = $tokens[$start]->content;
  1397. return new CellExpression(CellExpressionOperation::String,
  1398. [ new CellValue($str, $str, CellValue::TYPE_STRING, 0) ]);
  1399. }
  1400. /**
  1401. * @param CellExpressionToken[] $tokens
  1402. * @param number $start
  1403. * @param number $end
  1404. * @param CellAddress $address
  1405. * @return CellExpression|null
  1406. */
  1407. private static function tryBoolean(array $tokens, int $start, int $end,
  1408. CellAddress $address): ?CellExpression {
  1409. if ($start != $end) return null;
  1410. if (!$tokens[$start]->type->isPotentialName()) return null;
  1411. $str = mb_strtoupper($tokens[$start]->content);
  1412. if ($str != 'TRUE' && $str != 'FALSE') return null;
  1413. return new CellExpression(CellExpressionOperation::Boolean,
  1414. [ new CellValue($str, $str == 'TRUE', CellValue::TYPE_BOOLEAN) ]);
  1415. }
  1416. /**
  1417. * @param CellExpressionToken[] $tokens
  1418. * @param number $start
  1419. * @param number $end
  1420. * @param CellAddress $address
  1421. * @return CellExpression|null
  1422. */
  1423. private static function tryFunction(array $tokens, int $start, int $end,
  1424. CellAddress $address): ?CellExpression {
  1425. $count = $end - $start + 1;
  1426. if ($count < 3) return null;
  1427. if (!$tokens[$start]->type->isPotentialName()) return null;
  1428. $qualifier = $tokens[$start]->content;
  1429. if ($tokens[$start + 1]->type != CellExpressionTokenType::OpenParen) return null;
  1430. if ($tokens[$end]->type != CellExpressionTokenType::CloseParen) return null;
  1431. $argList = $this->tryArgumentList($tokens, $start + 2, $end - 1, $address);
  1432. if ($argList === null) return null;
  1433. return new CellExpression(CellExpressionOperation::Function, $argList, $qualifier);
  1434. }
  1435. /**
  1436. * @param CellExpressionToken[] $tokens
  1437. * @param number $start
  1438. * @param number $end
  1439. * @param CellAddress $address
  1440. * @return CellExpression[]|null
  1441. */
  1442. private static function tryArgumentList(array $tokens, int $start, int $end,
  1443. CellAddress $address): ?CellExpression {
  1444. $count = $end - $start + 1;
  1445. if ($count == 0) return [];
  1446. $parenDepth = 0;
  1447. $argCount = 1;
  1448. // Populate argTokens with tuples of start and end token indices for each arg.
  1449. /** @type {int[][]} */
  1450. $argTokens = []; // argindex -> [ start, end ]
  1451. $exprStartToken = $start;
  1452. for ($i = $start; $i <= $end; $i++) {
  1453. if ($tokens[$i]->type == CellExpressionTokenType::OpenParen) {
  1454. $parenDepth++;
  1455. } elseif ($tokens[$i]->type == CellExpressionTokenType::CloseParen) {
  1456. $parenDepth--;
  1457. } elseif ($tokens[$i]->type == CellExpressionTokenType::Comma && $parenDepth == 0) {
  1458. $exprEndToken = $i - 1;
  1459. array_push($argTokens, [ $exprStartToken, $exprEndToken ]);
  1460. $exprStartToken = $i + 1;
  1461. }
  1462. }
  1463. array_push($argTokens, [ $exprStartToken, $end ]);
  1464. // Convert token ranges to expressions
  1465. $args = [];
  1466. foreach ($argTokens as $argToken) {
  1467. $arg = $this->tryExpression($tokens, $argToken[0], $argToken[1], $address);
  1468. if ($arg === null) return null;
  1469. $args.push($arg);
  1470. }
  1471. return $args;
  1472. }
  1473. /**
  1474. * @param CellExpressionToken[] $tokens
  1475. * @param number $start
  1476. * @param number $end
  1477. * @param CellAddress $address
  1478. * @return CellExpression|null
  1479. */
  1480. private static function tryRange(array $tokens, int $start, int $end,
  1481. CellAddress $address): ?CellExpression {
  1482. $count = $end - $start + 1;
  1483. if ($count != 3) return null;
  1484. if (!$tokens[$start]->type->isPotentialAddress()) return null;
  1485. $first = mb_strtoupper($tokens[$start]->content);
  1486. if ($tokens[$start + 1]->type != CellExpressionTokenType::Colon) return null;
  1487. if (!$tokens[$end]->type->isPotentialAddress()) return null;
  1488. $last = mb_strtoupper($tokens[$end]->content);
  1489. $firstAddress = CellAddress::fromString($first);
  1490. $lastAddress = CellAddress::fromString($last);
  1491. $range = new CellAddressRange($firstAddress, $lastAddress);
  1492. return new CellExpression(CellExpressionOperation::Range, [ $range ]);
  1493. }
  1494. /**
  1495. * @param CellExpressionToken[] $tokens
  1496. * @param number $start
  1497. * @param number $end
  1498. * @param CellAddress $address
  1499. * @return CellExpression|null
  1500. */
  1501. private static function tryReference(array $tokens, int $start, int $end,
  1502. CellAddress $address): ?CellExpression {
  1503. if ($start != $end) return null;
  1504. if (!$tokens[$start]->type->isPotentialAddress()) return null;
  1505. $ref = mb_strtoupper($tokens[$start]->content);
  1506. $refAddress = CellAddress::fromString($ref, $address, true);
  1507. return new CellExpression(CellExpressionOperation::Reference, [ $refAddress ]);
  1508. }
  1509. private const infixPriority = [
  1510. 'Minus' => 1,
  1511. 'Plus' => 2,
  1512. 'Divide' => 3,
  1513. 'Multiply' => 4,
  1514. 'Ampersand' => 10,
  1515. 'GreaterThan' => 20,
  1516. 'GreaterThanEqual' => 20,
  1517. 'LessThan' => 20,
  1518. 'LessThanEqual' => 20,
  1519. 'Equal' => 20,
  1520. 'Unequal' => 20,
  1521. ];
  1522. /**
  1523. * @param CellExpressionToken[] $tokens
  1524. * @param number $start
  1525. * @param number $end
  1526. * @param CellAddress $address
  1527. * @return CellExpression|null
  1528. */
  1529. private static function tryInfix(array $tokens, int $start, int $end,
  1530. CellAddress $address): ?CellExpression {
  1531. $count = $end - $start + 1;
  1532. if ($count < 3) return null;
  1533. $candidates = [];
  1534. $parenLevel = 0;
  1535. for ($i = $start; $i <= $end; $i++) {
  1536. if ($tokens[$i]->type == CellExpressionTokenType::OpenParen) {
  1537. $parenLevel++;
  1538. } elseif ($tokens[$i]->type == CellExpressionTokenType::CloseParen) {
  1539. $parenLevel--;
  1540. } elseif ($parenLevel == 0 && $i > $start && $i < $end) {
  1541. $op = $tokens[$i]->type->name;
  1542. $priority = $this->infixPriority[$op] ?? false;
  1543. if ($priority === false) continue;
  1544. array_push($candidates, [ 'priority' => priority, 'i' => $i ]);
  1545. }
  1546. }
  1547. usort($candidates, fn($a, $b) => $a['priority'] - $b['priority']);
  1548. $bestCandidate = null;
  1549. foreach ($candidates as $candidate) {
  1550. try {
  1551. $i = $candidate['i'];
  1552. $operand1 = $this->tryExpression($tokens, $start, $i - 1, $address);
  1553. if ($operand1 === null) continue;
  1554. $operand2 = $this->tryExpression($tokens, $i + 1, $end, $address);
  1555. if ($operand2 === null) continue;
  1556. $bestCandidate = $candidate;
  1557. break;
  1558. } catch (e) {
  1559. if (!($e instanceof CellSyntaxException)) {
  1560. throw $e;
  1561. }
  1562. }
  1563. }
  1564. if ($bestCandidate === null) {
  1565. return null;
  1566. }
  1567. $i = $bestCandidate->i;
  1568. switch ($tokens[$bestCandidate['i']]->type) {
  1569. case CellExpressionTokenType::Plus:
  1570. return new CellExpression(CellExpressionOperation::Add, [ $operand1, $operand2 ]);
  1571. case CellExpressionTokenType::Minus:
  1572. return new CellExpression(CellExpressionOperation::Subtract, [ $operand1, $operand2 ]);
  1573. case CellExpressionTokenType::Multiply:
  1574. return new CellExpression(CellExpressionOperation::Multiply, [ $operand1, $operand2 ]);
  1575. case CellExpressionTokenType::Divide:
  1576. return new CellExpression(CellExpressionOperation::Divide, [ $operand1, $operand2 ]);
  1577. case CellExpressionTokenType::GreaterThan:
  1578. return new CellExpression(CellExpressionOperation::GreaterThan, [ $operand1, $operand2 ]);
  1579. case CellExpressionTokenType::GreaterThanEqual:
  1580. return new CellExpression(CellExpressionOperation::GreaterThanEqual, [ $operand1, $operand2 ]);
  1581. case CellExpressionTokenType::LessThan:
  1582. return new CellExpression(CellExpressionOperation::LessThan, [ $operand1, $operand2 ]);
  1583. case CellExpressionTokenType::LessThanEqual:
  1584. return new CellExpression(CellExpressionOperation::LessThanEqual, [ $operand1, $operand2 ]);
  1585. case CellExpressionTokenType::Equal:
  1586. return new CellExpression(CellExpressionOperation::Equal, [ $operand1, $operand2 ]);
  1587. case CellExpressionTokenType::Unequal:
  1588. return new CellExpression(CellExpressionOperation::Unequal, [ $operand1, $operand2 ]);
  1589. case CellExpressionTokenType::Ampersand:
  1590. return new CellExpression(CellExpressionOperation::Concatenate, [ $operand1, $operand2 ]);
  1591. }
  1592. return null;
  1593. }
  1594. /**
  1595. * @param CellExpressionToken[] $tokens
  1596. * @param number $start
  1597. * @param number $end
  1598. * @param CellAddress $address
  1599. * @return CellExpression|null
  1600. */
  1601. private static function tryUnary(array $tokens, int $start, int $end,
  1602. CellAddress $address): ?CellExpression {
  1603. $count = $end - $start + 1;
  1604. if ($count < 2) return null;
  1605. $ops = [
  1606. [ CellExpressionTokenType::Minus, CellExpressionOperation::UnaryMinus ],
  1607. [ CellExpressionTokenType::Not, CellExpressionOperation::UnaryNot ],
  1608. ];
  1609. foreach ($ops as $op) {
  1610. if ($tokens[$start]->type != $op[0]) continue;
  1611. $operand = $this->tryExpression($tokens, $start + 1, $end, $address);
  1612. if ($operand === null) return null;
  1613. return new CellExpression($op[1], [ $operand ]);
  1614. }
  1615. return null;
  1616. }
  1617. }
  1618. /**
  1619. * Parsing token for an expression.
  1620. */
  1621. class CellExpressionToken {
  1622. public CellExpressionTokenType $type;
  1623. public string $content;
  1624. /**
  1625. * @param CellExpressionTokenType $type
  1626. * @param string $content
  1627. */
  1628. public function __construct(CellExpressionTokenType $type, string $content) {
  1629. $this->type = $type;
  1630. $this->content = $content;
  1631. }
  1632. }
  1633. /**
  1634. * The location of a cell in a table. If the address was specified without a
  1635. * row, the address is considered "unresolved" and needs more context to
  1636. * uniquely identify a cell.
  1637. */
  1638. class CellAddress {
  1639. public string $name;
  1640. /**
  1641. * Whether the column should remain unchanged when transposed. This is
  1642. * symbolized by prefixing the column name with a `$` (e.g. `$C3`).
  1643. */
  1644. public bool $isColumnFixed = false;
  1645. /**
  1646. * Zero-based column index.
  1647. */
  1648. public int $columnIndex = -1;
  1649. /**
  1650. * Letter code for the column.
  1651. */
  1652. public function columnLetter(): string { return CellAddress::columnIndexToLetters($this->columnIndex); }
  1653. /**
  1654. * Whether the row should remain unchanged when transposed. This is
  1655. * symbolized by prefixing the row number with a `$` (e.g. `C$3`).
  1656. */
  1657. public bool $isRowFixed = false;
  1658. /**
  1659. * Zero-based row index.
  1660. */
  1661. public int $rowIndex = -1;
  1662. /**
  1663. * One-based row number. This is the human-facing row number.
  1664. */
  1665. public function rowNumber(): ?int { return $this->rowIndex >= 0 ? $this->rowIndex + 1 : null; }
  1666. /**
  1667. * Whether this address has both a definite column and row.
  1668. */
  1669. public function isResolved(): bool { return $this->columnIndex >= 0 && $this->rowIndex >= 0; }
  1670. /**
  1671. * @param int $columnIndex 0-based column index
  1672. * @param int $rowIndex 0-based row index
  1673. * @param bool $isColumnFixed whether the column name is fixed in
  1674. * place during transpositions. Denoted with a `$` in front of the column letters.
  1675. * @param bool $isRowFixed whether the row number is fixed in place
  1676. * during transpositions. Denoted with a `$` in front of the row digits.
  1677. */
  1678. public function __construct(int $columnIndex, int $rowIndex,
  1679. bool $isColumnFixed=false, bool $isRowFixed=false) {
  1680. if (!is_numeric($columnIndex)) {
  1681. throw new Error("columnIndex must be number, got " . gettype($columnIndex));
  1682. }
  1683. if (!is_numeric($rowIndex)) {
  1684. throw new Error("rowIndex must be number, got " . gettype($rowIndex));
  1685. }
  1686. $this->columnIndex = $columnIndex;
  1687. $this->rowIndex = $rowIndex;
  1688. $this->isColumnFixed = $isColumnFixed;
  1689. $this->isRowFixed = $isRowFixed;
  1690. $this->name = self::formatAddress($columnIndex, $rowIndex, $isColumnFixed, $isRowFixed);
  1691. }
  1692. /**
  1693. * Tests if a string is formatted like an address.
  1694. */
  1695. public static function isAddress(string $text): bool {
  1696. return self::fromString($text) != null;
  1697. }
  1698. /**
  1699. * Returns a converted form of this address reference in a formula that has
  1700. * been copied from its original location. In other words, if a formula
  1701. * refers to a cell one to the left and that formula is copied to the next
  1702. * cell down, that copy's reference should point to the cell on the next
  1703. * row as well. Addresses with an absolute column or row (e.g. "A5") will
  1704. * not be altered on that axis.
  1705. *
  1706. * Examples:
  1707. * - C6.transpose(A5, A9) = C10 (A9-A5 = +4 rows, C6 + 4 rows = C10)
  1708. * - C6.transpose(A5, B9) = D10 (B9-A5 = +4 rows +1 cols, C6 + 4 rows + 1
  1709. * col = D10)
  1710. * - C$6.transpose(A5, A9) = C6 (A9-A5 = +4 rows, but row is fixed, so
  1711. * still C6)
  1712. * - B.transpose(A5, A9) = B9 (A9-A4 = +4 rows, B has no row so last row
  1713. * used = B9)
  1714. * - A1.transpose(C3, A1) = null (out of bounds)
  1715. *
  1716. * @param CellAddress $relativeFrom original address of the formula
  1717. * @param CellAddress $relativeTo address where the formula is being
  1718. * repeated
  1719. * @param boolean $resolveToRow whether to fill in a row number if this
  1720. * address doesn't have one
  1721. * @return CellAddress|null resolved address, or `null` if out of bounds
  1722. */
  1723. public function transpose(CellAddress $relativeFrom, CellAddress $relativeTo,
  1724. bool $resolveToRow = true): ?CellAddress {
  1725. if (!$relativeFrom->isResolved() || !$relativeTo->isResolved()) {
  1726. throw new CellEvaluationException("Can only transpose to and from resolved addresses");
  1727. }
  1728. $newColumnIndex = $this->columnIndex;
  1729. if (!$this->isColumnFixed) {
  1730. $columnDelta = $relativeTo->columnIndex - $relativeFrom->columnIndex;
  1731. $newColumnIndex += $columnDelta;
  1732. }
  1733. $newRowIndex = $this->rowIndex;
  1734. if (!$this->isResolved && $resolveToRow) {
  1735. $newRowIndex = $relativeFrom->rowIndex;
  1736. }
  1737. if ($newRowIndex != -1 && !$this->isRowAbsolute) {
  1738. $rowDelta = $relativeTo->rowIndex - $relativeFrom->rowIndex;
  1739. $newRowIndex += $rowDelta;
  1740. }
  1741. if ($newColumnIndex < 0 || $newRowIndex < 0) return null;
  1742. return new CellAddress($newColumnIndex, $newRowIndex);
  1743. }
  1744. public function equals($other): bool {
  1745. if (!($other instanceof CellAddress)) return false;
  1746. return $other->columnIndex == $this->columnIndex && $other->rowIndex == $this->rowIndex;
  1747. }
  1748. public function exactlyEquals($other): bool {
  1749. if (!($other instanceof CellAddress)) return false;
  1750. return $other->name == $this->name;
  1751. }
  1752. public function __toString(): string {
  1753. return $this->name;
  1754. }
  1755. /**
  1756. * Converts column letters (e.g. `A`, `C`, `AA`) to a 0-based column index.
  1757. * Assumes a validated well-formed column letter or else behavior is undefined.
  1758. */
  1759. public static function lettersToColumnIndex(string $letters): int {
  1760. $ACodepoint = ord('A');
  1761. $columnIndex = 0;
  1762. for ($i = mb_strlen($letters) - 1; $i >= 0; $i--) {
  1763. $letterIndex = ord(mb_substr($letters, $i, 1)) - $ACodepoint;
  1764. $columnIndex = $columnIndex * 26 + $letterIndex;
  1765. }
  1766. return $columnIndex;
  1767. }
  1768. /**
  1769. * Converts a column index to column letters (e.g. index 0 = `A`).
  1770. */
  1771. private static function columnIndexToLetters(int $columnIndex): string {
  1772. $letters = '';
  1773. if ($columnIndex >= 0) {
  1774. $ACodepoint = ord('A');
  1775. $remaining = $columnIndex;
  1776. do {
  1777. $letters = chr(ACodepoint + (remaining % 26)) . $letters;
  1778. $remaining = floor($remaining / 26);
  1779. } while ($remaining > 0);
  1780. }
  1781. return $letters;
  1782. }
  1783. private static function formatAddress(int $columnIndex, int $rowIndex,
  1784. bool $isColumnFixed, bool $isRowFixed): string {
  1785. $addr = '';
  1786. if ($isColumnFixed && $columnIndex >= 0) $addr .= '$';
  1787. if ($columnIndex >= 0) $addr .= self::columnIndexToLetters($columnIndex);
  1788. if ($isRowFixed && $rowIndex >= 0) $addr .= '$';
  1789. if ($rowIndex >= 0) $addr .= "${rowIndex + 1}";
  1790. return $addr;
  1791. }
  1792. /**
  1793. * Attempts to convert a cell address string to a `CellAddress`.
  1794. *
  1795. * @param string $address cell address string
  1796. * @param ?CellAddress $relativeTo address to resolve relative
  1797. * addresses against
  1798. * @param boolean $throwIfInvalid whether to throw an error if address
  1799. * is invalid
  1800. * @return ?CellAddress address, if parsable
  1801. * @throws CellEvaluationException if the address is invalid and
  1802. * `$throwIfInvalid` is `true`
  1803. */
  1804. public static function fromString(string $address, ?CellAddress $relativeTo=null,
  1805. bool $throwIfInvalid=false): ?CellAddress {
  1806. if (!mb_eregi('^(\\$?)([A-Z]{1,2}?)((?:\\$(?=[0-9]))?)([0-9]*)$/', $address, $groups)) {
  1807. if ($throwIfInvalid) throw new CellEvaluationException("Bad address \"{$address}\"", '#REF');
  1808. return null;
  1809. }
  1810. $isColumnFixed = ($groups[1] == '$');
  1811. $letters = mb_strtoupper($groups[2]);
  1812. $isRowFixed = ($groups[3] == '$');
  1813. $numbers = $groups[4];
  1814. $columnIndex = $this->lettersToColumnIndex($letters);
  1815. $rowIndex = (mb_strlen($numbers) == 0) ? -1 : intval($numbers) - 1;
  1816. if ($columnIndex < 0 && $relativeTo !== null) $columnIndex = $relativeTo->columnIndex;
  1817. if ($rowIndex < 0 && $relativeTo !== null) $rowIndex = $relativeTo->rowIndex;
  1818. return new CellAddress($columnIndex, $rowIndex, $isColumnFixed, $isRowFixed);
  1819. }
  1820. }
  1821. /**
  1822. * Range of cells addresses. Can be iterated via `cellsIn`.
  1823. */
  1824. class CellAddressRange {
  1825. public bool $isResolved;
  1826. public int $minColumnIndex;
  1827. public int $maxColumnIndex;
  1828. public int $minRowIndex;
  1829. public int $maxRowIndex;
  1830. public string $name;
  1831. /**
  1832. * Creates a rectangular range between two corner cells. They can be in
  1833. * any order. The given cells must either both be resolved or both unresolved.
  1834. *
  1835. * @param CellAddress $fromCell
  1836. * @param CellAddress $toCell
  1837. */
  1838. public function __construct(CellAddress $fromCell, CellAddress $toCell) {
  1839. if ($fromCell->isResolved() != $toCell->isResolved()) {
  1840. throw new CellEvaluationException("Cannot mix resolved and unresolved cell addresses in range: {$fromCell->name} and {$toCell->name}");
  1841. }
  1842. $this->minColumnIndex = min($fromCell->columnIndex, $toCell->columnIndex);
  1843. $this->maxColumnIndex = max($fromCell->columnIndex, $toCell->columnIndex);
  1844. $this->minRowIndex = min($fromCell->rowIndex, $toCell->rowIndex);
  1845. $this->maxRowIndex = max($fromCell->rowIndex, $toCell->rowIndex);
  1846. $this->isResolved = $fromCell->isResolved;
  1847. $this->name = (new CellAddress($this->minColumnIndex, $this->minRowIndex))->name .
  1848. ':' .
  1849. (new CellAddress($this->maxColumnIndex, $this->maxRowIndex))->name;
  1850. }
  1851. /**
  1852. * Creates an iterator for every `CellAddress` in this range within the
  1853. * confines of the given grid's dimensions. Iterates each row in the first
  1854. * column, then each row in the second, etc. Iteration range is inclusive
  1855. * of the min and max extents.
  1856. *
  1857. * Example:
  1858. * ```
  1859. * foreach (range.cellsIn(grid) as $address) {
  1860. * ...
  1861. * }
  1862. * ```
  1863. *
  1864. * @param SpreadsheetGrid $grid
  1865. * @return object iterable object
  1866. */
  1867. public function cellsIn(SpreadsheetGrid $grid): Iterator {
  1868. $min_col = $this->minColumnIndex;
  1869. $max_col = $this->maxColumnIndex;
  1870. $min_row = $this->minRowIndex;
  1871. $max_row = $this->maxRowIndex;
  1872. if ($min_row == -1) {
  1873. $min_row = $grid->getHeaderRowCount();
  1874. }
  1875. if ($max_row == -1) {
  1876. $max_row = $grid->getRowCount() - 1;
  1877. }
  1878. $max_col = min($max_col, $grid->getColumnCount());
  1879. return new class($grid, $min_col, $max_col, $min_row, $max_row) implements Iterator {
  1880. private SpreadsheetGrid $grid;
  1881. private int $min_col;
  1882. private int $max_col;
  1883. private int $min_row;
  1884. private int $max_row;
  1885. private int $col;
  1886. private int $row;
  1887. private ?CellAddress $address = null;
  1888. private ?SpreadsheetCell $cell = null;
  1889. function __construct($grid, $min_col, $max_col, $min_row, $max_row) {
  1890. $this->grid = $grid;
  1891. $this->min_col = $min_col;
  1892. $this->max_col = $max_col;
  1893. $this->min_row = $min_row;
  1894. $this->max_row = $max_row;
  1895. $this->col = $min_col;
  1896. $this->row = $min_row;
  1897. $this->setValues();
  1898. }
  1899. private function setValues() {
  1900. if ($this->col >= $this->min_col && $this->col <= $this->max_col &&
  1901. $this->row >= $this->min_row && $this->row <= $this->max_row) {
  1902. $this->address = new CellAddress($this->col, $this->row);
  1903. $this->cell = $this->grid->getCell($this->address);
  1904. if (!$this->cell) {
  1905. error_log("WARNING: Iterator found no cell at {$this->address->name}");
  1906. }
  1907. } else {
  1908. $this->address = null;
  1909. $this->cell = null;
  1910. }
  1911. }
  1912. private function increment(): void {
  1913. $this->row++;
  1914. if ($this->row > $this->max_row) {
  1915. $this->row = $this->min_row;
  1916. $this->col++;
  1917. }
  1918. $this->setValues();
  1919. }
  1920. function current(): ?SpreadsheetCell {
  1921. return $this->cell;
  1922. }
  1923. function key(): string {
  1924. return $this->address->name;
  1925. }
  1926. function next(): void {
  1927. $this->increment();
  1928. }
  1929. function rewind(): void {
  1930. $this->row = $this->min_row;
  1931. $this->col = $this->min_col;
  1932. $this->setValues();
  1933. }
  1934. function valid(): bool {
  1935. return $this->address != null;
  1936. }
  1937. };
  1938. }
  1939. }
  1940. /**
  1941. * A value in a spreadsheet or calculation.
  1942. */
  1943. class CellValue {
  1944. /**
  1945. * Blank cell. `value` is `null`.
  1946. */
  1947. public const TYPE_BLANK = 'blank';
  1948. /**
  1949. * Currency value. `value` is `number`.
  1950. */
  1951. public const TYPE_CURRENCY = 'currency';
  1952. /**
  1953. * Regular number value. `value` is `number`.
  1954. */
  1955. public const TYPE_NUMBER = 'number';
  1956. /**
  1957. * Percentage. `value` is `number`, represented as a ratio (100% = 1.0).
  1958. */
  1959. public const TYPE_PERCENT = 'percent';
  1960. /**
  1961. * Unaltered text value. `value` is `string`.
  1962. */
  1963. public const TYPE_STRING = 'string';
  1964. /**
  1965. * Boolean. `value` is `boolean`.
  1966. */
  1967. public const TYPE_BOOLEAN = 'boolean';
  1968. /**
  1969. * A formula that has resulted in an error during parsing or evaluation.
  1970. * `value` is `string` error message.
  1971. */
  1972. public const TYPE_ERROR = 'error';
  1973. /**
  1974. * A formula expression. `value` is `string` and includes the leading `=`.
  1975. */
  1976. public const TYPE_FORMULA = 'formula';
  1977. // -- Properties -----
  1978. /**
  1979. * Type of value. One of the `TYPE_` constants.
  1980. */
  1981. public string $type = CellValue::TYPE_STRING;
  1982. /**
  1983. * Number of decimal places shown in the formatted value.
  1984. */
  1985. public int $decimals = 0;
  1986. /**
  1987. * The string shown in the table cell to the user.
  1988. */
  1989. public string $formattedValue = '';
  1990. /**
  1991. * The PHP data value. E.g. a `float` for currency values or an `Exception`
  1992. * for errors.
  1993. */
  1994. public $value = null;
  1995. /**
  1996. * Constructs a cell value explicitly. Values are not validated. Consider
  1997. * using `.fromCellString()` or `.fromValue()` to populate values more
  1998. * intelligently and consistently.
  1999. */
  2000. public function __construct(
  2001. string $formattedValue,
  2002. mixed $value = null,
  2003. string $type = CellValue::TYPE_STRING,
  2004. int $decimals = 0
  2005. ) {
  2006. $this->formattedValue = formattedValue;
  2007. $this->value = value;
  2008. $this->type = type;
  2009. $this->decimals = decimals;
  2010. }
  2011. /**
  2012. * Returns whether this value is a numeric type.
  2013. */
  2014. public function isNumeric(): bool {
  2015. return CellValue::isTypeNumeric($this->type);
  2016. }
  2017. /**
  2018. * Creates a CellValue from formatted table cell contents. Attempts to
  2019. * detect formatted numbers including currency and percentages.
  2020. */
  2021. public static function fromCellString(string $cellString): CellValue {
  2022. $cv = new CellValue($cellString);
  2023. $cv->populateFromCellString($cellString);
  2024. return $cv;
  2025. }
  2026. /**
  2027. * Creates a CellValue from a value. Based off datatype, not string
  2028. * formatting; use `fromCellString` to parse formatted numbers.
  2029. *
  2030. * @param mixed $value
  2031. * @param ?string $type optional forced type
  2032. * @param ?int $decimals optional number of decimal places to format to
  2033. * @return CellValue
  2034. * @throws CellEvaluationException if `$value` is of an unsupported type
  2035. */
  2036. public static function fromValue(mixed $value, ?string $type = null,
  2037. ?int $decimals = null): CellValue {
  2038. if ($value === null) {
  2039. return new CellValue('', null, CellValue::TYPE_BLANK);
  2040. }
  2041. if ($value instanceof Error) {
  2042. if ($value instanceof CellException) {
  2043. return new CellValue($value->errorSymbol, $value->message, CellValue::TYPE_ERROR);
  2044. }
  2045. return new CellValue('#ERROR', $value->message, CellValue::TYPE_ERROR);
  2046. }
  2047. if (is_bool($value)) {
  2048. $formatted = CellValue::formatType($value, CellValue::TYPE_BOOLEAN, 0);
  2049. return new CellValue($formatted, $value, CellValue::TYPE_BOOLEAN);
  2050. }
  2051. if (is_numeric($value)) {
  2052. $resolvedType = $type || CellValue::TYPE_NUMBER;
  2053. $resolvedDecimals = ($decimals !== null) ? $decimals :
  2054. ($resolvedType == CellValue::TYPE_CURRENCY ? 2 :
  2055. CellValue::autodecimals($resolvedType == CellValue::TYPE_PERCENT ?
  2056. $value * 100.0 : $value));
  2057. $formatted = CellValue::formatType($value, $resolvedType, $resolvedDecimals);
  2058. return new CellValue($formatted, $value, $resolvedType, $resolvedDecimals);
  2059. }
  2060. if (!is_string($value)) {
  2061. throw new CellEvaluationException("Value of type " . gettype($value) . "unsupported");
  2062. }
  2063. $trimmed = trim($value);
  2064. if (str_starts_with($trimmed, '=')) {
  2065. return new CellValue($trimmed, $trimmed, CellValue::TYPE_FORMULA);
  2066. }
  2067. return new CellValue($trimmed, $trimmed, CellValue::TYPE_STRING);
  2068. }
  2069. private function populateFromCellString(?string $cellString) {
  2070. $cellString = ($cellString !== null) ? trim($cellString) : null;
  2071. $this->formattedValue = $cellString;
  2072. // blank
  2073. if ($cellString === null || $cellString == '') {
  2074. $this->type = CellValue::TYPE_BLANK;
  2075. $this->value = null;
  2076. return;
  2077. }
  2078. // 'literal
  2079. if (str_starts_with($cellString, "'")) {
  2080. $stripped = trim(mb_substr($cellString, 1));
  2081. $this->type = CellValue::TYPE_STRING;
  2082. $this->formattedValue = $stripped;
  2083. $this->value = $stripped;
  2084. return;
  2085. }
  2086. // =TRUE
  2087. $caps = mb_strtoupper($cellString);
  2088. if ($caps == 'TRUE') {
  2089. $this->type = CellValue::TYPE_BOOLEAN;
  2090. $this->formattedValue = $caps;
  2091. $this->value = true;
  2092. $this->formattedValue = 'TRUE';
  2093. return;
  2094. }
  2095. // =FALSE
  2096. if ($caps == 'FALSE') {
  2097. $this->type = CellValue::TYPE_BOOLEAN;
  2098. $this->formattedValue = $caps;
  2099. $this->value = false;
  2100. $this->formattedValue = 'FALSE';
  2101. return;
  2102. }
  2103. // =A*B
  2104. if (str_starts_with($cellString, '=')) {
  2105. $this->type = CellValue::TYPE_FORMULA;
  2106. $this->value = $cellString;
  2107. return;
  2108. }
  2109. // -$1,234.56
  2110. if (mb_eregi('^([-]?)\\$(-?[0-9,]*\\.)([0-9]+)$', $cellString, $groups)) {
  2111. $sign = $groups[1];
  2112. $dollars = mb_eregi_replace(',', '', $groups[2]);
  2113. $cents = $groups[3];
  2114. $this->type = CellValue::TYPE_CURRENCY;
  2115. $this->decimals = 2;
  2116. $this->value = floatval($sign . $dollars . $cents);
  2117. $this->formattedValue = CellValue::formatCurrency($this->value, $this->decimals);
  2118. return;
  2119. }
  2120. // -$1,234
  2121. if (mb_eregi('^([-]?)\\$(-?[0-9,]+)$', $cellString, $groups)) {
  2122. $sign = $groups[1];
  2123. $dollars = mb_eregi_replace(',', '', $groups[2]);
  2124. $this->type = CellValue::TYPE_CURRENCY;
  2125. $this->decimals = 0;
  2126. $this->value = floatval($sign . $dollars);
  2127. $this->formattedValue = CellValue::formatCurrency($this->value, $this->decimals);
  2128. return;
  2129. }
  2130. // -1,234.56%
  2131. if (mb_eregi('^([-]?[0-9,]*\\.)([0-9,]+)%$', $cellString, $groups)) {
  2132. $wholes = mb_eregi_replace(',', '', $groups[1]);
  2133. $decimals = $groups[2];
  2134. $this->type = CellValue::TYPE_PERCENT;
  2135. $this->decimals = mb_strlen($decimals);
  2136. $this->value = floatval($wholes . $decimals) / 100.0;
  2137. $this->formattedValue = CellValue::formatPercent($this->value, $this->decimals);
  2138. return;
  2139. }
  2140. // -1,234%
  2141. if (mb_eregi('^([-]?[0-9,]+)%$', $cellString, $groups)) {
  2142. $wholes = mb_eregi_replace(',', '', $groups[1]);
  2143. $this->type = CellValue::TYPE_PERCENT;
  2144. $this->decimals = 0;
  2145. $this->value = floatval($wholes) / 100.0;
  2146. $this->formattedValue = CellValue::formatPercent($this->value, $this->decimals);
  2147. return;
  2148. }
  2149. // -1,234.56
  2150. if (mb_eregi('^([-]?[0-9,]*\\.)([0-9]+)$', $cellString, $groups)) {
  2151. $wholes = mb_eregi_replace(',', '', $groups[1]);
  2152. $decimals = $groups[2];
  2153. $this->type = CellValue::TYPE_NUMBER;
  2154. $this->decimals = mb_strlen($decimals);
  2155. $this->value = floatval($wholes . $decimals);
  2156. $this->formattedValue = CellValue::formatNumber($this->value, $this->decimals);
  2157. return;
  2158. }
  2159. // -1,234
  2160. if (mb_eregi('^([-]?[0-9,]+)$', $cellString, $groups)) {
  2161. $wholes = mb_eregi_replace(',', '', $groups[1]);
  2162. $this->type = CellValue::TYPE_NUMBER;
  2163. $this->decimals = 0;
  2164. $this->value = parseFloat($wholes);
  2165. $this->formattedValue = CellValue::formatNumber($this->value, $this->decimals);
  2166. return;
  2167. }
  2168. $this->type = CellValue::TYPE_STRING;
  2169. $this->value = $cellString;
  2170. }
  2171. /**
  2172. * Returns the boolean equivalent of this value if possible.
  2173. */
  2174. public function booleanValue(): ?bool {
  2175. switch ($this->type) {
  2176. case CellValue::TYPE_BLANK:
  2177. return false;
  2178. case CellValue::TYPE_BOOLEAN:
  2179. return $this->value;
  2180. case CellValue::TYPE_CURRENCY:
  2181. case CellValue::TYPE_NUMBER:
  2182. case CellValue::TYPE_PERCENT:
  2183. return $this->value != 0;
  2184. case CellValue::TYPE_ERROR:
  2185. case CellValue::TYPE_FORMULA:
  2186. case CellValue::TYPE_STRING:
  2187. return null;
  2188. }
  2189. }
  2190. /**
  2191. * Returns the numeric value of this value if possible.
  2192. */
  2193. public function numericValue(): ?float {
  2194. switch ($this->type) {
  2195. case CellValue::TYPE_BLANK:
  2196. return 0.0;
  2197. case CellValue::TYPE_BOOLEAN:
  2198. return $this->value ? 1.0 : 0.0;
  2199. case CellValue::TYPE_CURRENCY:
  2200. case CellValue::TYPE_NUMBER:
  2201. case CellValue::TYPE_PERCENT:
  2202. return $this->value;
  2203. case CellValue::TYPE_ERROR:
  2204. case CellValue::TYPE_FORMULA:
  2205. case CellValue::TYPE_STRING:
  2206. return null;
  2207. }
  2208. }
  2209. /**
  2210. * Returns the string value of this value if possible.
  2211. */
  2212. public function stringValue(bool $formatted = false): ?string {
  2213. switch ($this->type) {
  2214. case CellValue::TYPE_BLANK:
  2215. return '';
  2216. case CellValue::TYPE_BOOLEAN:
  2217. return $this->value ? 'TRUE' : 'FALSE';
  2218. case CellValue::TYPE_CURRENCY:
  2219. case CellValue::TYPE_NUMBER:
  2220. case CellValue::TYPE_PERCENT:
  2221. return $formatted ? $this->formattedValue : "${$this->value}";
  2222. case CellValue::TYPE_STRING:
  2223. return $formatted ? $this->formattedValue : $this->value;
  2224. case CellValue::TYPE_ERROR:
  2225. case CellValue::TYPE_FORMULA:
  2226. return null;
  2227. }
  2228. }
  2229. // -- Operations --------------------------------------------------------
  2230. /**
  2231. * Returns the result of this value plus `$b`.
  2232. */
  2233. public function add(CellValue $b): CellValue {
  2234. return self::binaryNumericOperation($this, $b, '+',
  2235. fn($aVal, $bVal) => $aVal + $bVal);
  2236. }
  2237. /**
  2238. * Returns the result of this value minus `$b`.
  2239. */
  2240. public function subtract(CellValue $b) {
  2241. return self::binaryNumericOperation($this, $b, '-',
  2242. fn($aVal, $bVal) => $aVal - $bVal);
  2243. }
  2244. /**
  2245. * Returns the result of this value multiplied by `$b`.
  2246. */
  2247. public function multiply(CellValue $b): CellValue {
  2248. return self::binaryNumericOperation($this, $b, '*',
  2249. fn($aVal, $bVal) => $aVal * $bVal);
  2250. }
  2251. /**
  2252. * Returns the result of this value divided by `$b`.
  2253. *
  2254. * @throws CellEvaluationException on divide by zero
  2255. */
  2256. public function divide(CellValue $b): CellValue {
  2257. return self::binaryNumericOperation($this, $b, '/', function($aVal, $bVal) {
  2258. if ($bVal == 0) throw new CellEvaluationException("Division by zero", '#NAN');
  2259. return $aVal / $bVal;
  2260. });
  2261. }
  2262. /**
  2263. * Returns the result of this value modulo by `$b`.
  2264. *
  2265. * @throws CellEvaluationException on divide by zero
  2266. */
  2267. public function modulo($b) {
  2268. return self::binaryNumericOperation($this, $b, '%', function($aVal, $bVal) {
  2269. if ($bVal == 0) throw new CellEvaluationException("Division by zero", '#NAN');
  2270. return $aVal % $bVal;
  2271. });
  2272. }
  2273. /**
  2274. * Returns the result of whether this value is greater than `$b`.
  2275. */
  2276. public function gt(CellValue $b): CellValue {
  2277. return self::fromValue(CellValue::compare($this, $b) > 0);
  2278. }
  2279. /**
  2280. * Returns the result of whether tihs value is greater than or equal to `$b`.
  2281. */
  2282. public function gte(CellValue $b): CellValue {
  2283. return self::fromValue(CellValue::compare($this, $b) >= 0);
  2284. }
  2285. /**
  2286. * Returns the result of whether this value is less than `$b`.
  2287. */
  2288. public function lt(CellValue $b): CellValue {
  2289. return self::fromValue(CellValue::compare($this, $b) < 0);
  2290. }
  2291. /**
  2292. * Returns the result of whether this value is less than or equal to `$b`.
  2293. */
  2294. public function lte(CellValue $b): CellValue {
  2295. return self::fromValue(CellValue::compare($this, $b) <= 0);
  2296. }
  2297. /**
  2298. * Returns the result of whether this value is equal to `$b`.
  2299. */
  2300. public function eq(CellValue $b): CellValue {
  2301. return self::fromValue(CellValue::compare($this, $b) == 0);
  2302. }
  2303. /**
  2304. * Returns the result of whether this value is unequal to `$b`.
  2305. */
  2306. public function neq(CellValue $b): CellValue {
  2307. return self::fromValue(CellValue::compare($this, $b) != 0);
  2308. }
  2309. /**
  2310. * Returns the boolean not of this value.
  2311. */
  2312. public function not(): CellValue {
  2313. switch ($this->type) {
  2314. case CellValue::TYPE_BLANK:
  2315. return self::fromValue(true);
  2316. case CellValue::TYPE_CURRENCY:
  2317. case CellValue::TYPE_NUMBER:
  2318. case CellValue::TYPE_PERCENT:
  2319. return self::fromValue($this->value == 0);
  2320. case CellValue::TYPE_STRING:
  2321. throw new CellEvaluationException("Cannot perform NOT on string");
  2322. case CellValue::TYPE_BOOLEAN:
  2323. return self::fromValue(!$this->value);
  2324. case CellValue::TYPE_ERROR:
  2325. throw $this->value;
  2326. case CellValue::TYPE_FORMULA:
  2327. throw new CellEvaluationException("Cannot perform NOT on expression");
  2328. }
  2329. }
  2330. /**
  2331. * Returns the string representation of a value concatenated to the string
  2332. * representation of this value.
  2333. */
  2334. public function concatenate(CellValue $b): CellValue {
  2335. $s1 = $this->stringValue(true);
  2336. $s2 = $b->stringValue(true);
  2337. if ($s1 === null || $s2 === null) {
  2338. throw new CellEvaluationException("Concatenation requires string arguments");
  2339. }
  2340. return self::fromValue("{$s1}{$s2}");
  2341. }
  2342. /**
  2343. * Helper to resolve two numeric arguments and perform an operation on them.
  2344. *
  2345. * @param CellValue $a operand A
  2346. * @param CellValue $b operand B
  2347. * @param string $op operator
  2348. * @param function $fn takes two `float` arguments and returns a `float` result
  2349. * @return CellValue result
  2350. * @throws CellEvaluationException
  2351. */
  2352. public static function binaryNumericOperation(CellValue $a, CellValue $b,
  2353. string $op, callable $fn): CellValue {
  2354. $ops = self::resolveNumericOperands($a, $b, $op);
  2355. $aNum = $ops[0];
  2356. $bNum = $ops[1];
  2357. $type = $ops[2];
  2358. $result = $fn($aNum, $bNum);
  2359. return self::fromValue($result, $type);
  2360. }
  2361. /**
  2362. * Determines what the result of a calculation with two operands should
  2363. * look like. Returns a tuple array of the A float value, the B float value,
  2364. * and the type of the result.
  2365. *
  2366. * @param CellValue $a operand A
  2367. * @param CellValue $b operand B
  2368. * @param string $op operator symbol
  2369. * @return array 3-element tuple array with A number value, B number value,
  2370. * and result type string
  2371. * @throws CellEvaluationException if types are incompatible for numeric operations
  2372. */
  2373. private static function resolveNumericOperands(CellValue $a, CellValue $b, string $op): array {
  2374. if ($a->type == $this->TYPE_ERROR) throw $a->value;
  2375. if ($b->type == $this->TYPE_ERROR) throw $b->value;
  2376. if ($a->type == $this->TYPE_STRING || $b->type == $this->TYPE_STRING) {
  2377. throw new CellEvaluationException("Cannot perform math on text values");
  2378. }
  2379. if ($a->type == $this->TYPE_BLANK) {
  2380. if ($b->type == $this->TYPE_BLANK) {
  2381. return [ 0, 0, $this->TYPE_NUMBER, 0 ];
  2382. }
  2383. return [ 0, $b->value, $b->type ];
  2384. } elseif ($b->type == $this->TYPE_BLANK) {
  2385. return [ $a->value, 0, $a->type ];
  2386. }
  2387. $isMultOrDiv = ($op == '*' || $op == '/' || $op == '%');
  2388. if ($a->type == $b->type) {
  2389. return [ $a->value, $b->value, $a->type ];
  2390. }
  2391. switch ($a->type . $b->type) {
  2392. case $this->TYPE_CURRENCY . $this->TYPE_NUMBER:
  2393. case $this->TYPE_CURRENCY . $this->TYPE_PERCENT:
  2394. return [ $a->value, $b->value, $this->TYPE_CURRENCY ];
  2395. case $this->TYPE_PERCENT . $this->TYPE_CURRENCY:
  2396. return [ $a->value, $b->value,
  2397. $isMultOrDiv ? $this->TYPE_CURRENCY : $this->TYPE_PERCENT ];
  2398. case $this->TYPE_PERCENT . $this->TYPE_NUMBER:
  2399. return [ $a->value, $b->value,
  2400. $isMultOrDiv ? $this->TYPE_NUMBER : $this->TYPE_PERCENT ];
  2401. case $this->TYPE_NUMBER . $this->TYPE_CURRENCY:
  2402. return [ $a->value, $b->value, $b->type ];
  2403. case $this->TYPE_NUMBER . $this->TYPE_PERCENT:
  2404. return [ $a->value, $b->value,
  2405. $isMultOrDiv ? $this->TYPE_NUMBER : $b->type ];
  2406. case $this->TYPE_BOOLEAN . $this->TYPE_CURRENCY:
  2407. case $this->TYPE_BOOLEAN . $this->TYPE_NUMBER:
  2408. case $this->TYPE_BOOLEAN . $this->TYPE_PERCENT:
  2409. return [ $a->value ? 1 : 0, $b->value, $b->type ];
  2410. case $this->TYPE_CURRENCY . $this->TYPE_BOOLEAN:
  2411. case $this->TYPE_NUMBER . $this->TYPE_BOOLEAN:
  2412. case $this->TYPE_PERCENT . $this->TYPE_BOOLEAN:
  2413. return [ $a->value, $b->value ? 1 : 0, $a->type ];
  2414. }
  2415. throw new CellEvaluationException(`Unhandled operand types "${a.type}" and "${b.type}"`);
  2416. }
  2417. /**
  2418. * Performs a comparison of two values.
  2419. *
  2420. * @param CellValue $a
  2421. * @param CellValue $b
  2422. * @return int `-1`, `0`, or `1` if a < b, a == b, or a > b, respectively
  2423. */
  2424. private static function compare(CellValue $a, CellValue $b): int {
  2425. $args = self::resolveComparableArguments($a, $b);
  2426. $valueA = $args[0];
  2427. $valueB = $args[1];
  2428. if (is_string($valueA)) {
  2429. return strcasecmp($valueA, $valueB);
  2430. } else {
  2431. if ($valueA < $valueB) return -1;
  2432. if ($valueA > $valueB) return 1;
  2433. return 0;
  2434. }
  2435. }
  2436. /**
  2437. * @param CellValue $a
  2438. * @param CellValue $b
  2439. * @return array two comparable values (strings or floats)
  2440. * @throws CellEvaluationException if values are formulas
  2441. * @throws CellException if `$a` or `$b` is of type `TYPE_ERROR`
  2442. */
  2443. private static function resolveComparableArguments(CellValue $a, CellValue $b): array {
  2444. if ($a->type == CellValue::TYPE_ERROR) throw $a->value;
  2445. if ($b->type == CellValue::TYPE_ERROR) throw $b->value;
  2446. if ($a->type == CellValue::TYPE_FORMULA) throw new CellEvaluationException("Can't compare formula values");
  2447. if ($b->type == CellValue::TYPE_FORMULA) throw new CellEvaluationException("Can't compare formula values");
  2448. $aNumValue = $a->value;
  2449. $bNumValue = $b->value;
  2450. $aStrValue = "{$a->value}";
  2451. $bStrValue = "{$b->value}";
  2452. switch ($a->type) {
  2453. case CellValue::TYPE_BLANK:
  2454. $aNumValue = 0;
  2455. $aStrValue = '';
  2456. break;
  2457. case CellValue::TYPE_BOOLEAN:
  2458. $aNumValue = ($aNumValue) ? 1 : 0;
  2459. break;
  2460. }
  2461. switch ($b->type) {
  2462. case CellValue::TYPE_BLANK:
  2463. $bNumValue = 0;
  2464. $bStrValue = '';
  2465. break;
  2466. case CellValue::TYPE_BOOLEAN:
  2467. $bNumValue = ($bNumValue) ? 1 : 0;
  2468. break;
  2469. }
  2470. if ($a->type == CellValue::TYPE_STRING || $b->type == CellValue::TYPE_STRING) {
  2471. return [ $aStrValue, $bStrValue ];
  2472. }
  2473. return [ $aNumValue, $bNumValue ];
  2474. }
  2475. /**
  2476. * Returns a formatted string for the given raw value, value type, and
  2477. * decimal places.
  2478. */
  2479. public static function formatType(mixed $value, string $type, int $decimals): string {
  2480. switch ($type) {
  2481. case CellValue::TYPE_BLANK: return '';
  2482. case CellValue::TYPE_CURRENCY: return CellValue::formatCurrency($value, $decimals);
  2483. case CellValue::TYPE_NUMBER: return CellValue::formatNumber($value, $decimals);
  2484. case CellValue::TYPE_PERCENT: return CellValue::formatPercent($value, $decimals);
  2485. case CellValue::TYPE_BOOLEAN: return $value ? 'TRUE' : 'FALSE';
  2486. case CellValue::TYPE_STRING: return "{$value}";
  2487. case CellValue::TYPE_FORMULA: return "{$value}";
  2488. }
  2489. }
  2490. private static function formatNumber(float|int $value, int $decimals): string {
  2491. return number_format($value, $decimals);
  2492. }
  2493. private static function formatCurrency(float|int $dollars, int $decimals): string {
  2494. $s = number_format($dollars, $decimals);
  2495. if (str_starts_with($s, '-')) {
  2496. return '-$' . mb_substr($s, 1);
  2497. }
  2498. return '$' . s;
  2499. }
  2500. private static function formatPercent(float|int $value, int $decimals): string {
  2501. $dec = $value * 100.0;
  2502. return number_format($dec, $decimals) . '%';
  2503. }
  2504. /**
  2505. * Determines a good number of decimal places to format a value to.
  2506. */
  2507. private static function autodecimals(mixed $value, int $maxDigits = 6): int {
  2508. if ($value instanceof CellValue) {
  2509. return CellValue::autodecimals($value->value);
  2510. }
  2511. if (is_numeric($value)) {
  2512. $s = number_format($value, $maxDigits);
  2513. if (strpos($s, '.') === false) return 0;
  2514. $fraction = explode('.', $s)[1];
  2515. return min($maxDigits, mb_strlen($fraction));
  2516. }
  2517. return 0;
  2518. }
  2519. /**
  2520. * Tests if a type is numeric.
  2521. */
  2522. public static function isTypeNumeric(string $type): bool {
  2523. return $type == CellValue::TYPE_NUMBER ||
  2524. $type == CellValue::TYPE_PERCENT ||
  2525. $type == CellValue::TYPE_CURRENCY ||
  2526. $type == CellValue::TYPE_BOOLEAN;
  2527. }
  2528. public function __toString(): string {
  2529. return "<CellValue type={$this->type} value={$this->value} \"{$this->formattedValue}\">";
  2530. }
  2531. }
  2532. /**
  2533. * A rectangular grid of `SpreadsheetCell`s representing a spreadsheet.
  2534. * Agnostic of presentation.
  2535. */
  2536. class SpreadsheetGrid {
  2537. /**
  2538. * Indexed by column then row.
  2539. * @type {SpreadsheetCell[][]}
  2540. */
  2541. public array $cells;
  2542. public int $columnCount;
  2543. public int $rowCount;
  2544. public function __construct(int $columnCount, int $rowCount) {
  2545. $this->columnCount = $columnCount;
  2546. $this->rowCount = $rowCount;
  2547. $this->cells = [];
  2548. for ($c = 0; $c < $columnCount; $c++) {
  2549. $column = [];
  2550. for ($r = 0; $r < $rowCount; $r++) {
  2551. array_push($column, new SpreadsheetCell());
  2552. }
  2553. array_push($this->cells, $column);
  2554. }
  2555. }
  2556. /**
  2557. * @param CellAddress $address
  2558. * @return SpreadsheetCell $cell
  2559. * @throws CellEvaluationException if the address it out of bounds
  2560. */
  2561. public function cellAt(CellAddress $address): SpreadsheetCell {
  2562. $c = $address->columnIndex; $r = $address->rowIndex;
  2563. if ($c < 0 || $c >= sizeof($this->cells)) throw new CellEvaluationException("Unresolved cell address {$address->name}", '#REF');
  2564. $col = $this->cells[$c];
  2565. if ($r < 0 || $r >= sizeof($col)) throw new CellEvaluationException("Unresolved cell address {$address->name}", '#REF');
  2566. return $col[$r];
  2567. }
  2568. /**
  2569. * Returns the original value at the given address.
  2570. */
  2571. public function valueAt(CellAddress $address): ?CellValue {
  2572. return $this->cellAt($address)->originalValue;
  2573. }
  2574. /**
  2575. * Returns the computed value at the given address.
  2576. */
  2577. public function outputValueAt(CellAddress $address): ?CellValue {
  2578. return $this->cellAt($address)->outputValue;
  2579. }
  2580. }
  2581. /**
  2582. * One cell in a spreadsheet grid. Has an `originalValue` to start and an
  2583. * evaluated `outputValue` after population by a `CellExpressionSet` computation.
  2584. */
  2585. class SpreadsheetCell {
  2586. public CellValue $originalValue;
  2587. public ?CellValue $outputValue = null;
  2588. /**
  2589. * Whether `outputValue` is the result of a formula evaluation.
  2590. */
  2591. public bool $isCalculated = false;
  2592. public ?CellExpression $parsedExpression = null;
  2593. public function __construct() {
  2594. $this->originalValue = new CellValue('', null, CellValue::TYPE_BLANK, 0);
  2595. }
  2596. public function resolvedValue(): CellValue { return $this->outputValue ?? $this->originalValue; }
  2597. }
  2598. /**
  2599. * Integration with Markdown. Adding this block reader to a parser will run a
  2600. * post-process step on any tables in the document tree. Must be used with
  2601. * `MDTableReader`. Tables without at least one formula will not be altered.
  2602. */
  2603. class MDSpreadsheetReader extends MDReader {
  2604. public function postProcess(MDState $state, array &$nodes) {
  2605. foreach ($nodes as $node) {
  2606. if ($node instanceof MDTableNode) {
  2607. $this->processTable($node, $state);
  2608. }
  2609. }
  2610. }
  2611. private function processTable(MDTableNode $tableNode, MDState $state) {
  2612. // Measure table
  2613. $rowCount = sizeof($tableNode->bodyRows());
  2614. $columnCount = 0;
  2615. foreach ($tableNode->bodyRows() as $row) {
  2616. $columnCount = max($columnCount, sizeof($row->children));
  2617. }
  2618. // Create and populate grid
  2619. $grid = new SpreadsheetGrid($columnCount, $rowCount);
  2620. for ($c = 0; $c < $columnCount; $c++) {
  2621. for ($r = 0; $r < $rowCount; $r++) {
  2622. $cellNode = $tableNode->bodyRows()[$r]->children[$c];
  2623. if ($cellNode === null) continue;
  2624. $cellText = $cellNode->toPlaintext($state);
  2625. $gridCell = $grid->cells[$c][$r];
  2626. $gridCell->originalValue = CellValue::fromCellString($cellText);
  2627. }
  2628. }
  2629. // Calculate
  2630. $expressions = new CellExpressionSet($grid);
  2631. $expressions->calculateCells();
  2632. // See if anything was calculated. If not, don't mess with table.
  2633. $isCalculated = false;
  2634. for ($c = 0; $c < $columnCount && !$isCalculated; $c++) {
  2635. for ($r = 0; $r < $rowCount; $r++) {
  2636. if ($grid->cells[$c][$r]->isCalculated) {
  2637. $isCalculated = true;
  2638. break;
  2639. }
  2640. }
  2641. }
  2642. if (!$isCalculated) return;
  2643. // Copy results back to table
  2644. for ($c = 0; $c < $columnCount; $c++) {
  2645. for ($r = 0; $r < $rowCount; $r++) {
  2646. $cellNode = $tableNode->bodyRows[$r]->children[$c];
  2647. if ($cellNode === null) continue;
  2648. $gridCell = $grid->cells[$c][$r];
  2649. $gridValue = $gridCell->outputValue;
  2650. $cellText = $gridValue->formattedValue;
  2651. $cellNode->children = [ new MDTextNode($cellText) ];
  2652. if ($gridCell->isCalculated) {
  2653. $cellNode->addClass('calculated');
  2654. }
  2655. $cellNode->addClass("spreadsheet-type-{$gridValue->type}");
  2656. if ($gridValue->type == CellValue::TYPE_ERROR) {
  2657. $cellNode->attributes['title'] = $gridValue->value;
  2658. }
  2659. $gridNumber = $gridValue->numericValue();
  2660. if ($gridNumber !== null) {
  2661. $cellNode->attributes['data-numeric-value'] = "{$gridNumber}";
  2662. }
  2663. $gridString = $gridValue->stringValue(false);
  2664. if ($gridString !== null) {
  2665. $cellNode->attributes['data-string-value'] = $gridString;
  2666. }
  2667. }
  2668. }
  2669. }
  2670. }
  2671. ?>