PHPackages                             eftec/minilang - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. eftec/minilang

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

eftec/minilang
==============

A mini scripting language for php

2.29(1y ago)113.2k2LGPL-3.0PHPPHP &gt;=7.4CI failing

Since Dec 26Pushed 1y ago1 watchersCompare

[ Source](https://github.com/EFTEC/MiniLang)[ Packagist](https://packagist.org/packages/eftec/minilang)[ Docs](https://github.com/EFTEC/MiniLang)[ RSS](/packages/eftec-minilang/feed)WikiDiscussions master Synced 1w ago

READMEChangelog (10)Dependencies (1)Versions (37)Used By (2)

MiniLang
========

[](#minilang)

This library is used to store business logic in a simple and yet powerful definition.

A mini script language for PHP. It does three simple tasks.

1. (optional) It set some initial values **(INIT)**.
2. It evaluates a logic expression **(WHERE)**.
3. If the expression (logic) is true then it executes the SET expression **(SET)**, so we could change the value of a variable, call a function and task like that.
4. (optional) If the expression (logic) is false then it executes the ELSE expression **(INIT)**.

For example :

```
when var1>5 and var2>20 then var3=20 // when and then
init var5=20 when var1>5 and var2>20 then var3=var5  // init, when and then
init var5=20 when var1>5 and var2>20 then var3=var5 else var3=var20 // init, when, then and else
when var1>$abc then var3=var5 // $abc is a PHP variable.

```

[![Packagist](https://camo.githubusercontent.com/f5bec8d8a416960bca2467618bc5492356051c3f25e289533e66860714a1a99d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f65667465632f6d696e696c616e672e737667)](https://packagist.org/packages/eftec/minilang)[![Total Downloads](https://camo.githubusercontent.com/4c427284f682d3c741593eab56dc6b76108855ff12009caebbcdabb2c90edbfc/68747470733a2f2f706f7365722e707567782e6f72672f65667465632f6d696e696c616e672f646f776e6c6f616473)](https://packagist.org/packages/eftec/minilang)![Maintenance](https://camo.githubusercontent.com/0c8f829897840ac35cb3daf181a719612c0f64c0ed5fca3c7b90ed7591169162/68747470733a2f2f696d672e736869656c64732e696f2f6d61696e74656e616e63652f7965732f323032352e737667)![composer](https://camo.githubusercontent.com/7a6cce75e3353cd615b111f2f4ff50dec30cf814dddb88b2613f656cec298330/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f636f6d706f7365722d253345322e302d626c75652e737667)![php](https://camo.githubusercontent.com/e5eef0b455ca9b0faae7697b9654c52f96b38f8cce34c0feb49fc702477bfcc9/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345372e342d677265656e2e737667)![php](https://camo.githubusercontent.com/5cd91a78fb469ca20b235b6951fb6dd77bda78ac4633eb432e93699bcb141589/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d382e342d677265656e2e737667)![CocoaPods](https://camo.githubusercontent.com/347353606ed8f26b45bcf9da083db0063fa1dadd1baef36a5f3bf9ce1d127548/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f646f63732d37302532352d79656c6c6f772e737667)

Why we need a mini script?
--------------------------

[](#why-we-need-a-mini-script)

Sometimes we need to execute arbitrary code in the basis of "if some value equals to, then we set or execute another code."

In PHP, we could do the next code.

```
if($condition) {
    $variable=1;
}
```

However, this code is executed at runtime. What if we need to execute this code at some specific point?.

We could do the next code:

```
$script='if($condition) {
    $variable=1;
}';

// and later..
eval($script);
```

This solution works (and it only executes if we call the command eval). But it is verbose, prone to error, and it's dangerous.

Our library does the same but safe and clean.

```
$mini->separate("when condition then variable=1");
```

Table of Content
----------------

[](#table-of-content)

- [MiniLang](#minilang)
    - [Why we need a mini script?](#why-we-need-a-mini-script)
    - [Table of Content](#table-of-content)
    - [Getting started](#getting-started)
    - [Methods](#methods)
        - [Constructor](#constructor)
        - [reset()](#reset)
        - [setCaller(&amp;$caller)](#setcallercaller)
        - [setDict(&amp;$dict)](#setdictdict)
        - [function separate($miniScript)](#function-separateminiscript)
        - [evalLogic($index)](#evallogicindex)
        - [evalAllLogic($stopOnFound = true, $start = false)](#evalalllogicstoponfound--true-start--false)
        - [evalSet($idx = 0, $position = 'set')](#evalsetidx--0-position--set)
    - [Fields](#fields)
        - [$throwError](#throwerror-)
        - [$errorLog](#errorlog)
    - [Definition](#definition)
        - [Sintaxis.](#sintaxis)
        - [Variables](#variables)
        - [Variables defined by a PHP Object](#variables-defined-by-a-php-object)
        - [Variables defined by a PHP array](#variables-defined-by-a-php-array)
        - [Global variables](#global-variables)
    - [Literals](#literals)
        - [Examples](#examples)
        - [Reserved methods](#reserved-methods)
    - [init](#init)
        - [Code:](#code)
    - [where](#where-)
        - [Example](#example)
        - [Logical expressions allowed](#logical-expressions-allowed)
    - [set](#set)
        - [Setting expressions allowed](#setting-expressions-allowed)
        - [Example:](#example-1)
        - [Code:](#code-1)
    - [else](#else)
        - [Example](#example-2)
    - [Loop](#loop)
    - [Compiling the logic into a PHP class](#compiling-the-logic-into-a-php-class)
        - [Creating the class](#creating-the-class)
        - [Using the class](#using-the-class)
    - [Benchmark](#benchmark)
        - [(reset+separate+evalAllLogic) x 1000](#resetseparateevalalllogic-x-1000)
        - [evalAllLogic x 1000](#evalalllogic-x-1000)
        - [(reset+separate2+evalAllLogic2) x 1000](#resetseparate2evalalllogic2-x-1000)
        - [(evalAllLogic2) x 1000](#evalalllogic2-x-1000)
        - [PHP method of class x 1000](#php-method-of-class-x-1000)
    - [Documentation](#documentation)
    - [To-do](#to-do)
    - [Version](#version)

Getting started
---------------

[](#getting-started)

Installing it using composer:

> composer requires eftec/minilang

Creating a new project

```
use eftec\minilang\MiniLang;
include "../lib/MiniLang.php"; // or the right path to MiniLang.php
$mini=new MiniLang();
$mini->separate("when field1=1 then field2=2"); // we set the logic of the language but we are not executed it yet.
$mini->separate("when field1=2 then field2=4"); // we set more logic.
$result=['field1'=>1,'field2'=>0]; // used for variables.
$callback=new stdClass(); // used for callbacks if any
$mini->evalAllLogic($callback,$result);
var_dump($result);
```

Another example:

```
use eftec\minilang\MiniLang;

include "../lib/MiniLang.php";

$result=['var1'=>'hello'];
$global1="hello";
$mini=new MiniLang(null,$result);
$mini->throwError=false; // if error then we store the errors in $mini->errorLog;
$mini->separate('when var1="hello" then var2="world" '); // if var1 is equals "hello" then var2 is set "world"
$mini->separate('when $global1="hello" then $global2="world" '); // we can also use php variables (global)
$mini->evalAllLogic(false); // false means it continues to evaluate more expressions if any
							// (true means that it only evaluates the first expression where "when" is valid)
var_dump($result); //  array(2) { ["var1"]=> string(5) "hello" ["var2"]=> string(5) "world" }
var_dump($global2); //  string(5) "world"
```

Methods
-------

[](#methods)

### Constructor

[](#constructor)

> \_\_construct(&amp;$caller,&amp;$dict,array $specialCom=\[\],$areaName=\[\],$serviceClass=null)

- object $caller Indicates the object with the callbacks
- array **$dict** Dictionary with initial values
- array **$specialCom** Special commands. it calls a function of the caller.
- array **$areaName** It marks special areas that could be called as " somevalue." \*null|object $serviceClass A service class. By default, it uses the $caller.

### reset()

[](#reset)

It reset the previous definitions but the variables, service and areas.

### setCaller(&amp;$caller)

[](#setcallercaller)

Set a caller object. The caller object it could be a service class with method that they could be called inside the script.

### setDict(&amp;$dict)

[](#setdictdict)

Set a dictionary with the variables used by the system.

### function separate($miniScript)

[](#function-separateminiscript)

It sends an expression to the MiniLang, and it is decomposed in its parts. The script is not executed but parsed.

### evalLogic($index)

[](#evallogicindex)

It evaluates a logic. It returns true or false.

- $index is the number of logic added by separate()

### evalAllLogic($stopOnFound = true, $start = false)

[](#evalalllogicstoponfound--true-start--false)

- bool $stopOnFound exit if some evaluation matches
- bool $start if true then it always evaluates the "init" expression.

### evalSet($idx = 0, $position = 'set')

[](#evalsetidx--0-position--set)

It sets a value or values. It does not consider if WHERE is true or not.

- int $idx number of expression
- string $position =\['set','init'\]\[$i\] It could be set or init

Fields
------

[](#fields)

### $throwError

[](#throwerror)

Boolean.

- If true (default value), then the library throw an error when an error is found (for example if a method does not exist).
- If false, then every error is captured in the array $errorLog

### $errorLog

[](#errorlog)

Array of String. if $throwError is false then every error is stored here.

Example:

```
$this->throwError=false;
$mini->separate("when FIELDDOESNOTEXIST=1 then field2=2");
var_dump($this->errorLog);
```

Definition
----------

[](#definition)

### Sintaxis.

[](#sintaxis)

The syntaxis of the code is separated into four parts. INIT, WHERE (or when), SET (or THEN) and ELSE.

Example:

```
$mini->separate("when field1=1 then field2=2");
```

It says if field1=1 then we set field2 as 2.

### Variables

[](#variables)

A variable is defined by `varname`

Example: [examples/examplevariable.php](examples/examplevariable.php)

```
$mini=new MiniLang();
$mini->separate("when field1>0 then field2=3"); // we prepare the language
$variables=['field1'=>1]; // we define regular variables
$callback=new stdClass();
$mini->evalAllLogic($callback,$variables); // we set the variables and run the languageand run the language
var_dump($variables); // field1=1, field2=3
```

### Variables defined by a PHP Object

[](#variables-defined-by-a-php-object)

A variable could host a PHP object, and it is possible to call and to access the fields inside it.

`varname.field`

- If the field exists, then it uses it.
- If the field doesn't exist, then it uses a method of the object CALLER.
- If the method of the CALLER doesn't exist then it tries to use the method of the service class
- If the method of the service class doesn't exist then it tries to use the inner method of the class MiniLang (with a prefix \_). Example function \_param()
- Finally, if everything fails then it triggers an error.

Example of code [examples/examplevariable2.php](examples/examplevariable2.php)

```
class MyModel {
    var $id=1;
    var $value="";
    public function __construct($id=0, $value="")
    {
        $this->id = $id;
        $this->value = $value;
    }
}
class ClassCaller {
    public function Processcaller($arg) {
        echo "Caller: setting the variable {$arg->id}";
    }
}
class ClassService {
    public function ProcessService($arg) {
        echo "Service: setting the variable {$arg->id}";
    }
}
$mini=new MiniLang([],[],new ClassService());
$mini->separate("when field1.id>0 then
                field2.value=3
                and field3.processcaller
                and processcaller(field3)
                and processservice(field3)"); // we prepare the language
$variables=['field1'=>new MyModel(1,"hi")
            ,'field2'=>new MyModel(2,'')
            ,'field3'=>new MyModel(3,'')]; // we define regular variables
$callback=new ClassCaller();
$mini->evalAllLogic($callback,$variables,false); // we set the variables and run the languageand run the language
var_dump($variables);
```

- field2.value references the field "value" (MyModel)
- field3.processcaller references the method ClassCaller::processcaller()
- processcaller(field3) does the same as field3.processcaller
- processservice(field3) calls the method ClassService::processservice()

### Variables defined by a PHP array

[](#variables-defined-by-a-php-array)

A variable could hold an associative/index array, and it is possible to read and to access the elements inside it.

Example:

```
$mini=new MiniLang(null,
                   [
                       'vararray'=>['associindex'=>'hi',0=>'a',1=>'b',2=>'c',3=>'d',4=>'last','a'=>['b'=>['c'=>'nested']]]
                   ]
                  );
```

```
vararray.associndex // vararray['associindex'] ('hi')
vararray.4 // vararray[4] 'last'
vararray.123 // it will throw an error (out of index)
vararray.param('a.b.c')) // vararray['a']['b']['c'] ('nested')
param(vararray,'a.b.c')) // vararray['a']['b']['c'] ('nested')
vararray._first // first element ('hi')
vararray._last // last element ('last')
vararray._count // returns the number of elements. (6)
```

- If the element exists, then it uses it.
- If the element doesn't exist, then it uses a method of the caller.
- If the method of the caller doesn't exist then it tries to use the method of the service class
- Finally, if everything fails then it triggers an error.

Example of code [examples/examplevariable\_arr.php](examples/examplevariable_arr.php)

```
class ClassCaller {
    public function Processcaller($arg) {
        echo "Caller: setting the variable {$arg['id']}";
    }
}
class ClassService {
    public function ProcessService($arg) {
        echo "Service: setting the variable {$arg['id']}";
    }
}

$mini=new MiniLang([],[],new ClassService());
$mini->separate("when field1.id>0 then
                field2.value=3
                and field3.processcaller
                and processcaller(field3)
                and processservice(field3)");

$variables=['field1'=>['id'=>1,'value'=>3]
            ,'field2'=>['id'=>2,'value'=>'']
            ,'field3'=>['id'=>3,'value'=>'']
           ];
$callback=new ClassCaller();
$mini->evalAllLogic($callback,$variables,false);
var_dump($variables);
```

- field2.value references the element "value" of the array
- field3.processcaller references the method ClassCaller::processcaller()
- processcaller(field3) does the same as field3.processcaller
- processservice(field3) calls the method ClassService::processservice()

### Global variables

[](#global-variables)

A global variable takes the values of the PHP ($GLOBAL), so it doesn't need to be defined or set inside the language

> **Note:** For security purpose. global variables defined by PHP as "$\_namevar" can't be read or modified. So if you want to protect a global variable, then you can rename it with an underscore as prefix.
> **Example:** If you try to read the variable $\_SERVER, then it will return the value of the variable $SERVER which it could be or not defined.

A global variable is defined by

`$globalname`

```
$globalname.associndex // $globalname['associindex']
$globalname.4 // $globalname[4]
$globalname.param('a.b.c') // $globalname['a']['b']['c']
param($globalname,'a.b.c') // $globalname['a']['b']['c']
```

Example:

`$globalname=30`

Example Code: [examples/exampleglobal.php](examples/exampleglobal.php)

```
$field1=1; // our global variable
$mini=new MiniLang();
$mini->separate('when $field1>0 then $field1=3'); // we prepare the language
$variables=[]; // local variables
$callback=new stdClass();
$mini->evalAllLogic($callback,$variables); // we set the variables and run the languageand run the language
var_dump($field1); // returns 3
```

Literals
--------

[](#literals)

TypeExampleNumber20string"hello world", 'hello world'stringp"my name is {{var}}"functionnamefunction(arg,arg)### Examples

[](#examples)

> set var=20 and var2="hello" and var3="hello {{var}}" and var4=fn()

### Reserved methods

[](#reserved-methods)

Reserved wordExplanationnull()null valuefalse()false valuetrue()true valueon()1param(var,'l1.l2.l3')Separates an array (var) into var\['l1'\]\['l2'\]\['l3'\]off()0undef()-1 (for undefined)flip()(special value). It inverts a value ON&lt;-&gt;OFF
Used as value=flip()now()returns the current timestamp (integer)timer()returns the current timestamp (integer)interval()returns the interval (in seconds) between the last change and now. It uses the field dateLastChange or method dateLastChange() of the callback classfullinterval()returns the interval (in seconds) between the start of the process and now. It uses the field dateInit or method dateInit() of the callback classcontains()/str\_contains()returns true if the text is contained in another text.Example: str\_contains(field1,'hi')str\_starts\_with(), startwith()returns true if the text starts with another textstr\_ends\_with(),endwith()returns true if the text ends with another text.Example: [examples/examplereserved.php](examples/examplereserved.php)

```
$mini=new MiniLang();
$mini->separate("when true=true then field1=timer()"); // we prepare the language
$variables=['field1'=>1]; // we define regular variables
$callback=new stdClass();
$mini->evalAllLogic($callback,$variables); // we set the variables and run the language
var_dump($variables);
```

Example Timer: [examples/examplereservedtimer.php](examples/examplereservedtimer.php)

```
class ClassWithTimer {
    var $dateLastChange;
    public function dateInit() {
        return time();
    }
    public function __construct()
    {
        $this->dateLastChange=time();

    }
}
$mini=new MiniLang();
$mini->separate("when true=true then field1=interval() and field2=fullinterval()"); // we prepare the language
$variables=['field1'=>0,'field2'=>0]; // we define regular variables
$callback=new ClassWithTimer();
$mini->evalAllLogic($callback,$variables); // we set the variables and run the language
var_dump($variables);
```

init
----

[](#init)

This part of the expression allows setting a value. This expression is usually optional, and it could be omitted.

> It is similar to SET, but it is executed before WHERE and no matter if WHERE is valid or not.

> **init counter=20** where variable1=20 set variable+counter

- it set the counter to 20.
- And compares: variable1 is equaled to 20
- If yes, then increases a variable by counter

### Code:

[](#code)

```
$mini->separate("init tmp=50 when condition=1 then field1+10"); // set tmp to 50. If condition is 1 then it increases the field1 by 10.
```

where
-----

[](#where)

This part of the expression adds a condition to the statement.

We can also use "when."

> **where** expression

or

> **when** expression

It's possible to compare more than a condition at the same time by separating by "and" or "or."

> where v1=10 and v2=20 or v3&lt;50

### Example

[](#example)

> where variable1=20 and $variable2=variable3 or function(20)=40

> where $field=20 and field2&lt;&gt;40 or field3=40 // sql syntax

> where $field==20 &amp;&amp; field2!=40 || field3=+40 // PHP syntax

> where 1 // it always true

### Logical expressions allowed

[](#logical-expressions-allowed)

- **equals:** = and == (the symbol "=" and "==" acts similarly).
- **not equals:** &lt;&gt; and !=
- **less than:** &lt;
- **less or equal than:** &lt;=
- **greater than:** &gt;
- **greater or equal than:** &gt;=
- **and logic:** "and" and &amp;&amp;
- **or logic:** "or" and ||

set
---

[](#set)

This part of the expression allows setting the value of a variable. It is possible to set more than one variable at the same time by separating by "," or "and."

We can also use the expression "set" or "then"

> **set** expression

or

> **then** expression

> This part of the expression is only executed if WHERE is valid

### Setting expressions allowed

[](#setting-expressions-allowed)

We could set a variable using the next expressions:

- variable=20
- variable=anothervariable
- variable=20+30
- variable=20-30 // it will work
- variable=20+-30 // !!!! **it will not work correctly because it will consider the -30 as a negative number "-30" and not "20 minus 30"**
- variable=40\*50+30
- variable+30 // it increases the variable by 30
- variable+=anothervariable // it will increase the variable by the value of anothervariable
- variable-30 // it decreases the variable by -30 Note: **+variable-30 will not work because the symbol - is an operation so +-20 is a double operator**
- variable=flip() // it flips the value 0-&gt;1 or 1-&gt;0

This library does not allow complex instruction such as

- variable=20+30\*(20+30) // is not allowed.

### Example:

[](#example-1)

> set variable1=20 and $variable2=variable3 and function(20)=40

### Code:

[](#code-1)

```
$mini->separate("when condition=1 then field1+10"); // if condition is 1 then it increases the field1 by 10.
```

else
----

[](#else)

This optional part of the expression allows setting the value of a variable. It is possible to set more than one variable at the same time by separating by "," or "and".

> This code is only evaluated if "where" returns false of if ELSE is called manually.

### Example

[](#example-2)

> else variable1=20 and $variable2=variable3 and function(20)=40

Loop
----

[](#loop)

It is possible to create a loop using the space "loop"

To start a loop, you must write

```
$this->separate('loop variableloop=variable_with_values');
// where variable_with_values is must contains an array of values
// variableloop._key will contain the key of the loop
// variableloop._value will contain the value of the loop
```

And to end the loop, you must use

```
$this->separate('loop end');
```

You can escape the loop using the operator "break" in the "set" or "else".

```
$this->separate('when condition set break else break');
```

> Note: Loops are only evaluated when you evaluate all the logic. It does not work with evalLogic() and evalLogic2()
>
> Note: You can't add a condition to a loop, however you can skip a loop assigning an empty array

Example:

```
$this->separate('loop $row=variable');
	$this->separate('loop $row2=variable');
		$this->separate('where op=2 then cc=2');
		$this->separate('where op=3 then break'); // ends of the first loop
	$this->separate('loop end');
$this->separate('loop end')
$obj->evalAllLogic();
```

Compiling the logic into a PHP class
------------------------------------

[](#compiling-the-logic-into-a-php-class)

It is possible to create a class with the logic created in the language. The goal is to increase the performance of the code.

### Creating the class

[](#creating-the-class)

To generate the class, first we need to write the logic using the method **separate2()** instead of **separate()**. It will store the logic inside an array of the instance of the class. You could use the code directly, or you could save inside a class as follows:

```
// create an instance of MiniLang
$mini=new MiniLang(null);
// the logic goes here
$mini->separate2('when var1="hello" and comp.f=false() then var2="world" '); // if var1 is equals "hello" then var2 is set "world"
// and the generation of the class
$r=$mini->generateClass('ExampleBasicClass','ns\example','ExampleBasicClass.php');
```

It will save a new file called 📄 ExampleBasicClass.php (you can check the example 📁 example/genclass/1.examplebasic.php)

### Using the class

[](#using-the-class)

With the class generated, you can use this new class instead of **MiniLang**. Since this class is already compiled, then it is blazing fast. However, if you need to change the logic, then you will need to compile it again. (you can check the example 📁 example/genclass/2.examplebasic.php and 📁 example/genclass/ExampleBasicClass.php)

```
$result=['var1'=>'hello'];
$obj=new ExampleBasicClass(null,$result);
$obj->evalAllLogic(true);
```

The class will look like:

```
