Skip to content

Instantly share code, notes, and snippets.

@ksn135
Created May 28, 2017 14:58
Show Gist options
  • Save ksn135/e969887f2fa4e538d7944c449adaa75b to your computer and use it in GitHub Desktop.
Save ksn135/e969887f2fa4e538d7944c449adaa75b to your computer and use it in GitHub Desktop.
Простой калькулятор с переменными
<?php
/*
* This file is part of the <censored> informational system package.
*
* (c) Serg N. Kalachev <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace AppBundle\Util;
/**
* Class provided by http://stackoverflow.com/users/555222/clarkk
* in this answer http://stackoverflow.com/a/27077376
*/
class FieldCalculator {
public static function callback1($m) {
return self::calculate($m[1]);
}
public static function callback2($n,$m) {
$o=$m[0];
$m[0]=' ';
return $o=='+' ? $n+$m : ($o=='-' ? $n-$m : ($o=='*' ? $n*$m : $n/$m));
}
public static function calculate($s){
while ($s != ($t = preg_replace_callback('/\(([^()]*)\)/','self::callback1',$s))) $s=$t;
preg_match_all('![-+/*].*?[\d.]+!', "+$s", $m);
return array_reduce($m[0], 'self::callback2');
}
public static function resolve_vars_in_string($formula, array $values)
{
preg_match_all('/\$([a-zA-Z0-9]+)/', $formula, $out, PREG_PATTERN_ORDER);
foreach(array_unique($out[1]) as $variable){
if (!isset($values[$variable])) {
throw new \LogicException("Unexpected variable '$variable' in formula '$formula'");
}
$formula=str_replace('$'.$variable, $values[$variable], $formula);
}
return $formula;
}
}
<?php
use AppBundle\Util\FieldCalculator;
$formula = '$a * $b * 21';
$params = ['a' => 4, 'b' => 0.5];
$formula = FieldCalculator::resolve_vars_in_string($formula, $params);
echo FieldCalculator::calculate($formula); // 42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment