PHP and Javascript implementations of a simple markdown parser
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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