Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Json Logic Php Laravel Package

jwadhams/json-logic-php

Evaluate JsonLogic rules in PHP to share and store business logic across frontend and backend. Parses JSON-formatted logic (arrays/objects), supports nesting, comparisons, boolean ops, and data-driven evaluation via JsonLogic::apply with input data.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require jwadhams/json-logic-php:^1.5.1
    

    No additional configuration is required—just require the package in your project.

  2. First Use Case: Basic Rule Evaluation

    use JsonLogic\JsonLogic;
    
    $rule = [
        '==', ['var', 'age'], 30
    ];
    
    $data = ['age' => 30];
    $result = JsonLogic::evaluate($rule, $data); // true
    
  3. Where to Look First

    • Documentation (if available) or the JSON Logic Spec for syntax.
    • JsonLogic::evaluate() for core functionality.
    • JsonLogic::parse() for custom rule parsing (if needed).
    • New in 1.5.1: Support for expression-based initial values in reduce (see Implementation Patterns).

Implementation Patterns

Common Workflows

  1. Dynamic Rule Evaluation

    // Store rules in DB as JSON, fetch, and evaluate dynamically
    $storedRule = json_decode($dbRule, true);
    $result = JsonLogic::evaluate($storedRule, $userData);
    
  2. Combining Rules with Operators

    $complexRule = [
        'all',
        ['==', ['var', 'status'], 'active'],
        ['>', ['var', 'score'], 50]
    ];
    
  3. Variable Access

    • Use ['var', 'key'] to reference nested data:
      $rule = ['==', ['var', 'user.profile.role'], 'admin'];
      
  4. Custom Functions

    • Extend with custom logic via JsonLogic::addFunction():
      JsonLogic::addFunction('customFn', function ($args, $data) {
          return strtolower($args[0]);
      });
      
      $rule = ['customFn', ['var', 'name']];
      
  5. Error Handling

    • Wrap evaluations in try-catch:
      try {
          $result = JsonLogic::evaluate($rule, $data);
      } catch (\JsonLogic\Exception\InvalidJsonLogic $e) {
          Log::error("Invalid rule: " . $e->getMessage());
      }
      
  6. New in 1.5.1: Expression-Based reduce Initial Values

    • The reduce operator now supports expression-based initial values evaluated in the outer context:
      $rule = [
          'reduce',
          ['var', 'numbers'], // iterable
          ['+', ['var', 'initial'], ['var', 'item']], // operation
          ['var', 'initial'] // initial value (now supports expressions)
      ];
      
      $data = [
          'numbers' => [1, 2, 3],
          'initial' => 10
      ];
      $result = JsonLogic::evaluate($rule, $data); // 16 (10 + 1 + 2 + 3)
      
    • Key Use Case: Dynamically compute initial values from variables (e.g., ['var', 'baseValue']).

Integration Tips

  • Laravel Service Provider Bind the evaluator for dependency injection:
    $this->app->singleton('jsonLogic', function () {
        return new JsonLogic();
    });
    
  • Form Request Validation Use rules to validate dynamic conditions:
    $validator = Validator::make($request->all(), [
        'age' => ['required', function ($attribute, $value, $fail) {
            $rule = ['>=', ['var', 'age'], 18];
            if (!JsonLogic::evaluate($rule, ['age' => $value])) {
                $fail('Must be at least 18.');
            }
        }]
    ]);
    

Gotchas and Tips

Pitfalls

  1. Variable Scope in reduce

    • The initial value in reduce is now evaluated in the outer context, meaning ['var', 'key'] references the top-level $data array.
    • Example Pitfall:
      $rule = [
          'reduce',
          ['var', 'items'],
          ['+', ['var', 'total'], ['var', 'item']],
          ['var', 'total'] // Fails if 'total' is undefined in $data
      ];
      
    • Fix: Ensure variables exist or use defaults:
      $data = ['items' => [1, 2], 'total' => 0];
      
  2. Type Mismatches

    • Rules like ['==', 1, '1'] evaluate to false (strict comparison). Use ['==', ['var', 'id'], '1', true] for loose comparison (third argument enables type coercion).
  3. Circular References

    • Rules with circular dependencies (e.g., ['var', 'self'] where self references itself) may cause infinite loops.
    • Fix: Add depth limits or validate rules before evaluation.
  4. Performance

    • Complex rules with deep recursion (e.g., nested all/any operations) can be slow for large datasets.
    • Tip: Cache compiled rules if reused frequently.

Debugging

  • Enable Debug Mode
    JsonLogic::setDebug(true); // Logs parsed rules to `storage/logs/json-logic.log`
    
  • Validate Rules First Use JsonLogic::parse() to catch syntax errors early:
    try {
        JsonLogic::parse($rule);
    } catch (\JsonLogic\Exception\InvalidJsonLogic $e) {
        // Handle error
    }
    

Extension Points

  1. Custom Operators Extend core logic by adding new operators:

    JsonLogic::addOperator('in_range', function ($args, $data) {
        $value = $args[0][1] === 'var' ? $data[$args[0][0]] : $args[0];
        return $value >= $args[1] && $value <= $args[2];
    });
    

    Usage:

    $rule = ['in_range', ['var', 'age'], 18, 65];
    
  2. Hooks for Pre/Post Evaluation Override JsonLogic class methods (e.g., evaluate) in a decorator pattern for logging/auditing.

  3. Serialization Serialize rules to JSON for storage/transmission:

    $jsonRule = json_encode($rule);
    $decodedRule = json_decode($jsonRule, true);
    

Config Quirks

  • Default Behavior
    • JsonLogic::evaluate() throws exceptions on invalid rules by default. Use JsonLogic::evaluate($rule, $data, false) to return null on errors instead.
  • Custom Data Accessors Override variable resolution by extending JsonLogic and modifying the resolveVar() method.

New in 1.5.1: reduce Expression Support

  • Breaking Change: The reduce operator now evaluates the initial value as an expression if it is a var or array. Ensure your rules account for this:
    // Old behavior (if initial was a literal):
    ['reduce', ['var', 'items'], ['+', ['var', 'total'], ['var', 'item']], 0]
    
    // New behavior (initial as expression):
    ['reduce', ['var', 'items'], ['+', ['var', 'total'], ['var', 'item']], ['var', 'total']]
    
  • Migration Tip: Test reduce-based rules with the new release to confirm expected behavior.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor