zanchi/utils 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

zanchi/utils

Composer 安装命令:

composer require zanchi/utils

包简介

PHP Utilies

关键字:

README 文档

README

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

Install via Composer:

composer require zanchi/utils

Minimum PHP version: 5.6

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

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

  • 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

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

  • 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

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

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

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

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

About

Author: Luis Zanchi Package: zanchi/utils

统计信息

  • 总下载量: 0
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-08-15