Michal Čihař - Announcing SimpleMath

Announcing SimpleMath

For quite some time we've been relying on using eval() function in phpMyAdmin in two places. One of them is gettext library, where we have to evaluate plural forms and second of them is MySQL configuration advisor, which does it's suggestions based on text file (the original idea was to make this file shared with other tools, but it never really worked out).

Using eval() in PHP is something what is better to avoid, but we were using it on data we ship, so it was considered safe. On the other side, there are hostings which deny using eval() altogether (as many of exploits are using this function), so it's better to avoid that. I've been looking for options for replacing eval() in motranslator (library we use for handling Gettext MO files) for quite some time, but never found library which would support all operators needed in Gettext plural formulas.

Yesterday I finally came to conclusion that writing own library to do this is best approach. This way it can in future extended to work with Advisor as well. Also we can make it pretty lightweight without additional dependencies (what was problem in some existing libraries I've found).

To make the story short, this is how SimpleMath was born. As of now, it has grown to version 0.2 (you can use Packagist to install it). For now it's really simple and it can be probably confused by various strange inputs, but it seems for work pretty well for our case. Currently supported features:

  • Supports basic arithmetic operations +, -, *, /, %
  • Supports parenthesis
  • Supports right associative ternary operator
  • Supports comparison operators ==, !=, >, <, >=, <=
  • Supports basic logical operations &&, ||
  • Supports variables (either PHP style $a or simple n)

Maybe it will be usable for somebody else as well, but even if not, it's the way for us to get rid of using eval() in our codebase.


It seems that Symfony ExpressionLanguage Component is doing pretty much same, but more flexible and faster, so SimpleMath will be probably dead soon and we will switch to using Symphony component.


Nemo wrote on Oct. 13, 2016, 10:49 a.m.

Note that a PHP library for standard plural rules exists: https://www.mediawiki.org/wiki/CLDRPluralRuleParser

Flavius Nopcea wrote on Oct. 13, 2016, 11:50 a.m.

Maybe not reinvent the wheel and use


wrote on Oct. 13, 2016, 2:11 p.m.

@Nemo: We're targeting more things than just plural in the long term.

@Flavius: When evaluating it I understood that it evaluates expressions as in PHP, what is problem with ternary operator as it behaves differently in PHP than elsewhere. But I can check again if that is really the case.

Jakub Wilk wrote on Oct. 14, 2016, 1:12 p.m.

@Nemo: CLDR plural rules have completely different syntax than Gettext ones.