PHPackages                             zanchi/utils - 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. zanchi/utils

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

zanchi/utils
============

PHP Utilies

00PHP

Since Aug 15Pushed 9mo agoCompare

[ Source](https://github.com/luiszanchi/php-utils)[ Packagist](https://packagist.org/packages/zanchi/utils)[ RSS](/packages/zanchi-utils/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

zanchi/utils
============

[](#zanchiutils)

A small set of lightweight utilities for plain PHP (compatible with PHP 5.6) focused on ergonomics and functional-style helpers:

- EnumType: Backport-like, class-based enums for PHP 5.6 with singleton instances per value.
- Result: Tiny result type (Ok/Err) to model success/failure without exceptions.
- Option: Maybe/Option type for nullable values.
- Pipe and Arg: Fluent value piping with placeholder-based function calls and simple DocBlock directives.

This library has no runtime dependencies and is namespaced under `Zanchi\Utils`.

Installation
------------

[](#installation)

Install via Composer:

```
composer require zanchi/utils
```

Minimum PHP version: 5.6

Contents
--------

[](#contents)

- EnumType (Zanchi\\Utils\\Support\\EnumType)
- Result (Zanchi\\Utils\\Support\\Result)
- Option (Zanchi\\Utils\\Support\\Option)
- Pipe and Arg (Zanchi\\Utils\\Support\\Map{Pipe,Arg})

Below you can find quick examples for each component.

---

EnumType
--------

[](#enumtype)

Backport-style enum base class. Define your enum by extending `EnumType` and declaring `const` values. Instances are singletons per value.

```
use Zanchi\Utils\Support\EnumType;

final class Status extends EnumType
{
    const DRAFT = 'draft';
    const PUBLISHED = 'published';
    const ARCHIVED = 'archived';
}

$draft = Status::from('draft');              // throws if invalid
$maybe = Status::tryFrom('published');       // null if invalid

$cases  = Status::cases();  // ['DRAFT' => 'draft', ...]
$names  = Status::names();  // ['DRAFT', 'PUBLISHED', 'ARCHIVED']
$values = Status::values(); // ['draft', 'published', 'archived']

$draft->name();   // 'DRAFT'
$draft->value();  // 'draft'

// Equality compares both class and value
$draft->equals(Status::from('draft'));            // true
$draft->equals(Status::from('published'));        // false
$draft->equals(Another\Status::from('draft'));   // false

(string) $draft;        // 'draft'
json_encode($draft);    // '"draft"'
```

### Notes

[](#notes)

- `from($value)` throws `InvalidArgumentException` if the value is not one of the enum constants.
- `tryFrom($value)` returns `null` instead of throwing.
- Instances are cached per-class and per-value (singleton per value).

---

Result
------

[](#result)

A tiny `Result` type to model success (`Ok`) or failure (`Err`) without throwing. Useful to chain operations and avoid try/catch at call sites.

```
use Zanchi\Utils\Support\Result;

$ok = Result::ok(10);
$err = Result::err(new \RuntimeException('boom'));

$ok->isOk();   // true
$ok->isErr();  // false

$val = $ok->map(function ($v) { return $v * 2; })
          ->andThen(function ($v) { return Result::ok($v + 1); })
          ->unwrapOr(0); // 21

$fallback = $err->map(function ($v) { return $v; })
               ->mapError(function ($e) { return $e; })
               ->unwrapOr('default'); // 'default'

// Exception capture
$r = Result::tryCatch(function () {
    if (mt_rand(0, 1)) {
        return 123;
    }
    throw new \InvalidArgumentException('nope');
});
$final = $r->unwrapOr(0); // 123 or 0
```

### Methods at a glance

[](#methods-at-a-glance)

- `ok($v)` / `err($e)`
- `tryCatch(callable $fn)`
- `isOk()` / `isErr()`
- `map($fn)` transforms Ok value; Err is kept as-is (same instance)
- `mapError($fn)` transforms Err value; Ok is kept as-is (same instance)
- `andThen($fn)` chains with a callable that may return a raw value or another `Result`
- `unwrapOr($default)` returns the Ok value or the provided default

---

Option
------

[](#option)

Simple `Option`/`Maybe` type for nullable values.

```
use Zanchi\Utils\Support\Option;

$some = Option::some('data');
$none = Option::none();

$from = Option::fromNullable(null); // -> none

$isSome = $some->isSome(); // true
$isNone = $none->isNone(); // true

$mapped = $some->map(function ($v) { return strtoupper($v); }); // Some('DATA')
$plain  = $mapped->getOrElse('fallback'); // 'DATA'

$plain2 = $none->getOrElse(function () { return 'computed-default'; });
```

---

Pipe and Arg
------------

[](#pipe-and-arg)

A minimal, fluent pipeline that lets you pipe a current value through functions. You can:

- Use `then(callable $fn, ...$extra)` to pass the current value as the first argument.
- Use `call(callable $fn, ...$args)` with placeholders `Arg::_()` to inject the current value at arbitrary positions.
- Use `callAt(callable $fn, int $position, ...$args)` to specify the index explicitly (0-based).
- Use `tap(callable $fn, ...$args)` for side effects without changing the value.
- Use `when($predicate, $fn)` / `unless($predicate, $fn)` for conditional transformations.

It also supports two simple DocBlock directives on the target callable when using `call()` without placeholders:

- `@pipe-into N` to define the injection position (0-based; default is 0)
- `@pipe-accept Type|Other` to validate the current value type before calling

```
use Zanchi\Utils\Support\Map\Pipe;
use Zanchi\Utils\Support\Map\Arg;

$slug = Pipe::with('  Hello World  ')
    ->then('trim')
    ->call('str_replace', Arg::_(), ' ', '-')      // str_replace($value, ' ', '-')
    ->then('strtolower')
    ->value(); // 'hello-world'

// Example with callAt
$len = Pipe::with('abc')
    ->callAt('substr', 0, 0, 2) // injects 'abc' at position 0 -> substr('abc', 0, 2)
    ->then('strlen')
    ->value(); // 2

// Example for @pipe-into and @pipe-accept
/**
 * @pipe-into 1
 * @pipe-accept string
 */
function surround($needle, $haystack) {
    return '[' . $haystack . ':' . $needle . ']';
}

$out = Pipe::with('x')
    ->call('surround', '-') // value goes to position 1 -> surround('-', 'x')
    ->value(); // "[-:x]"
```

---

Running tests
-------------

[](#running-tests)

This repository ships a PHPUnit configuration. After installing dev dependencies:

```
composer install
vendor/bin/phpunit
```

On Windows PowerShell, you can also run:

```
vendor\bin\phpunit
```

License
-------

[](#license)

MIT License. See `LICENSE` if present, or the `license` field in composer.json.

About
-----

[](#about)

Author: Luis Zanchi Package: zanchi/utils

###  Health Score

15

—

LowBetter than 3% of packages

Maintenance41

Moderate activity, may be stable

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity13

Early-stage or recently created project

 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.

### Community

Maintainers

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

---

Top Contributors

[![luiszanchi](https://avatars.githubusercontent.com/u/26325408?v=4)](https://github.com/luiszanchi "luiszanchi (1 commits)")

### Embed Badge

![Health badge](/badges/zanchi-utils/health.svg)

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

###  Alternatives

[devgeniem/wp-no-admin-ajax

A WordPress plugin that lightens the WP AJAX routine and directs the requests to front-end rather than admin back-end.

3821.4k1](/packages/devgeniem-wp-no-admin-ajax)[0x13a/geodistance-php

Calculate geodistance between two points, latitude and longitude

3120.6k](/packages/0x13a-geodistance-php)

PHPackages © 2026

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