PHPackages                             tracesoftwareinternational/elephant-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. [HTTP &amp; Networking](/categories/http)
4. /
5. tracesoftwareinternational/elephant-guard

ActiveLibrary[HTTP &amp; Networking](/categories/http)

tracesoftwareinternational/elephant-guard
=========================================

PSR-7 and PSR-15 HTTP compliant middleware

1.1.0(6y ago)2522GPL-3.0PHPPHP ^7.1CI failing

Since Apr 11Pushed 6y ago3 watchersCompare

[ Source](https://github.com/TraceSoftwareInternational/ElephantGuard)[ Packagist](https://packagist.org/packages/tracesoftwareinternational/elephant-guard)[ RSS](/packages/tracesoftwareinternational-elephant-guard/feed)WikiDiscussions master Synced 2mo ago

READMEChangelog (1)Dependencies (11)Versions (4)Used By (0)

Elephant Guard
==============

[](#elephant-guard)

[![Software License](https://camo.githubusercontent.com/3ca82e27764c921f5b030689faba4f4a176d98384a170974bdec84292e1d83e2/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d47504c25323076332e302d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE)[![Build Status](https://camo.githubusercontent.com/f99a651b96766ec521b623a11edcfa7f2cf241b3ff093e72621101f93ead6914/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f5472616365536f667477617265496e7465726e6174696f6e616c2f656c657068616e742d67756172642f6d61737465722e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.org/TraceSoftwareInternational/elephant-guard)[![Latest Version](https://camo.githubusercontent.com/4405a0b063911f165818f90550ffa29ca2cae09caad37b749b404a5c81766412/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7472616365736f667477617265696e7465726e6174696f6e616c2f656c657068616e742d67756172642e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tracesoftwareinternational/elephant-guard)

This middleware is meant to apply a given [`AuthenticatorInterface`](src/ElephantGuard/AuthenticatorInterface.php) on a given set of routes.

It can be used with all frameworks using PSR-7 or PSR-15 style middlewares. It has been tested with [Slim Framework](http://www.slimframework.com/).

Credits
-------

[](#credits)

Huge thanks to [Mika Tuupola](https://github.com/tuupola) for his greatly structured [PSR-15](https://www.php-fig.org/psr/psr-15/) compliant middlewares that inspired us (thinking of [slim-jwt-auth](https://github.com/tuupola/slim-jwt-auth) and [slim-basic-auth](https://github.com/tuupola/slim-basic-auth)), Elephant Guard contains some of his work, a lot of thanks Mika !

Install
-------

[](#install)

Install latest version using [composer](https://getcomposer.org/).

```
$ composer require tracesoftwareinternational/elephgant-guard

```

Usage
-----

[](#usage)

Configuration options are passed as an array. Only mandatory parameter is `authenticator`.

For more information, please refer to [Parameters](#Parameters).

Parameters
----------

[](#parameters)

Authenticator
-------------

[](#authenticator)

The main purpose of this library is to test an incoming request against a class that implements [`AuthenticatorInterface`](src/ElephantGuard/AuthenticatorInterface.php)

By example, you could use a random based authentication :

```
use TraceSoftware\Middleware\ElephantGuard\AuthenticatorInterface;
use TraceSoftware\Middleware\ElephantGuard

class RandomAuthenticator implements AuthenticatorInterface {
    public function __invoke(array $arguments) {
        return (bool)rand(0,1);
    }

    public function getLastError(): string
    {
        return "";
    }
}

$app = new Slim\App;

$app->add(new ElephantGuard([
    "path" => "/",
    "authenticator" => new RandomAuthenticator
]);
```

Same thing can also be accomplished with anonymous class declaration.

```
use TraceSoftware\Middleware\ElephantGuard\AuthenticatorInterface;
use TraceSoftware\Middleware\ElephantGuard

$app = new Slim\App;

$app->add(new ElephantGuard([
    "path" => "/",
    "authenticator" => new class implements AuthenticatorInterface {

        public function __invoke(\Psr\Http\Message\ServerRequestInterface $request): bool
        {
            return (bool) rand(0,1);
        }

        public function getLastError(): string
        {
            return "";
        }
    }
]);
```

### Path

[](#path)

The optional `path` parameter allows you to specify the protected part of your website. It can be either a string or an array. You do not need to specify each URL. Instead think of `path` setting as a folder. In the example below everything starting with `/api` will be authenticated.

```
$app = new Slim\App;

$app->add(new \TraceSoftware\Middleware\ElephantGuard([
    "path" => "/api", /* or ["/admin", "/api"] */
    "authenticator" => new \MyCustomAuthenticator()
]));
```

### Ignore

[](#ignore)

With optional `ignore` parameter you can make exceptions to `path` parameter. In the example below everything starting with `/api` and `/admin` will be authenticated with the exception of `/api/token` and `/admin/ping` which will not be authenticated.

```
$app = new Slim\App;

$app->add(new \TraceSoftware\Middleware\ElephantGuard([
    "path" => ["/api", "/admin"],
    "ignore" => [
        "/api/token",
        "/admin/ping"
    ],
    "authenticator" => new \MyCustomAuthenticator()
]));
```

You may use the Glob syntax as supported by [webmozart/glob](https://github.com/webmozart/glob) to ignore routes with parameters in URL (like `/products/123456`)

### Before

[](#before)

Before function is called only when authentication succeeds but before the next incoming middleware is called. You can use this to alter the request before passing it to the next incoming middleware in the stack. If it returns anything else than `\Psr\Http\Message\RequestInterface` the return value will be ignored.

```
$app = new Slim\App;

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
    "path" => "/admin",
    "authenticator" => new \MyCustomAuthenticator()
    "before" => function ($request, $arguments) {
        return $request->withAttribute("user", $arguments["user"]);
    }
]));
```

### After

[](#after)

After function is called only when authentication succeeds and after the incoming middleware stack has been called. You can use this to alter the response before passing it next outgoing middleware in the stack. If it returns anything else than `\Psr\Http\Message\ResponseInterface` the return value will be ignored.

```
$app = new Slim\App;

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
    "path" => "/admin",
    "authenticator" => new \MyCustomAuthenticator()
    "after" => function ($request, $response, $arguments) {
        return $response->withHeader("X-Brawndo", "plants crave");
    }
]));
```

Setting response body when authentication fails
-----------------------------------------------

[](#setting-response-body-when-authentication-fails)

By default Elephant Guard returns an empty response body with 401 response and an array of "arguments".

arguments will be an array containing two indexes :

- `message` : the reason why it failed
- `authenticatorError` : the last error retrieved from the provided authenticator

You can return custom body using by providing an error handler. This is useful for example when you need additional information why authentication failed.

```
$app = new Slim\App;

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
    "path" => "/api",
    "authenticator" => new \MyCustomAuthenticator()
    "error" => function ($response, array $arguments) {
        $data = [];
        $data["status"] = "error";
        $data["message"] = $arguments["message"];
        $data["additionalInformation"] = $arguments['authenticatorError'];
        return $response->write(json_encode($data, JSON_UNESCAPED_SLASHES));
    }
]));
```

Testing
-------

[](#testing)

You can run tests manually with [composer](https://getcomposer.org/) :

```
$ composer test
```

License
-------

[](#license)

The GNU General Public License v3.0 (GPL v3.0). Please see [License File](LICENSE) for more information.

###  Health Score

29

—

LowBetter than 60% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity15

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity60

Established project with proven stability

 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 ~230 days

Total

3

Last Release

2491d ago

### Community

Maintainers

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

---

Top Contributors

[![glc-mvion](https://avatars.githubusercontent.com/u/6715182?v=4)](https://github.com/glc-mvion "glc-mvion (7 commits)")

---

Tags

psr-7middlewareauthpsr-15

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

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

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

###  Alternatives

[tuupola/slim-basic-auth

PSR-7 and PSR-15 HTTP Basic Authentication Middleware

4442.0M26](/packages/tuupola-slim-basic-auth)[tuupola/cors-middleware

PSR-7 and PSR-15 CORS middleware

1331.8M24](/packages/tuupola-cors-middleware)[mezzio/mezzio

PSR-15 Middleware Microframework

3883.6M97](/packages/mezzio-mezzio)[relay/relay

A PSR-15 server request handler.

3302.1M86](/packages/relay-relay)[jimtools/jwt-auth

PSR-15 JWT Authentication middleware, A replacement for tuupola/slim-jwt-auth

20142.3k3](/packages/jimtools-jwt-auth)[hkarlstrom/openapi-validation-middleware

PSR-7 and PSR-15 OpenAPI Validation Middleware

95198.8k1](/packages/hkarlstrom-openapi-validation-middleware)

PHPackages © 2026

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