定制 xakepehok/expression-executor 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

xakepehok/expression-executor

Composer 安装命令:

composer require xakepehok/expression-executor

包简介

Expression executor, which allow to implement domain-specific language

README 文档

README

Expression executor, which allows to implement domain-specific language. This lib doesn’t contain any implemented operators or functions. Its only a framework, which allows you to build your own domain-specific language for expressions, with any functions, operators and typing system.

You can define your own operator, functions and variables. For example, you want to calc/execute expressions like:

MIN(5, 10.5) + NUMBER_OF_DAY(year: "2019", month: "01", day: "20") + PI * {{VARIABLE}} + ((-2) + 2.5) * 2

In example above

  • MIN and NUMBER_OF_DAY - functions
  • {{VARIABLE}} - variable
  • PI - syntax user-defined constant (for example, you can define TRUE, FALSE and NULL constants)
  • + and * - operators
  • "5", "10", "2019" - strings in double-quotes
  • 5, 10.5, (-2), 2.5, 2 - int/float as is, but negative values should be wrapped in brackets

Also, it support arrays and boolean logic like:

("HELLO" IN ["HELLO", "WORLD"]) && (10 IN [2+2, 3+3, 5+5, "string here"])

where

  • ["HELLO", "WORLD"] - array of strings
  • [2+2, 3+3, 5+5, "string here"] - mixed array of integers and strings
  • IN - operator, that check is array contain value or not
  • && - logic operator "and"

Installation:

composer require xakepehok/expression-executor

Usage

In order to calc/execute expressions above you need to define those functions, operators and values

MIN():

<?php
class MinFunction implements \XAKEPEHOK\ExpressionExecutor\FunctionInterface 
{

    public function getName(): string
    {
        return 'MIN';
    }

    public function execute(array $arguments, array $context)
    {
        return min($arguments);
    }
}

NUMBER_OF_DAY():

<?php
class NumberOfDayFunction implements \XAKEPEHOK\ExpressionExecutor\FunctionInterface 
{

    public function getName(): string
    {
        return 'NUMBER_OF_DAY';
    }

    public function execute(array $arguments, array $context)
    {
        $year = $arguments['year'] ?? ($arguments[0] ?? null);
        $month = $arguments['month'] ?? ($arguments[1] ?? null);
        $day = $arguments['day'] ?? ($arguments[2] ?? null);
        
        if ($year === null || $month === null || $day === null) {
            throw new \XAKEPEHOK\ExpressionExecutor\Exceptions\FunctionException('Arguments error');
        }
        
        return date('N', strtotime("{$year}-{$month}-{$day}"));
    }
}

+ operator:

<?php
class PlusOperator implements \XAKEPEHOK\ExpressionExecutor\OperatorInterface 
{
    
    public function operator() : string
    {
        return '+';    
    }
    
    /**
    * Custom integer priority value. For example, for "+" it can be 1, for "*" it can be 2
    * @return int
    */
    public function priority() : int
    {
        return 1;
    }
    
    public function execute($leftOperand, $rightOperand, array $context)
    {
        return $leftOperand + $rightOperand;
    }    
}

* operator:

<?php
class MultiplyOperator implements \XAKEPEHOK\ExpressionExecutor\OperatorInterface 
{
    
    public function operator() : string
    {
        return '*';    
    }
    
    /**
    * Custom integer priority value. For example, for "+" it can be 1, for "*" it can be 2
    * @return int
    */
    public function priority() : int
    {
        return 2;
    }
    
    public function execute($leftOperand, $rightOperand, array $context)
    {
        return $leftOperand * $rightOperand;
    }    
}

IN operator:

<?php
class InOperator implements \XAKEPEHOK\ExpressionExecutor\OperatorInterface 
{
    
    public function operator() : string
    {
        return 'IN';    
    }
    
    /**
    * Custom integer priority value. For example, for "+" it can be 1, for "*" it can be 2
    * @return int
    */
    public function priority() : int
    {
        return 1;
    }
    
    public function execute($leftOperand, $rightOperand, array $context)
    {
        return in_array($leftOperand, $rightOperand, true);
    }    
}

&& operator:

<?php
class AndOperator implements \XAKEPEHOK\ExpressionExecutor\OperatorInterface 
{
    
    public function operator() : string
    {
        return '&&';    
    }
    
    /**
    * Custom integer priority value. For example, for "+" it can be 1, for "*" it can be 2
    * @return int
    */
    public function priority() : int
    {
        return 1;
    }
    
    public function execute($leftOperand, $rightOperand, array $context)
    {
        return $leftOperand && $rightOperand;
    }    
}

Create executor instance:

<?php
$executor = new \XAKEPEHOK\ExpressionExecutor\Executor(
    [new MinFunction(), new NumberOfDayFunction()],
    [new PlusOperator(), new MultiplyOperator(), new InOperator(), new AndOperator()],
    function ($name, array $context) {
        $vars = [
            'VARIABLE' => 10,
            'CONTEXT.VALUE' => $context['value'],
        ];
        return $vars[$name];
    },
    ['PI' => 3.14]
);

//And simply execute our expression 
$result_1 = $executor->execute('MIN(5, 10.5) + NUMBER_OF_DAY(year: "2019", month: "01", day: "20") + PI * {{VARIABLE}} + ((-2) + 2.5) * 2');

$result_2 = $executor->execute('("HELLO" IN ["HELLO", "WORLD"]) && (10 IN [2+2, 3+3, 5+5, "string here"])');

Features

  • Its safe. No eval()
  • Executor can return and work with any types of data. All types checking and manipulating should be implemented in your classes (functions and operators)
  • String arguments support escaped double quotes, for example "My name is \"Timur\""
  • Functions accept any count of arguments (you can limit in function body by exceptions)
  • Functions arguments can be named NUMBER_OF_DAY(year: "2019", month: "01", day: "20") and unnamed NUMBER_OF_DAY("2019", "01", "20"), but not combined
  • Function arguments can be strings, numbers, variables, constants, other functions result and any expressions
  • You can pass context (any common data as array) as second param for execute() method. Context will be passed to functions, operators and variables callable
  • Use brackets (2 + 2) * 2 for priority
  • Use brackets for negative numbers, such as (-1), (-1.2)
  • You can implement any operator, such as >, >=, <, <= and any what you want and desire

See ExecutorTest.php for more examples.

Differences from analogues

  • https://symfony.com/doc/current/components/expression_language.html - great symfony component for expressions, but it is impossible to override logic of any built-in operators and also impossible use your own strict type system. Only one way to extend - define your own function
  • https://github.com/NeonXP/MathExecutor - good math expressions calculator with user-defined operators and functions, but it is also impossible to use your own strict type system. For example, you can't do something like Datetime - Datetime (with type saving)

xakepehok/expression-executor 适用场景与选型建议

xakepehok/expression-executor 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 4k 次下载、GitHub Stars 达 4, 最近一次更新时间为 2019 年 01 月 20 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「DSL」 「expression」 「executor」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 xakepehok/expression-executor 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 xakepehok/expression-executor 我们能提供哪些服务?
定制开发 / 二次开发

基于 xakepehok/expression-executor 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 4k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 4
  • 点击次数: 5
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 4
  • Watchers: 1
  • Forks: 2
  • 开发语言: PHP

其他信息

  • 授权协议: BSD-3-Clause
  • 更新时间: 2019-01-20