PHP and Javascript implementations of a simple markdown parser
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928
  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 = round($val->value * $divider) / $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_replace($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 = $this->minColumnIndex;
  1893. $maxCol = $this->maxColumnIndex;
  1894. $minRow = $this->minRowIndex;
  1895. $maxRow = $this->maxRowIndex;
  1896. if ($minRow === -1) {
  1897. $minRow = 0;
  1898. }
  1899. if ($maxRow === -1) {
  1900. $maxRow = $grid->rowCount - 1;
  1901. }
  1902. $maxCol = min($maxCol, $grid->columnCount);
  1903. return new class($grid, $minCol, $maxCol, $minRow, $maxRow) implements Iterator {
  1904. private SpreadsheetGrid $grid;
  1905. private int $minCol;
  1906. private int $maxCol;
  1907. private int $minRow;
  1908. private int $maxRow;
  1909. private int $col;
  1910. private int $row;
  1911. private ?CellAddress $address = null;
  1912. private ?SpreadsheetCell $cell = null;
  1913. function __construct($grid, $minCol, $maxCol, $minRow, $maxRow) {
  1914. $this->grid = $grid;
  1915. $this->minCol = $minCol;
  1916. $this->maxCol = $maxCol;
  1917. $this->minRow = $minRow;
  1918. $this->maxRow = $maxRow;
  1919. $this->col = $minCol;
  1920. $this->row = $minRow;
  1921. $this->setValues();
  1922. }
  1923. private function setValues() {
  1924. if ($this->col >= $this->minCol && $this->col <= $this->maxCol &&
  1925. $this->row >= $this->minRow && $this->row <= $this->maxRow) {
  1926. $this->address = new CellAddress($this->col, $this->row);
  1927. $this->cell = $this->grid->cellAt($this->address);
  1928. if (!$this->cell) {
  1929. error_log("WARNING: Iterator found no cell at {$this->address->name}");
  1930. }
  1931. } else {
  1932. $this->address = null;
  1933. $this->cell = null;
  1934. }
  1935. }
  1936. private function increment(): void {
  1937. $this->row++;
  1938. if ($this->row > $this->maxRow) {
  1939. $this->row = $this->minRow;
  1940. $this->col++;
  1941. }
  1942. $this->setValues();
  1943. }
  1944. function current(): ?SpreadsheetCell {
  1945. return $this->cell;
  1946. }
  1947. function key(): string {
  1948. return $this->address->name;
  1949. }
  1950. function next(): void {
  1951. $this->increment();
  1952. }
  1953. function rewind(): void {
  1954. $this->row = $this->minRow;
  1955. $this->col = $this->minCol;
  1956. $this->setValues();
  1957. }
  1958. function valid(): bool {
  1959. return $this->address !== null;
  1960. }
  1961. };
  1962. }
  1963. }
  1964. /**
  1965. * A value in a spreadsheet or calculation.
  1966. */
  1967. class CellValue {
  1968. /**
  1969. * Blank cell. `$value` is `null`.
  1970. */
  1971. public const TYPE_BLANK = 'blank';
  1972. /**
  1973. * Currency value. `$value` is `float`.
  1974. */
  1975. public const TYPE_CURRENCY = 'currency';
  1976. /**
  1977. * Regular number value. `$value` is `float`.
  1978. */
  1979. public const TYPE_NUMBER = 'number';
  1980. /**
  1981. * Percentage. `$value` is `float`, represented as a ratio (100% = 1.0).
  1982. */
  1983. public const TYPE_PERCENT = 'percent';
  1984. /**
  1985. * Unaltered text value. `$value` is `string`.
  1986. */
  1987. public const TYPE_STRING = 'string';
  1988. /**
  1989. * Boolean. `$value` is `bool`.
  1990. */
  1991. public const TYPE_BOOLEAN = 'boolean';
  1992. /**
  1993. * A formula that has resulted in an error during parsing or evaluation.
  1994. * `$value` is `string` error message.
  1995. */
  1996. public const TYPE_ERROR = 'error';
  1997. /**
  1998. * A formula expression. `$value` is `string` and includes the leading `=`.
  1999. */
  2000. public const TYPE_FORMULA = 'formula';
  2001. // -- Properties -----
  2002. /**
  2003. * Type of value. One of the `TYPE_` constants.
  2004. */
  2005. public string $type = CellValue::TYPE_STRING;
  2006. /**
  2007. * Number of decimal places shown in the formatted value.
  2008. */
  2009. public int $decimals = 0;
  2010. /**
  2011. * The string shown in the table cell to the user.
  2012. */
  2013. public string $formattedValue = '';
  2014. /**
  2015. * The PHP data value. E.g. a `float` for currency values or an `Exception`
  2016. * for errors.
  2017. */
  2018. public $value = null;
  2019. /**
  2020. * Constructs a cell value explicitly. Values are not validated. Consider
  2021. * using `.fromCellString()` or `.fromValue()` to populate values more
  2022. * intelligently and consistently.
  2023. */
  2024. public function __construct(
  2025. string $formattedValue,
  2026. mixed $value = null,
  2027. string $type = CellValue::TYPE_STRING,
  2028. int $decimals = 0
  2029. ) {
  2030. $this->formattedValue = $formattedValue;
  2031. $this->value = $value;
  2032. $this->type = $type;
  2033. $this->decimals = $decimals;
  2034. }
  2035. /**
  2036. * Returns whether this value is a numeric type.
  2037. */
  2038. public function isNumeric(): bool {
  2039. return CellValue::isTypeNumeric($this->type);
  2040. }
  2041. /**
  2042. * Creates a CellValue from formatted table cell contents. Attempts to
  2043. * detect formatted numbers including currency and percentages.
  2044. */
  2045. public static function fromCellString(string $cellString): CellValue {
  2046. $cv = new CellValue($cellString);
  2047. $cv->populateFromCellString($cellString);
  2048. return $cv;
  2049. }
  2050. /**
  2051. * Creates a CellValue from a value. Based off datatype, not string
  2052. * formatting; use `fromCellString` to parse formatted numbers.
  2053. *
  2054. * @param mixed $value
  2055. * @param ?string $type optional forced type
  2056. * @param ?int $decimals optional number of decimal places to format to
  2057. * @return CellValue
  2058. * @throws CellEvaluationException if `$value` is of an unsupported type
  2059. */
  2060. public static function fromValue(mixed $value, ?string $type = null,
  2061. ?int $decimals = null): CellValue {
  2062. if ($value === null) {
  2063. return new CellValue('', null, CellValue::TYPE_BLANK);
  2064. }
  2065. if ($value instanceof Error) {
  2066. if ($value instanceof CellException) {
  2067. return new CellValue($value->errorSymbol, $value->getMessage(), CellValue::TYPE_ERROR);
  2068. }
  2069. return new CellValue('#ERROR', $value->getMessage(), CellValue::TYPE_ERROR);
  2070. }
  2071. if (is_bool($value)) {
  2072. $formatted = CellValue::formatType($value, CellValue::TYPE_BOOLEAN, 0);
  2073. return new CellValue($formatted, $value, CellValue::TYPE_BOOLEAN);
  2074. }
  2075. if (is_numeric($value)) {
  2076. $resolvedType = $type ?? CellValue::TYPE_NUMBER;
  2077. $resolvedDecimals = ($decimals !== null) ? $decimals :
  2078. ($resolvedType === CellValue::TYPE_CURRENCY ? 2 :
  2079. CellValue::autodecimals($resolvedType === CellValue::TYPE_PERCENT ?
  2080. $value * 100.0 : $value));
  2081. $formatted = CellValue::formatType($value, $resolvedType, $resolvedDecimals);
  2082. return new CellValue($formatted, $value, $resolvedType, $resolvedDecimals);
  2083. }
  2084. if (!is_string($value)) {
  2085. throw new CellEvaluationException("Value of type " . gettype($value) . "unsupported");
  2086. }
  2087. $trimmed = trim($value);
  2088. if (str_starts_with($trimmed, '=')) {
  2089. return new CellValue($trimmed, $trimmed, CellValue::TYPE_FORMULA);
  2090. }
  2091. return new CellValue($trimmed, $trimmed, CellValue::TYPE_STRING);
  2092. }
  2093. private function populateFromCellString(?string $cellString) {
  2094. $cellString = ($cellString !== null) ? trim($cellString) : null;
  2095. $this->formattedValue = $cellString;
  2096. // blank
  2097. if ($cellString === null || $cellString === '') {
  2098. $this->type = CellValue::TYPE_BLANK;
  2099. $this->value = null;
  2100. return;
  2101. }
  2102. // 'literal
  2103. if (str_starts_with($cellString, "'")) {
  2104. $stripped = trim(mb_substr($cellString, 1));
  2105. $this->type = CellValue::TYPE_STRING;
  2106. $this->formattedValue = $stripped;
  2107. $this->value = $stripped;
  2108. return;
  2109. }
  2110. // =TRUE
  2111. $caps = mb_strtoupper($cellString);
  2112. if ($caps === 'TRUE') {
  2113. $this->type = CellValue::TYPE_BOOLEAN;
  2114. $this->formattedValue = $caps;
  2115. $this->value = true;
  2116. $this->formattedValue = 'TRUE';
  2117. return;
  2118. }
  2119. // =FALSE
  2120. if ($caps === 'FALSE') {
  2121. $this->type = CellValue::TYPE_BOOLEAN;
  2122. $this->formattedValue = $caps;
  2123. $this->value = false;
  2124. $this->formattedValue = 'FALSE';
  2125. return;
  2126. }
  2127. // =A*B
  2128. if (str_starts_with($cellString, '=')) {
  2129. $this->type = CellValue::TYPE_FORMULA;
  2130. $this->value = $cellString;
  2131. return;
  2132. }
  2133. // -$1,234.56
  2134. if (mb_eregi('^([-]?)\\$(-?[0-9,]*\\.)([0-9]+)$', $cellString, $groups)) {
  2135. $sign = $groups[1];
  2136. $dollars = mb_eregi_replace(',', '', $groups[2]);
  2137. $cents = $groups[3];
  2138. $this->type = CellValue::TYPE_CURRENCY;
  2139. $this->decimals = 2;
  2140. $this->value = floatval($sign . $dollars . $cents);
  2141. $this->formattedValue = CellValue::formatCurrency($this->value, $this->decimals);
  2142. return;
  2143. }
  2144. // -$1,234
  2145. if (mb_eregi('^([-]?)\\$(-?[0-9,]+)$', $cellString, $groups)) {
  2146. $sign = $groups[1];
  2147. $dollars = mb_eregi_replace(',', '', $groups[2]);
  2148. $this->type = CellValue::TYPE_CURRENCY;
  2149. $this->decimals = 0;
  2150. $this->value = floatval($sign . $dollars);
  2151. $this->formattedValue = CellValue::formatCurrency($this->value, $this->decimals);
  2152. return;
  2153. }
  2154. // -1,234.56%
  2155. if (mb_eregi('^([-]?[0-9,]*\\.)([0-9,]+)%$', $cellString, $groups)) {
  2156. $wholes = mb_eregi_replace(',', '', $groups[1]);
  2157. $decimals = $groups[2];
  2158. $this->type = CellValue::TYPE_PERCENT;
  2159. $this->decimals = mb_strlen($decimals);
  2160. $this->value = floatval($wholes . $decimals) / 100.0;
  2161. $this->formattedValue = CellValue::formatPercent($this->value, $this->decimals);
  2162. return;
  2163. }
  2164. // -1,234%
  2165. if (mb_eregi('^([-]?[0-9,]+)%$', $cellString, $groups)) {
  2166. $wholes = mb_eregi_replace(',', '', $groups[1]);
  2167. $this->type = CellValue::TYPE_PERCENT;
  2168. $this->decimals = 0;
  2169. $this->value = floatval($wholes) / 100.0;
  2170. $this->formattedValue = CellValue::formatPercent($this->value, $this->decimals);
  2171. return;
  2172. }
  2173. // -1,234.56
  2174. if (mb_eregi('^([-]?[0-9,]*\\.)([0-9]+)$', $cellString, $groups)) {
  2175. $wholes = mb_eregi_replace(',', '', $groups[1]);
  2176. $decimals = $groups[2];
  2177. $this->type = CellValue::TYPE_NUMBER;
  2178. $this->decimals = mb_strlen($decimals);
  2179. $this->value = floatval($wholes . $decimals);
  2180. $this->formattedValue = CellValue::formatNumber($this->value, $this->decimals);
  2181. return;
  2182. }
  2183. // -1,234
  2184. if (mb_eregi('^([-]?[0-9,]+)$', $cellString, $groups)) {
  2185. $wholes = mb_eregi_replace(',', '', $groups[1]);
  2186. $this->type = CellValue::TYPE_NUMBER;
  2187. $this->decimals = 0;
  2188. $this->value = floatval($wholes);
  2189. $this->formattedValue = CellValue::formatNumber($this->value, $this->decimals);
  2190. return;
  2191. }
  2192. $this->type = CellValue::TYPE_STRING;
  2193. $this->value = $cellString;
  2194. }
  2195. /**
  2196. * Returns the boolean equivalent of this value if possible.
  2197. */
  2198. public function booleanValue(): ?bool {
  2199. switch ($this->type) {
  2200. case CellValue::TYPE_BLANK:
  2201. return false;
  2202. case CellValue::TYPE_BOOLEAN:
  2203. return $this->value;
  2204. case CellValue::TYPE_CURRENCY:
  2205. case CellValue::TYPE_NUMBER:
  2206. case CellValue::TYPE_PERCENT:
  2207. return $this->value !== 0;
  2208. case CellValue::TYPE_ERROR:
  2209. case CellValue::TYPE_FORMULA:
  2210. case CellValue::TYPE_STRING:
  2211. return null;
  2212. }
  2213. }
  2214. /**
  2215. * Returns the numeric value of this value if possible.
  2216. */
  2217. public function numericValue(): ?float {
  2218. switch ($this->type) {
  2219. case CellValue::TYPE_BLANK:
  2220. return 0.0;
  2221. case CellValue::TYPE_BOOLEAN:
  2222. return $this->value ? 1.0 : 0.0;
  2223. case CellValue::TYPE_CURRENCY:
  2224. case CellValue::TYPE_NUMBER:
  2225. case CellValue::TYPE_PERCENT:
  2226. return $this->value;
  2227. case CellValue::TYPE_ERROR:
  2228. case CellValue::TYPE_FORMULA:
  2229. case CellValue::TYPE_STRING:
  2230. return null;
  2231. }
  2232. }
  2233. /**
  2234. * Returns the string value of this value if possible.
  2235. */
  2236. public function stringValue(bool $formatted = false): ?string {
  2237. switch ($this->type) {
  2238. case CellValue::TYPE_BLANK:
  2239. return '';
  2240. case CellValue::TYPE_BOOLEAN:
  2241. return $this->value ? 'TRUE' : 'FALSE';
  2242. case CellValue::TYPE_CURRENCY:
  2243. case CellValue::TYPE_NUMBER:
  2244. case CellValue::TYPE_PERCENT:
  2245. return $formatted ? $this->formattedValue : "{$this->value}";
  2246. case CellValue::TYPE_STRING:
  2247. return $formatted ? $this->formattedValue : $this->value;
  2248. case CellValue::TYPE_ERROR:
  2249. case CellValue::TYPE_FORMULA:
  2250. return null;
  2251. }
  2252. }
  2253. // -- Operations --------------------------------------------------------
  2254. /**
  2255. * Returns the result of this value plus `$b`.
  2256. */
  2257. public function add(CellValue $b): CellValue {
  2258. return self::binaryNumericOperation($this, $b, '+',
  2259. fn($aVal, $bVal) => $aVal + $bVal);
  2260. }
  2261. /**
  2262. * Returns the result of this value minus `$b`.
  2263. */
  2264. public function subtract(CellValue $b) {
  2265. return self::binaryNumericOperation($this, $b, '-',
  2266. fn($aVal, $bVal) => $aVal - $bVal);
  2267. }
  2268. /**
  2269. * Returns the result of this value multiplied by `$b`.
  2270. */
  2271. public function multiply(CellValue $b): CellValue {
  2272. return self::binaryNumericOperation($this, $b, '*',
  2273. fn($aVal, $bVal) => $aVal * $bVal);
  2274. }
  2275. /**
  2276. * Returns the result of this value divided by `$b`.
  2277. *
  2278. * @throws CellEvaluationException on divide by zero
  2279. */
  2280. public function divide(CellValue $b): CellValue {
  2281. return self::binaryNumericOperation($this, $b, '/', function($aVal, $bVal) {
  2282. if ($bVal === 0) throw new CellEvaluationException("Division by zero", '#NAN');
  2283. return $aVal / $bVal;
  2284. });
  2285. }
  2286. /**
  2287. * Returns the result of this value modulo by `$b`.
  2288. *
  2289. * @throws CellEvaluationException on divide by zero
  2290. */
  2291. public function modulo($b) {
  2292. return self::binaryNumericOperation($this, $b, '%', function($aVal, $bVal) {
  2293. if ($bVal === 0) throw new CellEvaluationException("Division by zero", '#NAN');
  2294. return $aVal % $bVal;
  2295. });
  2296. }
  2297. /**
  2298. * Returns the result of whether this value is greater than `$b`.
  2299. */
  2300. public function gt(CellValue $b): CellValue {
  2301. return self::fromValue(CellValue::compare($this, $b) > 0);
  2302. }
  2303. /**
  2304. * Returns the result of whether tihs value is greater than or equal to `$b`.
  2305. */
  2306. public function gte(CellValue $b): CellValue {
  2307. return self::fromValue(CellValue::compare($this, $b) >= 0);
  2308. }
  2309. /**
  2310. * Returns the result of whether this value is less than `$b`.
  2311. */
  2312. public function lt(CellValue $b): CellValue {
  2313. return self::fromValue(CellValue::compare($this, $b) < 0);
  2314. }
  2315. /**
  2316. * Returns the result of whether this value is less than or equal to `$b`.
  2317. */
  2318. public function lte(CellValue $b): CellValue {
  2319. return self::fromValue(CellValue::compare($this, $b) <= 0);
  2320. }
  2321. /**
  2322. * Returns the result of whether this value is equal to `$b`.
  2323. */
  2324. public function eq(CellValue $b): CellValue {
  2325. return self::fromValue(CellValue::compare($this, $b) === 0);
  2326. }
  2327. /**
  2328. * Returns the result of whether this value is unequal to `$b`.
  2329. */
  2330. public function neq(CellValue $b): CellValue {
  2331. return self::fromValue(CellValue::compare($this, $b) !== 0);
  2332. }
  2333. /**
  2334. * Returns the boolean not of this value.
  2335. */
  2336. public function not(): CellValue {
  2337. switch ($this->type) {
  2338. case CellValue::TYPE_BLANK:
  2339. return self::fromValue(true);
  2340. case CellValue::TYPE_CURRENCY:
  2341. case CellValue::TYPE_NUMBER:
  2342. case CellValue::TYPE_PERCENT:
  2343. return self::fromValue($this->value === 0);
  2344. case CellValue::TYPE_STRING:
  2345. throw new CellEvaluationException("Cannot perform NOT on string");
  2346. case CellValue::TYPE_BOOLEAN:
  2347. return self::fromValue(!$this->value);
  2348. case CellValue::TYPE_ERROR:
  2349. throw $this->value;
  2350. case CellValue::TYPE_FORMULA:
  2351. throw new CellEvaluationException("Cannot perform NOT on expression");
  2352. }
  2353. }
  2354. /**
  2355. * Returns the string representation of a value concatenated to the string
  2356. * representation of this value.
  2357. */
  2358. public function concatenate(CellValue $b): CellValue {
  2359. $s1 = $this->stringValue(true);
  2360. $s2 = $b->stringValue(true);
  2361. if ($s1 === null || $s2 === null) {
  2362. throw new CellEvaluationException("Concatenation requires string arguments");
  2363. }
  2364. return self::fromValue("{$s1}{$s2}");
  2365. }
  2366. /**
  2367. * Helper to resolve two numeric arguments and perform an operation on them.
  2368. *
  2369. * @param CellValue $a operand A
  2370. * @param CellValue $b operand B
  2371. * @param string $op operator
  2372. * @param function $fn takes two `float` arguments and returns a `float` result
  2373. * @return CellValue result
  2374. * @throws CellEvaluationException
  2375. */
  2376. public static function binaryNumericOperation(CellValue $a, CellValue $b,
  2377. string $op, callable $fn): CellValue {
  2378. $ops = self::resolveNumericOperands($a, $b, $op);
  2379. $aNum = $ops[0];
  2380. $bNum = $ops[1];
  2381. $type = $ops[2];
  2382. $result = $fn($aNum, $bNum);
  2383. return self::fromValue($result, $type);
  2384. }
  2385. /**
  2386. * Determines what the result of a calculation with two operands should
  2387. * look like. Returns a tuple array of the A float value, the B float value,
  2388. * and the type of the result.
  2389. *
  2390. * @param CellValue $a operand A
  2391. * @param CellValue $b operand B
  2392. * @param string $op operator symbol
  2393. * @return array 3-element tuple array with A float value, B float value,
  2394. * and result type string
  2395. * @throws CellEvaluationException if types are incompatible for numeric operations
  2396. */
  2397. private static function resolveNumericOperands(CellValue $a, CellValue $b, string $op): array {
  2398. if ($a->type === self::TYPE_ERROR) throw $a->value;
  2399. if ($b->type === self::TYPE_ERROR) throw $b->value;
  2400. if ($a->type === self::TYPE_STRING || $b->type === self::TYPE_STRING) {
  2401. throw new CellEvaluationException("Cannot perform math on text values");
  2402. }
  2403. if ($a->type === self::TYPE_BLANK) {
  2404. if ($b->type === self::TYPE_BLANK) {
  2405. return [ 0, 0, self::TYPE_NUMBER, 0 ];
  2406. }
  2407. return [ 0, $b->value, $b->type ];
  2408. } elseif ($b->type === self::TYPE_BLANK) {
  2409. return [ $a->value, 0, $a->type ];
  2410. }
  2411. $isMultOrDiv = ($op === '*' || $op === '/' || $op === '%');
  2412. if ($a->type === $b->type) {
  2413. return [ $a->value, $b->value, $a->type ];
  2414. }
  2415. switch ($a->type . $b->type) {
  2416. case self::TYPE_CURRENCY . self::TYPE_NUMBER:
  2417. case self::TYPE_CURRENCY . self::TYPE_PERCENT:
  2418. return [ $a->value, $b->value, self::TYPE_CURRENCY ];
  2419. case self::TYPE_PERCENT . self::TYPE_CURRENCY:
  2420. return [ $a->value, $b->value,
  2421. $isMultOrDiv ? self::TYPE_CURRENCY : self::TYPE_PERCENT ];
  2422. case self::TYPE_PERCENT . self::TYPE_NUMBER:
  2423. return [ $a->value, $b->value,
  2424. $isMultOrDiv ? self::TYPE_NUMBER : self::TYPE_PERCENT ];
  2425. case self::TYPE_NUMBER . self::TYPE_CURRENCY:
  2426. return [ $a->value, $b->value, $b->type ];
  2427. case self::TYPE_NUMBER . self::TYPE_PERCENT:
  2428. return [ $a->value, $b->value,
  2429. $isMultOrDiv ? self::TYPE_NUMBER : $b->type ];
  2430. case self::TYPE_BOOLEAN . self::TYPE_CURRENCY:
  2431. case self::TYPE_BOOLEAN . self::TYPE_NUMBER:
  2432. case self::TYPE_BOOLEAN . self::TYPE_PERCENT:
  2433. return [ $a->value ? 1 : 0, $b->value, $b->type ];
  2434. case self::TYPE_CURRENCY . self::TYPE_BOOLEAN:
  2435. case self::TYPE_NUMBER . self::TYPE_BOOLEAN:
  2436. case self::TYPE_PERCENT . self::TYPE_BOOLEAN:
  2437. return [ $a->value, $b->value ? 1 : 0, $a->type ];
  2438. }
  2439. throw new CellEvaluationException("Unhandled operand types \"{$a->type}\" and \"{$b->type}\"");
  2440. }
  2441. /**
  2442. * Performs a comparison of two values.
  2443. *
  2444. * @param CellValue $a
  2445. * @param CellValue $b
  2446. * @return int `-1`, `0`, or `1` if a < b, a == b, or a > b, respectively
  2447. */
  2448. private static function compare(CellValue $a, CellValue $b): int {
  2449. $args = self::resolveComparableArguments($a, $b);
  2450. $valueA = $args[0];
  2451. $valueB = $args[1];
  2452. if (is_string($valueA)) {
  2453. return strcasecmp($valueA, $valueB);
  2454. } else {
  2455. if ($valueA < $valueB) return -1;
  2456. if ($valueA > $valueB) return 1;
  2457. return 0;
  2458. }
  2459. }
  2460. /**
  2461. * @param CellValue $a
  2462. * @param CellValue $b
  2463. * @return array two comparable values (strings or floats)
  2464. * @throws CellEvaluationException if values are formulas
  2465. * @throws CellException if `$a` or `$b` is of type `TYPE_ERROR`
  2466. */
  2467. private static function resolveComparableArguments(CellValue $a, CellValue $b): array {
  2468. if ($a->type === CellValue::TYPE_ERROR) throw $a->value;
  2469. if ($b->type === CellValue::TYPE_ERROR) throw $b->value;
  2470. if ($a->type === CellValue::TYPE_FORMULA) throw new CellEvaluationException("Can't compare formula values");
  2471. if ($b->type === CellValue::TYPE_FORMULA) throw new CellEvaluationException("Can't compare formula values");
  2472. $aNumValue = $a->value;
  2473. $bNumValue = $b->value;
  2474. $aStrValue = "{$a->value}";
  2475. $bStrValue = "{$b->value}";
  2476. switch ($a->type) {
  2477. case CellValue::TYPE_BLANK:
  2478. $aNumValue = 0;
  2479. $aStrValue = '';
  2480. break;
  2481. case CellValue::TYPE_BOOLEAN:
  2482. $aNumValue = ($aNumValue) ? 1 : 0;
  2483. break;
  2484. }
  2485. switch ($b->type) {
  2486. case CellValue::TYPE_BLANK:
  2487. $bNumValue = 0;
  2488. $bStrValue = '';
  2489. break;
  2490. case CellValue::TYPE_BOOLEAN:
  2491. $bNumValue = ($bNumValue) ? 1 : 0;
  2492. break;
  2493. }
  2494. if ($a->type === CellValue::TYPE_STRING || $b->type === CellValue::TYPE_STRING) {
  2495. return [ $aStrValue, $bStrValue ];
  2496. }
  2497. return [ $aNumValue, $bNumValue ];
  2498. }
  2499. /**
  2500. * Returns a formatted string for the given raw value, value type, and
  2501. * decimal places.
  2502. */
  2503. public static function formatType(mixed $value, string $type, int $decimals): string {
  2504. switch ($type) {
  2505. case CellValue::TYPE_BLANK: return '';
  2506. case CellValue::TYPE_CURRENCY: return CellValue::formatCurrency($value, $decimals);
  2507. case CellValue::TYPE_NUMBER: return CellValue::formatNumber($value, $decimals);
  2508. case CellValue::TYPE_PERCENT: return CellValue::formatPercent($value, $decimals);
  2509. case CellValue::TYPE_BOOLEAN: return $value ? 'TRUE' : 'FALSE';
  2510. case CellValue::TYPE_STRING: return "{$value}";
  2511. case CellValue::TYPE_FORMULA: return "{$value}";
  2512. default: throw new CellException("Cannot format value of type {$type}");
  2513. }
  2514. }
  2515. private static function formatNumber(float|int $value, int $decimals): string {
  2516. return number_format($value, $decimals);
  2517. }
  2518. private static function formatCurrency(float|int $dollars, int $decimals): string {
  2519. $s = number_format($dollars, $decimals);
  2520. if (str_starts_with($s, '-')) {
  2521. return '-$' . mb_substr($s, 1);
  2522. }
  2523. return '$' . $s;
  2524. }
  2525. private static function formatPercent(float|int $value, int $decimals): string {
  2526. $dec = $value * 100.0;
  2527. return number_format($dec, $decimals) . '%';
  2528. }
  2529. /**
  2530. * Determines a good number of decimal places to format a value to.
  2531. */
  2532. private static function autodecimals(mixed $value, int $maxDigits = 6): int {
  2533. if ($value instanceof CellValue) {
  2534. return CellValue::autodecimals($value->value);
  2535. }
  2536. if (is_numeric($value)) {
  2537. $s = number_format($value, $maxDigits);
  2538. if (strpos($s, '.') === false) return 0;
  2539. $fraction = explode('.', $s)[1];
  2540. $fraction = rtrim($fraction, '0');
  2541. return min($maxDigits, mb_strlen($fraction));
  2542. }
  2543. return 0;
  2544. }
  2545. /**
  2546. * Tests if a type is numeric.
  2547. */
  2548. public static function isTypeNumeric(string $type): bool {
  2549. return $type === CellValue::TYPE_NUMBER ||
  2550. $type === CellValue::TYPE_PERCENT ||
  2551. $type === CellValue::TYPE_CURRENCY ||
  2552. $type === CellValue::TYPE_BOOLEAN;
  2553. }
  2554. public function __toString(): string {
  2555. return "<CellValue type={$this->type} value={$this->value} \"{$this->formattedValue}\">";
  2556. }
  2557. }
  2558. /**
  2559. * A rectangular grid of `SpreadsheetCell`s representing a spreadsheet.
  2560. * Agnostic of presentation.
  2561. */
  2562. class SpreadsheetGrid {
  2563. /**
  2564. * Indexed by column then row.
  2565. * @type {SpreadsheetCell[][]}
  2566. */
  2567. public array $cells;
  2568. public int $columnCount;
  2569. public int $rowCount;
  2570. public function __construct(int $columnCount, int $rowCount) {
  2571. $this->columnCount = $columnCount;
  2572. $this->rowCount = $rowCount;
  2573. $this->cells = [];
  2574. for ($c = 0; $c < $columnCount; $c++) {
  2575. $column = [];
  2576. for ($r = 0; $r < $rowCount; $r++) {
  2577. array_push($column, new SpreadsheetCell());
  2578. }
  2579. array_push($this->cells, $column);
  2580. }
  2581. }
  2582. /**
  2583. * @param CellAddress $address
  2584. * @return SpreadsheetCell $cell
  2585. * @throws CellEvaluationException if the address it out of bounds
  2586. */
  2587. public function cellAt(CellAddress $address): SpreadsheetCell {
  2588. $c = $address->columnIndex; $r = $address->rowIndex;
  2589. if ($c < 0 || $c >= count($this->cells)) throw new CellEvaluationException("Unresolved cell address {$address->name}", '#REF');
  2590. $col = $this->cells[$c];
  2591. if ($r < 0 || $r >= count($col)) throw new CellEvaluationException("Unresolved cell address {$address->name}", '#REF');
  2592. return $col[$r];
  2593. }
  2594. /**
  2595. * Returns the original value at the given address.
  2596. */
  2597. public function valueAt(CellAddress $address): ?CellValue {
  2598. return $this->cellAt($address)->originalValue;
  2599. }
  2600. /**
  2601. * Returns the computed value at the given address.
  2602. */
  2603. public function outputValueAt(CellAddress $address): ?CellValue {
  2604. return $this->cellAt($address)->outputValue;
  2605. }
  2606. }
  2607. /**
  2608. * One cell in a spreadsheet grid. Has an `originalValue` to start and an
  2609. * evaluated `outputValue` after population by a `CellExpressionSet` computation.
  2610. */
  2611. class SpreadsheetCell {
  2612. public CellValue $originalValue;
  2613. public ?CellValue $outputValue = null;
  2614. /**
  2615. * Whether `outputValue` is the result of a formula evaluation.
  2616. */
  2617. public bool $isCalculated = false;
  2618. public ?CellExpression $parsedExpression = null;
  2619. public function __construct() {
  2620. $this->originalValue = new CellValue('', null, CellValue::TYPE_BLANK, 0);
  2621. }
  2622. public function resolvedValue(): CellValue { return $this->outputValue ?? $this->originalValue; }
  2623. }
  2624. /**
  2625. * Integration with Markdown. Adding this block reader to a parser will run a
  2626. * post-process step on any tables in the document tree. Must be used with
  2627. * `MDTableReader`. Tables without at least one formula will not be altered.
  2628. */
  2629. class MDSpreadsheetReader extends MDReader {
  2630. public function preProcess(MDState $state) {
  2631. foreach ($state->readersByBlockPriority as $reader) {
  2632. if ($reader instanceof MDTableReader) {
  2633. $reader->preferFormulas = true;
  2634. }
  2635. }
  2636. }
  2637. public function postProcess(MDState $state, array &$nodes) {
  2638. foreach ($nodes as $node) {
  2639. if ($node instanceof MDTableNode) {
  2640. $this->processTable($node, $state);
  2641. }
  2642. }
  2643. }
  2644. private function processTable(MDTableNode $tableNode, MDState $state) {
  2645. // Measure table
  2646. $rowCount = count($tableNode->bodyRows());
  2647. $columnCount = 0;
  2648. foreach ($tableNode->bodyRows() as $row) {
  2649. $columnCount = max($columnCount, count($row->children));
  2650. }
  2651. // Create and populate grid
  2652. $grid = new SpreadsheetGrid($columnCount, $rowCount);
  2653. for ($c = 0; $c < $columnCount; $c++) {
  2654. for ($r = 0; $r < $rowCount; $r++) {
  2655. $cellNode = $tableNode->bodyCellAt($c, $r);
  2656. if ($cellNode === null) continue;
  2657. $cellText = $cellNode->toPlaintext($state);
  2658. $gridCell = $grid->cells[$c][$r];
  2659. $gridCell->originalValue = CellValue::fromCellString($cellText);
  2660. }
  2661. }
  2662. // Calculate
  2663. $expressions = new CellExpressionSet($grid);
  2664. $expressions->calculateCells();
  2665. // See if anything was calculated. If not, don't mess with table.
  2666. $isCalculated = false;
  2667. for ($c = 0; $c < $columnCount && !$isCalculated; $c++) {
  2668. for ($r = 0; $r < $rowCount; $r++) {
  2669. if ($grid->cellAt(new CellAddress($c, $r))->isCalculated) {
  2670. $isCalculated = true;
  2671. break;
  2672. }
  2673. }
  2674. }
  2675. if (!$isCalculated) return;
  2676. // Copy results back to table
  2677. for ($c = 0; $c < $columnCount; $c++) {
  2678. for ($r = 0; $r < $rowCount; $r++) {
  2679. $cellNode = $tableNode->bodyCellAt($c, $r);
  2680. $gridCell = $grid->cellAt(new CellAddress($c, $r));
  2681. if ($cellNode === null || $gridCell === null) continue;
  2682. $this->populateCell($cellNode, $gridCell, $state, $c, $r);
  2683. }
  2684. }
  2685. }
  2686. /**
  2687. * @param MDTableCellNode $cellNode
  2688. * @param SpreadsheetCell $gridCell
  2689. * @param MDState $state
  2690. * @param int $c column index
  2691. * @param int $r row index
  2692. */
  2693. private function populateCell(MDTableCellNode $cellNode,
  2694. SpreadsheetCell $gridCell, MDState $state, int $c, int $r) {
  2695. $gridValue = $gridCell->outputValue;
  2696. if ($gridValue === null) return;
  2697. $oldCellText = trim($cellNode->toPlaintext($state));
  2698. $cellText = $gridValue->formattedValue;
  2699. if ($cellText != $oldCellText) {
  2700. // Try to insert the text into any nested whole-value formatting nodes
  2701. // if possible
  2702. if (!$this->findTextNode($cellNode, $oldCellText, $cellText)) {
  2703. // Contents contain mixed formatting. We'll have to just replace
  2704. // the whole thing.
  2705. $cellNode->children = [ new MDTextNode($cellText) ];
  2706. }
  2707. }
  2708. if ($gridCell->isCalculated) {
  2709. $cellNode->addClass('calculated');
  2710. }
  2711. $cellNode->addClass("spreadsheet-type-{$gridValue->type}");
  2712. if ($gridValue->type == CellValue::TYPE_ERROR) {
  2713. $cellNode->attributes['title'] = $gridValue->value;
  2714. }
  2715. $gridNumber = $gridValue->numericValue();
  2716. if ($gridNumber !== null) {
  2717. $cellNode->attributes['data-numeric-value'] = "{$gridNumber}";
  2718. }
  2719. $gridString = $gridValue->stringValue(false);
  2720. if ($gridString !== null) {
  2721. $cellNode->attributes['data-string-value'] = $gridString;
  2722. }
  2723. }
  2724. private function findTextNode(MDNode $startNode, string $expectedText, string $newText): bool {
  2725. if ($startNode instanceof MDTextNode) {
  2726. if (trim($startNode->text) === trim($expectedText)) {
  2727. $startNode->text = $newText;
  2728. return true;
  2729. }
  2730. }
  2731. foreach ($startNode->children as $child) {
  2732. if ($this->findTextNode($child, $expectedText, $newText)) return true;
  2733. }
  2734. return false;
  2735. }
  2736. }
  2737. ?>