Separating simple rules from PHP code

At the moment, I have PHP that sets a single variable based on the value of other independent variables in a linear format, for example:

$result = 0;

if ($var1 == 'X') {
  $result += 10;
}

if ($var2 < 10) {
  $result += 15;
}
elseif ($var2 > 50) {
  $result -= 50;
}

// more of the same

However, I would like these rules to be expressed in a less programmable way, mainly because someone who does not know how to program can add / edit rules, and also because I might want to use the same rules in a Python or Perl script, without having to save copies in multiple languages. I could write my own simple language (because of a better word) and a parser, but I would prefer to use the existing solution, as this saves work and increases the likelihood that other people will know how to write rules in it.

/ ?

+3
4

, /. ( , ) . .

, , .

+1

PHP-.

$var1 == 'X': +10
$var2 < 10:   +15
$var2 > 50:   -50

PHP Tokenizer, PHP-. PHP.

, TokenStream ( )

<?php
    $code =<<<'EOC'
$var1 == 'X': +10

$var2 < 10:   +15
$var2 > 50:   -50
EOC;

    require '../tokenstream/src/TokenStream.php';

    $tokenStream = new TokenStream('<?php ' . $code);
    $code = '';
    foreach ($tokenStream as $i => $token) {
        if ($token->is(T_OPEN_TAG)) {
            $code .= '<?php $result = 0;' . PHP_EOL . 'if (';
        }
        elseif ($token->is(T_WHITESPACE) && preg_match("[\r\n]", $token->content)) {
            $code .= ';' . $token . 'if (';
        }
        elseif ($token->is(T_COLON)) {
            $code .= ') $result += ';
        }
        else {
            $code .= $token;
        }
    }
    $code .= ';';

    echo '<pre>', htmlspecialchars($code), '</pre>';

. . , ;)

Script :

<?php $result = 0;
if ($var1 == 'X') $result +=  +10;

if ($var2 < 10) $result +=    +15;
if ($var2 > 50) $result +=    -50;
+1

.

0

Source: https://habr.com/ru/post/1765652/


All Articles