json-logic-php

repository·master·Indexed 41 days ago

https://github.com/jwadhams/json-logic-php

A PHP implementation of the JsonLogic specification that allows developers to define complex logic as JSON structures. It features the JWadhams\JsonLogic::apply() method for rule evaluation, support for the 'var' operator with dot-notation for nested data access, and the ability to extend the engine with custom operations via JsonLogic::add_operation().

Tokens
2K
Snippets
8
Records
9
Agent score
1%

What's inside json-logic-php

  1. How to use data-driven rules with the 'var' operator

    master

    To make rules dynamic, use the var operator to access values from a provided data object. This allows you to mix static literals with dynamic data.

    Accessing keys

    You can access associative array keys using ["var" => "key_name"]. The library also supports syntactic sugar for unary operators, allowing you to skip the array wrapper: ["var" => "key_name"].

    Accessing numeric indices

    You can access array elements by numeric index using ["var" => index].

    Nested data access

    You can access nested properties using dot notation within the var operator (e.g., ["var" => "parent.child"]).

    // Accessing a key
    JWadhams\JsonLogic::apply([ "var" => "a" ], [ "a" => 1, "b" => 2 ]);
    // returns 1
    
    // Syntactic sugar for unary operators
    JWadhams\JsonLogic::apply([ "var" => "a" ], [ "a" => 1, "b" => 2 ]);
    // returns 1
    
    // Accessing numeric index
    JWadhams\JsonLogic::apply([ "var" => 1 ], [ "apple", "banana", "carrot" ]);
    // returns "banana"
    
    // Complex nested rule
    $rules = [ "and" => [ 
        [ "<" => [ [ "var" => "temp" ], 110 ] ],
        [ "==" => [ [ "var" => "pie.filling" ], "apple" ] ]
    ] ];
    $data = [ "temp" => 100, "pie" => [ "filling" => "apple" ] ];
    JWadhams\JsonLogic::apply($rules, $data);
    // returns true
  2. How to implement 'Always' and 'Never' rules

    master

    If you need a rule that always evaluates to true or false, you can pass a boolean literal as the first argument to JWadhams\JsonLogic::apply(). If the first parameter is not an object or an associative array, the library returns it immediately without evaluating the data object.

    // Always true
    JWadhams\JsonLogic::apply(true, $any_data);
    
    // Always false
    JWadhams\JsonLogic::apply(false, $any_data);
  3. Install json-logic-php

    master

    You can install the library using Composer, which is the recommended method:

    composer require jwadhams/json-logic-php

    Alternatively, you can manually download the self-contained library file from the repository and include it in your project:

    curl -O https://raw.githubusercontent.com/jwadhams/json-logic-php/master/src/JWadhams/JsonLogic.php
  4. How conditional 'if' and '?:' operators work

    master

    The if and ?: operators implement a conditional branching pattern. They expect an odd number of parameters (3 or greater).

    Pattern: if( condition1, result1, condition2, result2, ..., [else_result] )

    1. The engine evaluates pairs of (condition, result).
    2. If a condition evaluates to truthy, the corresponding result is evaluated and returned immediately (short-circuiting).
    3. If the last parameter is provided without a preceding condition, it acts as the else block.
    4. If no conditions match and no else is provided, it returns null.
    // if(condition, then, else)
    $logic = ['if' => [['==' => [1, 1]], 'yes', 'no']];
    JsonLogic::apply($logic); // returns 'yes'
    
    // if(cond1, res1, cond2, res2, else)
    $logic = ['if' => [['==' => [1, 2]], 'a', ['==' => [1, 1]], 'b', 'c']];
    JsonLogic::apply($logic); // returns 'b'
  5. Use the 'var' operator to access data

    master

    The var operator allows you to retrieve values from the $data array passed to apply(). It supports dot-notation for descending into nested arrays or objects.

    • Dot-notation: Use strings like 'user.profile.name' to traverse the data structure.
    • Default values: You can provide a second argument to var to return a default value if the path is not found or is empty.
    • Root access: If var is called with null or an empty string, it returns the entire $data object/array.
    // Example of dot-notation access
    $logic = ['var' => 'user.age'];
    $data = ['user' => ['age' => 25]];
    
    $result = JsonLogic::apply($logic, $data);
    // $result is 25
  6. Evaluate JsonLogic rules with JWadhams\JsonLogic::apply()

    master

    The primary way to execute logic is using the JWadhams\JsonLogic::apply() method. This method accepts a rule (as an associative array or object) and an optional data object.

    Rules are structured as associative arrays where the key is the operator and the value is an array of operands. The library supports both associative arrays (decoded via json_decode($json, true)) and objects (decoded via json_decode($json, false)).

    // Using an associative array rule
    JWadhams\JsonLogic::apply([ "==" => [1, 1] ]);
    
    // Using a JSON string rule (decoded as object)
    $rule = '{"==":["apples", "apples"]}';
    JWadhams\JsonLogic::apply(json_decode($rule, false));
  7. Extend JsonLogic with custom operations

    master

    You can add your own operators to the engine using JsonLogic::add_operation($name, $callable).

    • $name: A string representing the operator key used in the JSON logic.
    • $callable: A PHP callable (function, closure, etc.) that accepts the arguments extracted from the logic rule and returns a result.

    Custom operations are executed during the apply() process if no built-in operator matches the provided name.

    JsonLogic::add_operation('is_even', function($n) {
        return $n % 2 === 0;
    });
    
    $logic = ['is_even' => [['var' => 'number']]];
    $data = ['number' => 4];
    
    $result = JsonLogic::apply($logic, $data);
    // $result is true
  8. Evaluate JsonLogic rules with apply()

    master

    The primary way to use this library is via the JsonLogic::apply($logic, $data) method. It evaluates a JSON Logic rule against a provided data set.

    • $logic: The rule to evaluate. It can be an associative array (e.g., ['==' => [1, 1]]), an object (which will be cast to an array), or an array of multiple logic statements.
    • $data: The data context used by operators like var to resolve values.

    If $logic is a simple array of multiple statements, apply() will return an array of the results of each statement.

    use JWadhams\JsonLogic;
    
    $logic = ['==' => [['var' => 'x'], 10]];
    $data = ['x' => 10];
    
    $result = JsonLogic::apply($logic, $data);
    // $result is true
  9. Reference built-in JsonLogic operators

    master

    The library includes several built-in operators for comparison, math, logic, and data manipulation:

    CategoryOperators
    Comparison==, ===, !=, !==, >, >=, <, <=
    Math% (modulo), + (sum), - (subtract), / (divide), * (product), max, min
    Logicand, or, !! (truthy), ! (not), if / ?: (conditional)
    Data/Arrayvar (data access), in (contains/substring), cat (concatenate), merge (array merge), substr (substring), missing (check for null/empty), missing_some
    Functionalfilter, map, reduce, all, none, some