PHP code example of aegisora / rule-contract

1. Go to this page and download the library: Download aegisora/rule-contract library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

aegisora / rule-contract example snippets


class UserAgeRule extends Rule
{
    protected function executeValidate(Context $context): Result
    {
        $age = $context->getValue();
        
        if ($age < 18) {
            return $this->getDefaultInvalidResult();
        }
        
        return $this->getDefaultValidResult();
    } 
}

$rule = new UserAgeRule();
$result = $rule->validate(Context::create(20));
if ($result->isValid()) {
    // valid
}

$ruleContext = RuleContext::createFromValue($rule, 20);
$result = $ruleContext->getRule()->validate($ruleContext->getContext());

$collection = RuleContextCollection::create(
    RuleContext::create($ruleA, Context::create($valueA)),
    RuleContext::create($ruleB, Context::create($valueB)),
);

foreach ($collection as $ruleContext) {
    $result = $ruleContext->getRule()->validate($ruleContext->getContext());
    // ...
}