定制 tetthys/wrap 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

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

tetthys/wrap

Composer 安装命令:

composer require tetthys/wrap

包简介

Minimal Result-like wrapper with fluent map/filter/reduce and conditional helpers for PHP 8.3+.

README 文档

README

A minimal, fluent Result-like wrapper for PHP 8.3+.

  • Safely execute code and keep either a value (ok) or a captured exception (fail)
  • Transform values (then, map, filter, reduce)
  • Use expressive flow helpers (when, unless, branch)
  • Add modern chain helpers (andThen, ensure, recoverWhen, mapError, rethrowWhen, tap, tryTap, failWhen)
  • Support optional pipelines (keep, whenValue, whenValueThen) and error side-effects (tapError, tryTapError)
  • Make exception behavior explicit with safe*, try*, and rethrow* helpers

Installation

composer require tetthys/wrap

Quick Start

use Tetthys\Wrap\Wrap;

$result = Wrap::handle(fn() => riskyOperation())
    ->tryOk(fn($v) => logger()->info('ok', ['value' => $v]))       // swallows callback exceptions
    ->tryFail(fn($e) => logger()->warning('fail', ['msg' => $e->getMessage()])) // swallows callback exceptions
    ->rescue(fn() => 42)                                          // recover from failure
    ->then(fn($v) => $v * 2)
    ->getValueOr(0);

echo $result; // 84

Exception Policy (Important)

Wrap deliberately separates how exceptions are handled by method name. You should be able to tell whether an exception is thrown, captured, or swallowed just by reading the chain.

1) Thrown (escape the Wrap boundary)

These methods do not catch exceptions from callbacks or explicitly rethrow errors:

  • then, map, filter, reduce
  • ok, fail
  • rethrowWhen
  • rescueWhen (when predicate does not match)
  • rescueExcept (when error matches except list)
  • throwIfFailed, rethrow, rethrowRoot

Use these when an error must propagate to the caller.

2) Captured (invalidate the chain)

These methods catch exceptions and convert them into a failed Wrap state (using InvalidArgumentException with the original error as previous):

  • safeThen, safeMap, safeFilter, safeReduce
  • tap, tapError
  • when, unless, branch
  • ensure, safeKeep
  • whenValue, whenValueThen
  • Added: safeOk, safeFail

Use these when errors should stay inside the Wrap pipeline.

3) Swallowed (ignored)

These methods ignore callback exceptions entirely and keep the current state:

  • tryTap, tryTapError
  • Added: tryOk, tryFail

Use these for logging, metrics, tracing, or any side effects that must never break the flow.

Recommended rule of thumb

  • Logging / metrics / monitoring → try*
  • Business logic that may fail → safe*
  • Domain or application boundaries → throwIfFailed / rethrow*

Construction

Wrap::handle(callable $callback)

Runs a callback and captures its return value or any thrown Throwable.

$wrap = Wrap::handle(fn() => 42);
$wrap = Wrap::handle(fn() => throw new RuntimeException('boom'));

Wrap::fromValue(mixed $value)

Creates a successful Wrap.

$wrap = Wrap::fromValue(['a' => 1]);

Wrap::fromError(Throwable $error)

Creates a failed Wrap.

$wrap = Wrap::fromError(new RuntimeException('x'));

Side Effects

ok(callable $callback) / fail(callable $callback)

Runs only on success / failure.

If the callback throws, the exception is thrown immediately.

Wrap::handle(fn() => 10)
    ->ok(fn($v) => logger()->info("Value: $v"));

safeOk(callable $callback) / safeFail(callable $callback)

Runs only on success / failure.

If the callback throws, the chain is invalidated.

Wrap::handle(fn() => 10)
    ->safeOk(fn($v) => riskyLog($v))
    ->then(fn($v) => $v + 1);

tryOk(callable $callback) / tryFail(callable $callback)

Runs only on success / failure.

If the callback throws, the exception is swallowed.

Wrap::handle(fn() => 10)
    ->tryOk(fn($v) => riskyLog($v))
    ->then(fn($v) => $v + 1);

always(callable $callback): void

Always runs (finally-style) and ends the chain.

Receives (bool $ok, ?Throwable $error, mixed $value).

finally(callable $callback)

Always runs and continues the chain. If the callback throws, the chain is invalidated.

Transformations

then(callable $callback)

Transforms the stored value on success.

⚠ If the callback throws, the exception is thrown.

$out = Wrap::handle(fn() => 10)
    ->then(fn(int $x) => $x + 5)
    ->then(fn(int $x) => (string) ($x * 2))
    ->getValueOr('fallback');

safeThen(callable $callback)

Catches exceptions and invalidates instead of throwing.

Iterable Operators

map, filter, and reduce require the stored value to be iterable.

  • map / filter / reducethrow
  • safeMap / safeFilter / safeReduceinvalidate

Recovery

rescue(callable $fallback)

On failure, provides a fallback value and flips the state to success.

✅ The fallback may accept zero arguments or one Throwable argument.

Wrap::handle(fn() => throw new RuntimeException('oops'))
    ->rescue(fn() => 123)
    ->getValueOr(-1);
Wrap::handle(fn() => throw new RuntimeException('oops'))
    ->rescue(fn(Throwable $e) => 123);

recoverWhen(string|callable $matcher, callable $fallback)

Recover only when the failure matches a class-string or predicate.

Flat-mapping

andThen(callable $callbackReturningWrap)

Like then(), but flattens another Wrap into the chain.

Validation

ensure(callable $predicate, string|callable $message = 'Ensure failed')

Invalidates the chain when the predicate returns false.

Optional Value Flow

Helpers for pipelines where null means “no work to do”:

  • keep, safeKeep
  • whenValue, whenValueThen

Error Utilities

throwIfFailed(?callable $factory = null)

Escapes the Wrap boundary. Throws the captured error if failed.

rethrow()

Throws the captured error as-is. If invalidated, throws the wrapper exception.

rethrowRoot()

Throws the root cause error (the previous exception when wrapped).

Wrap::handle(fn() => 1)
    ->safeThen(fn() => throw new RuntimeException('root'))
    ->rethrowRoot();

rethrowWhen(string|callable $matcher)

Throws the captured error only when it matches.

tapError / tryTapError

  • tapError → callback throws → invalidate
  • tryTapError → callback throws → swallow

Extraction & Accessors

  • isOk()
  • getError()
  • getValue()
  • getValueOr()
  • getValueOrCall()
  • getValueOrNull()
  • getOrThrow()

Optional Global Helper

function wrap(callable $callback): Wrap
{
    return Wrap::handle($callback);
}

License

MIT

tetthys/wrap 适用场景与选型建议

tetthys/wrap 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 58 次下载、GitHub Stars 达 1, 最近一次更新时间为 2025 年 10 月 17 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 tetthys/wrap 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 tetthys/wrap 我们能提供哪些服务?
定制开发 / 二次开发

基于 tetthys/wrap 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-10-17