PHP and Javascript implementations of a simple markdown parser
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

spreadsheet.php 95KB

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