-
Notifications
You must be signed in to change notification settings - Fork 2
Sample test code
stevewest edited this page Oct 6, 2014
·
3 revisions
Below is a sample rule and result used to modify the price of a project if that product is in the context. It is not meant as a serious implementation but as an idea as to what the logic processor can be used for.
<?php
use Ve\LogicProcessor\AbstractResult;
use Ve\LogicProcessor\AbstractRule;
use Ve\LogicProcessor\Assertion\Equal;
use Ve\LogicProcessor\Modifier\Percent;
use Ve\LogicProcessor\Processor;
use Ve\LogicProcessor\RuleSet;
require __DIR__.'/vendor/autoload.php';
class HasProductRule extends AbstractRule
{
public function run($context)
{
$find = null;
foreach ($context as $id => $product)
{
if ($this->getAssertion()->run($product['id']))
{
$find = $product;
break;
}
}
return $find !== null;
}
}
class ProductDiscountResult extends AbstractResult
{
public function mutate(&$target)
{
$id = null;
foreach ($target as $id => $product)
{
if ($product['id'] == $this->getValue())
{
break;
}
}
if ($id !== null)
{
$target[$id]['price'] = $this->getModifier()
->run($target[$id]['price']);
}
}
}
$context = [
['id' => 1, 'name' => 'foobar', 'qty' => 12, 'price' => 10],
['id' => 2, 'name' => 'bazbat', 'qty' => 9, 'price' => 25],
];
// Set up a rule that will give a 50% discount on product 1
// Set up the "has product" rule and point it at product 1
$modifier = new Equal();
$modifier->setTargetValue(1);
$rule = new HasProductRule();
$rule->setAssertion($modifier);
// Set up our 50% discount
$result = new ProductDiscountResult();
$resultMod = new Percent();
$resultMod->setTargetValue(50);
$result->setModifier($resultMod);
$result->setValue(1);
// Roll them into a rule set
$ruleSet = new RuleSet();
$ruleSet->setRule($rule);
$ruleSet->addResult($result);
// Add to the rule set and run
$pro = new Processor;
$pro->addRuleSet($ruleSet);
$pro->run($context, $context);
// New price for product 1 is now 5
var_dump($context);