PHP code example of cleverage / ruler

1. Go to this page and download the library: Download cleverage/ruler 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/ */

    

cleverage / ruler example snippets


 // test

// PHP 5.3
$rule = new IsConnectedRule($user);
$rule->andRule(new IsSuscriberRule($user, 'PREMIUM'))
     ->andRule(new HasMoneyRule($user, 300))
     ->orRule(new IsAdminRule($user));

// PHP 5.4
$rule = (new IsConnectedRule($user))
  ->andRule(new IsSuscriberRule($user, 'PREMIUM'))
  ->andRule(new HasMoneyRule($user, 300))
  ->orRule(new IsAdminRule($user));

try {
    if ($rule->isSatisfied()) {
      echo 'activated';
    }
} catch (NotConnectedException $e) {
    // show connection form
} catch (NotSuscriberException $e) {
    // show subscription form
} catch (NotEnoughMoneyException $e) {
    echo 'not enough Money';
} catch(\CleverAge\Ruler\Exception\Exception $e) {
    echo 'Failed : '.$e->getMessage();
}

 // IsConnectedRule class
class IsConnectedRule extends \CleverAge\Ruler\RuleAbstract
{
    protected $_user;

    protected $_failure_exception_class = 'NotConnectedException';
    protected $_failure_message = 'user is not connected';

    public function __construct(\User $user)
    {
        $this->_user = $user;
    }

    public function doIsSatisfied()
    {
        return $this->_user->isLoggedOn();
    }
}

// ActiveFeatureXRule class
class ActiveFeatureXRule extends \CleverAge\Ruler\RuleAbstract
{
    public function __construct(\User $user)
    {
        $this->andRule(new IsSuscriberRule($user, 'PREMIUM'))
             ->andRule(new HasMoneyRule($user, 300))
             ->orRule(new IsAdminRule($user));
    }

    public function doIsSatisfied()
    {
        // method is abstract, and this container rule always satisfies.
        return true;
    }
}

// A,B,C,D,G,Z are rules
$A->andRule($B)
  ->orRule($C->andRule($Z))
  ->andRule($D)
  ->nandRule($G)
  ->isSatisfied();

// PHP =>($A && $B && $D && !$G) || ($C && $Z)
// Binary => (A.B.D.!G)+(C.Z)

// A,B,C,D,G,Z are rules
$A->andRule($B)
  ->orRule($C->andRule($Z))
  ->andRule($D)
  ->nandRule($G)
  ->isNotSatisfied()

// PHP => (!$A || !$B || !$D || $G) && (!$C || !$Z)
// Binary => (!A+!B+!D+G).(!C+!Z)

$A = new MyRule();
$A->setException('My\Name\Space\Ruler\Exceptions\MyException', 'my custom error message');

$A->isSatisfied();

// If rule is not satisfied
// it throws a new My\Name\Space\Ruler\Exceptions\MyException('my custom error message') exception