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

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

adriengras/guard-php
====================

A tiny guard() helper for PHP (Symfony/Laravel/plain).

1.0.4(10mo ago)133MITPHPPHP ^8.2CI passing

Since Aug 11Pushed 10mo agoCompare

[ Source](https://github.com/AdrienGras/guard-php)[ Packagist](https://packagist.org/packages/adriengras/guard-php)[ RSS](/packages/adriengras-guard-php/feed)WikiDiscussions main Synced 2w ago

READMEChangelogDependencies (2)Versions (6)Used By (0)

guard-php
=========

[](#guard-php)

[![GitHub Workflow Status](https://camo.githubusercontent.com/1f3d77c8f8cd9ec89bc2fb245d30c37a34252523aee3e6cd10f0fcbc94a71746/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f41647269656e477261732f67756172642d7068702f74657374732e796d6c3f6272616e63683d6d61696e266c6f676f3d676974687562)](https://github.com/AdrienGras/guard-php/actions)[![Packagist Version](https://camo.githubusercontent.com/9bce460b0487241cb56e0542820b2a38293b51237bd9feabb4520efae046f030/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f61647269656e677261732f67756172642d7068703f6c6f676f3d7061636b6167697374)](https://packagist.org/packages/adriengras/guard-php)[![PHP Version](https://camo.githubusercontent.com/788e2c354ee1d81d8f1b9d165faaf5521c37513890cee9ee85927d21e022c698/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f61647269656e677261732f67756172642d7068703f6c6f676f3d706870)](https://packagist.org/packages/adriengras/guard-php)[![License](https://camo.githubusercontent.com/46eebb26061285609285474d5c78da65aba76c0800c46329f4e3aa100b1ab67f/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f41647269656e477261732f67756172642d706870)](LICENSE)

A tiny PHP library bringing the **`guard`** concept (inspired by Kotlin, Swift, Dart…) to PHP.
Available globally via Composer — works in **plain PHP, Symfony, and Laravel**.

---

✨ Features
----------

[](#-features)

- **Global `guard()` function** available everywhere
- Throws an exception if a condition is not met
- Supports:
    - Simple error message
    - Existing exception instance
    - Lazy exception factory (`callable`)
- **Caller blame** mode: the error is shown as if it occurred where `guard()` was called, not inside the package
- PHP **8.1+** compatible
- Zero runtime dependencies

❓ Why this package?
-------------------

[](#-why-this-package)

Defensive programming is a key practice to make your code more reliable and easier to debug.
Languages like **Kotlin** and **Swift** provide a native `guard` statement to quickly validate assumptions and fail fast when something is wrong.

In PHP, similar checks often look like this:

```
if ($price < 0) {
    throw new InvalidArgumentException('Price must be non-negative');
}
```

This package brings a **concise, expressive, and consistent way** to write those checks:

```
guard($price >= 0, 'Price must be non-negative');
```

Benefits:

- **Readability** – One-line, expressive intent
- **Consistency** – Same syntax across all projects and frameworks
- **Less boilerplate** – No repetitive if + throw blocks
- **Framework-agnostic** – Works in plain PHP, Symfony, Laravel…

⚙️ How it works — Caller blame mode
-----------------------------------

[](#️-how-it-works--caller-blame-mode)

By default, guard() is in caller **blame mode** (`$blameCaller = true`):

- It scans the **debug backtrace** to find the first frame **outside** `vendor/` and outside the `guard.php` file itself.
- It then *tries* to rewrite the `$file` and `$line` properties of the exception via `ReflectionProperty` so the error appears to originate from your code.
- If PHP forbids modifying these properties (some runtimes mark them internally as readonly), `guard()` falls back to **wrapping** the original exception in an `ErrorException`:
    - The new exception has `file` and `line` set to the caller’s location
    - The original exception is preserved as `$previous`

Example — without blame:

```
In vendor/your-vendor/guard-php/src/functions.php line 47:
Price must be non-negative
```

Example — with blame (default):

```
In src/Service/CheckoutService.php line 123:
Price must be non-negative
```

You can disable caller blame explicitly:

```
guard($condition, 'message', null, null, false);
```

📦 Installation
--------------

[](#-installation)

```
composer require adriengras/guard-php
```

> The global function is automatically loaded via autoload.files — no extra configuration needed.

🚀 Usage
-------

[](#-usage)

### Basic example

[](#basic-example)

```
guard($price >= 0, 'Price must be non-negative');
```

### With a custom exception

[](#with-a-custom-exception)

```
guard($user !== null, new DomainException('User not found'));
```

### Lazy exception (callable)

[](#lazy-exception-callable)

```
guard($stock >= $qty, fn() => new OutOfRangeException("Not enough stock for SKU {$sku}"));
```

🧩 Framework compatibility
-------------------------

[](#-framework-compatibility)

- **Symfony** – works out-of-the-box in controllers, services, commands…
- **Laravel** – works directly in controllers, jobs, events…
- **Plain PHP** – just require 'vendor/autoload.php';

🧪 Tests
-------

[](#-tests)

Tests are written with [Pest](https://pestphp.com/).

### Run tests:

[](#run-tests)

```
composer test
```

### Run tests with coverage:

[](#run-tests-with-coverage)

```
XDEBUG_MODE=coverage composer test:cov
```

🤝 Contributing
--------------

[](#-contributing)

Contributions are welcome!
If you’d like to contribute:

- Fork the repository
- Create a new branch (`git checkout -b feature/my-feature`)
- Make your changes
- Run the tests (`composer test`)
- Submit a Pull Request

📄 License
---------

[](#-license)

MIT - You can find the licence in the [LICENSE](LICENSE) file.

###  Health Score

33

—

LowBetter than 72% of packages

Maintenance54

Moderate activity, may be stable

Popularity10

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity53

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

Every ~0 days

Total

5

Last Release

316d ago

PHP version history (2 changes)1.0.0PHP ^8.1

1.0.3PHP ^8.2

### Community

Maintainers

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

---

Top Contributors

[![AdrienGras](https://avatars.githubusercontent.com/u/72006541?v=4)](https://github.com/AdrienGras "AdrienGras (17 commits)")

---

Tags

phpsymfonylaravelhelperguard

###  Code Quality

TestsPest

### Embed Badge

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

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

###  Alternatives

[laravelista/ekko

Framework agnostic PHP package for marking navigation items active.

274691.7k4](/packages/laravelista-ekko)[fab2s/yaetl

Widely Extended Nodal Extract-Transform-Load ETL Workflow AKA NEJQTL or Nodal-Extract-Join-Qualify-Tranform-Load

64187.4k](/packages/fab2s-yaetl)[rumenx/php-feed

Framework-agnostic PHP Feed generator for Laravel, Symfony, and more.

3664.1k](/packages/rumenx-php-feed)[llm-agents/agents

LLM Agents PHP SDK - Autonomous Language Model Agents for PHP

16612.6k9](/packages/llm-agents-agents)[lazerg/laravel-enum-pro

A powerful PHP enum extension with collection support, random selection, and magic static calls

4319.5k](/packages/lazerg-laravel-enum-pro)[rumenx/php-assets

Framework-agnostic PHP package to manage frontend assets in the backend. Works with plain PHP, Laravel, Symfony, and any PHP framework.

1043.3k](/packages/rumenx-php-assets)

PHPackages © 2026

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