PHPackages                             djb/guard - 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. djb/guard

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

djb/guard
=========

Swift 2 inspired guard feature for PHP

v1.0(10y ago)024MITPHPPHP &gt;=5.4.0

Since Nov 19Pushed 10y ago1 watchersCompare

[ Source](https://github.com/dazzz1er/guard)[ Packagist](https://packagist.org/packages/djb/guard)[ RSS](/packages/djb-guard/feed)WikiDiscussions master Synced today

READMEChangelog (1)DependenciesVersions (2)Used By (0)

guard
=====

[](#guard)

Swift 2 inspired guard for PHP to make simple validation more readable.

Will add more methods as and when I need extended functionality, or if requested - pull requests welcome as well!

installation
------------

[](#installation)

`composer require djb/guard`

suggested usage
---------------

[](#suggested-usage)

Common validation required: email address, string, int, greaterthan, less than etc should be handled by the package.

After that I suggest extending the class to incorporate your own readable guard methods:

```
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');
  }
}
```

In use:

```
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!'
```

Note that to use the `guard()` function with your new class, you will need to modify the `helpers.php` file in the package to instantiate your new class instead of the package base class.

syntax
------

[](#syntax)

The syntax is inspired by Swift 2's guard feature, to guard a simple variable with an exception you could use the `otherwise` method:

```
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);
}
```

or you can get a boolean pass or fail using `passes`:

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

or you can have guard raise an `Exception` for you with `raises`:

```
$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 required boundaries.'
```

All validation methods handled by guard have a built in validation error description like the one above.

You can override this by subclassing `\DJB\Guard\Guard`, as in the example in suggested usage, and providing the `$exceptionMessages` property with keys matching the error code you want to override. i.e:

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

would override the `between($min, $max)` validation method's error message.

validation methods
------------------

[](#validation-methods)

You can check if the variable:

- **`exists`** - exists (if the var has length, or is a `bool` or `array`)
- **`isTrue`** - evaluates to bool `true`
- **`isFalse`** - evaluates to bool `false`
- **`isDate`** - is in a valid date format
- **`isClass($className)`** - is an instance of class `$className`
- **`isArray`** - is an `array`
- **`isInteger`** - is an `integer`
- **`isString`** - is a `string`
- **`isAlpha`** - contains only alphabetic characters
- **`isNumeric`** - contains only numeric characters
- **`isEmailAddress`** - is in email address format
- **`isURL`** - is a URL
- **`isActiveURL`** - is an URL which can be reached (i.e. website is live)
- **`isJSON`** - is a valid JSON string
- **`isIP`** - is IP address format
- **`length($length)`** - is the length specified
- **`in(Array $acceptable)`** - is one of the accepted values
- **`notIn(Array $excluded)`** - is not one of the excluded values
- **`after($date)`** - is after the provided date (can be a date format string, or an instance of `DateTime`)
- **`before($date)`** - is before the provided date (can be a date format string, or an instance of `DateTime`)
- **`between($min, $max)`** - is between the `$min` and `$max` values (can be a date format string, instance of `DateTime` or numbers)
- **`equal($value)`** - is equal to the provided value (number, string)
- **`lessThan($value)`** - is less than the provided value (number)
- **`greaterThan($value)`** - is greater than the provided value (number)
- **`equalOrLessThan($value)`** - is equal or less than the provided value (number)
- **`equalOrGreaterThan($value)`** - is equal or greater than the provided value (number)

###  Health Score

25

—

LowBetter than 35% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity6

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

3879d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/eca49a0bfdb5708a73d60cd92e86e8af0d7734e05191e9b444368e43cb9a9dfc?d=identicon)[dazzz1er](/maintainers/dazzz1er)

---

Top Contributors

[![dazzz1er](https://avatars.githubusercontent.com/u/6876139?v=4)](https://github.com/dazzz1er "dazzz1er (8 commits)")

### Embed Badge

![Health badge](/badges/djb-guard/health.svg)

```
[![Health](https://phpackages.com/badges/djb-guard/health.svg)](https://phpackages.com/packages/djb-guard)
```

###  Alternatives

[genericmilk/docudoodle

Generate documentation for your Laravel application using OpenAI

15433.6k](/packages/genericmilk-docudoodle)[scandipwa/persisted-query

ScandiPWA persisted query module

12250.8k3](/packages/scandipwa-persisted-query)[asgardcms/blog-module

A blog module for AsgardCMS.

4311.3k](/packages/asgardcms-blog-module)[hexadog/laravel-menus-manager

Dynamic Menus Management package for your Laravel application

184.8k](/packages/hexadog-laravel-menus-manager)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
