PHP and Javascript implementations of a simple markdown parser
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

spreadsheet.php 92KB

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