jwadhams / json-logic-php

使用JSON序列化构建复杂比较和布尔运算规则,并在PHP中执行

1.5.1 2024-07-09 15:20 UTC

README

此解析器接受 JsonLogic 规则并在PHP中执行它们。

JsonLogic 格式旨在允许您在前后端代码(无论语言差异)之间共享规则(逻辑),甚至可以将逻辑与数据库中的记录一起存储。JsonLogic 在 JsonLogic.com 上有详细的文档,包括每个 支持的操作 的示例,以及一个可以在浏览器中尝试规则的地方 try out rules in your browser

相同的格式也可以通过库 json-logic-js 在JavaScript中执行

示例

关于类型的说明

这是一个设计为以JSON格式传输和存储的格式。因此,将规则概念化为JSON是有意义的。

用JSON表示,JsonLogic规则始终是一个键,后面跟着一个值数组。

{"==" : ["apples", "apples"]}

PHP 有一种方法可以将关联数组表示为字面量,没有对象等效项,因此所有这些示例都写成如果 JsonLogic 规则使用 json_decode$assoc 参数设置为 true 解码,例如。

json_decode('{"==" : ["apples", "apples"]}', true);
// ["==" => ["apples", "apples"]]

库将愉快地接受关联数组或对象

$rule = '{"==":["apples", "apples"]}';

//Decode the JSON string to an array, and evaluate it.
JWadhams\JsonLogic::apply( json_decode($rule, true) );
// true

//Decode the JSON string to an object, and evaluate it.
JWadhams\JsonLogic::apply( json_decode($rule, false) );
// true

简单

JWadhams\JsonLogic::apply( [ "==" => [1, 1] ] );
// true

这是一个简单的测试,相当于 1 == 1。关于格式的一些说明

  1. 运算符始终位于 "键" 位置。每个 JsonLogic 规则只有一个键。
  2. 值通常是数组。
  3. 每个值可以是字符串、数字、布尔值、数组或 null

复合

这里我们开始嵌套规则。

JWadhams\JsonLogic::apply(
	[ "and" => [
		[ ">" => [3,1] ],
		[ "<" => [1,3] ]
	] ]
);
// true

在算符优先的语言(如PHP)中,这可以写成

( (3 > 1) and (1 < 3) )

数据驱动

显然,如果这些规则只能接受静态字面量数据,它们就不会很有趣。通常,会使用规则对象和数据对象调用 JsonLogic::apply。您可以使用 var 运算符来获取数据对象的属性

JWadhams\JsonLogic::apply(
	[ "var" => ["a"] ], // Rule
	[ "a" => 1, "b" => 2 ]   // Data
);
// 1

如果您喜欢,我们支持 语法糖 在一元运算符上,以跳过值周围的数组

JWadhams\JsonLogic::apply(
	[ "var" => "a" ],
	[ "a" => 1, "b" => 2 ]
);
// 1

您还可以使用 var 运算符通过数字索引访问数组

JWadhams\JsonLogic::apply(
	[ "var" => 1 ],
	[ "apple", "banana", "carrot" ]
);
// "banana"

这是一个混合字面量和数据的复杂规则。这个派不会在温度低于110度或填满苹果之前准备好食用。

$rules = [ "and" => [
	[ "<" => [ [ "var" => "temp" ], 110 ] ],
	[ "==" => [ [ "var" => "pie.filling" ], "apple" ] ]
] ];

$data = [ "temp" => 100, "pie" => [ "filling" => "apple" ] ];

JWadhams\JsonLogic::apply($rules, $data);
// true

总是和从不

有时您要处理的规则是 "总是" 或 "从不"。如果传递给 JsonLogic::apply 的第一个参数不是对象或非关联数组,它将立即返回。

//Always
JWadhams\JsonLogic::apply(true, $data_will_be_ignored);
// true

//Never
JWadhams\JsonLogic::apply(false, $i_wasnt_even_supposed_to_be_here);
// false

安装

安装此库的最佳方式是通过 Composer

composer require jwadhams/json-logic-php

如果您不喜欢这种方法,并且想要自己管理更新,整个库都包含在 src/JWadhams/JsonLogic.php 中,您可以按照自己的意愿将其直接下载到项目中。

curl -O https://raw.githubusercontent.com/jwadhams/json-logic-php/master/src/JWadhams/JsonLogic.php