PHP code example of djb / guard

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

    

djb / guard example snippets


class MyFlyingAppGuard extends \DJB\Guard\Guard {
  
  /**
   * This var allows you to describe your exceptions.
   * Should the raises() function be used, the exception raised will automatically contain the message associated with the relevant validation issue.
   */
  protected $exceptionMessages = [
   'can fly' => 'The provided object cannot fly!'
  ];

  private function canFly() {
    if ( ! $this->value->canFly()) $this->setIssue('can fly');
  }
}

guard($plane)->canFly()->otherwise(function($error) {
  // $error holds the error description from which validation failed.. but as we are only checking one thing we don't need it!
  throw new \Exception('The provided plane cannot fly!');
});

guard($plane)->canFly()->raises();
// Results in Excepton with message: 'The provided object cannot fly!'

function createBag($studs) {
  guard($studs)->greaterThan(5)->otherwise(function($error) {
  	  // $error will be 'equal or greater than'
	  throw new \Exception('There are not enough studs to make your gothic bag!');
  });
  return new Bag($studs);
}

if (! guard($var)->isString()->equal('hello')->passes()) {
  return 'Error!';
}

$min  = '2015-10-25 00:00:00';
$max  = '2015-10-26 00:00:00';
$date = '2015-10-24 00:00:00';

// The below will raise an Exception as $date does not fall between $min and $max
guard($date)->between($min, $max)->raises();
// Results in Excepton with message: 'The variable provided does not fall between the 

protected $exceptionMessages = ['is between' => 'Make it between 12 and 24, please'];