Skip to content

feat: add Results helper class (try / combine / flatten)#96

Merged
valbeat merged 3 commits into
mainfrom
feat/results-helpers
Jul 7, 2026
Merged

feat: add Results helper class (try / combine / flatten)#96
valbeat merged 3 commits into
mainfrom
feat/results-helpers

Conversation

@valbeat

@valbeat valbeat commented Jul 7, 2026

Copy link
Copy Markdown
Owner

概要

コードレビューで提案した 3 つのヘルパー(例外インターオペの try、集約の combine、平坦化の flatten)の追加です。3 つとも同じ新規クラスに載るため 1 PR にまとめています。

変更内容

新規 Valbeat\Result\Results(静的ヘルパー、インスタンス化不可):

  • Results::try(callable $fn): Result<T, Throwable> — 例外を投げる既存 PHP コードを Result の世界に持ち込む入口。成功なら Ok、Throwable 送出なら Err(DivisionByZeroError などの Error も捕捉することをテストで確認)
  • Results::combine(iterable<Result<T, E>>): Result<list<T>, E> — 全部成功なら値のリスト、失敗があれば最初の Err を short-circuit で返す(バリデーション集約用途)。Generator も受け付けます
  • Results::flatten(Result<Result<T, E2>, E1>): Result<T, E1|E2> — ネストの平坦化

設計メモ

  • flatten をインスタンスメソッドにしなかったのは PHPStan の制約のためです。条件型に infer がなくテンプレート TResult<U, F> に分解できないため、インスタンス版は正確に型付けできません。静的ヘルパーなら @param のテンプレートで内側の型まで完全に推論でき、assertType テストで Result<int, LogicException|RuntimeException> の推論をピン留めしています
  • try はメソッド名として予約語ですが PHP 7 以降クラスメソッド名に使用可能です
  • クラス名は Results(Java の Objects / Collections 流)。ResultFactory 等が好みであれば改名は容易です

TDD

  1. 挙動テスト 9 件 + 型テスト(tests/Types/results.php 新設)を先に追加し RED(10 エラー)を確認してコミット
  2. 実装して GREEN: 79 tests / 127 assertions、PHPStan max エラーなし、cs-fixer クリーン
  3. README の使用例 4 つはすべて PHP 8.4.7 で実行して動作確認済み

https://claude.ai/code/session_017XTM7pxbWPVNLV639i5WgK

valbeat added 2 commits July 7, 2026 13:13
- Results::try(callable): run exception-throwing code and wrap the
  outcome (Ok on success, Err<Throwable> on throw, including Errors)
- Results::combine(iterable<Result<T,E>>): Result<list<T>, E>,
  short-circuiting on the first Err
- Results::flatten(Result<Result<T,E2>,E1>): Result<T, E1|E2>

flatten is a static helper rather than an instance method because
PHPStan cannot destructure a template (no 'infer' in conditional
types), while @param templates on a static type precisely.

Currently RED: the Results class does not exist yet.

Claude-Session: https://claude.ai/code/session_017XTM7pxbWPVNLV639i5WgK
- Results::try(callable): bridge from exception-throwing code into
  the Result world — Ok with the return value, or Err wrapping the
  thrown Throwable (Errors included)
- Results::combine(iterable<Result<T,E>>): Result<list<T>, E> with
  first-Err short-circuit, for validation-style aggregation
- Results::flatten(Result<Result<T,E2>,E1>): Result<T, E1|E2>

These are static helpers because PHP interfaces cannot carry
implementations and PHPStan conditional types cannot destructure a
template parameter (no infer), whereas @param templates on statics
give full inference. Type-level behavior is pinned with assertType
tests alongside the runtime tests.

Claude-Session: https://claude.ai/code/session_017XTM7pxbWPVNLV639i5WgK
@valbeat valbeat self-assigned this Jul 7, 2026
@coderabbitai

coderabbitai Bot commented Jul 7, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@valbeat, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 44 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 0b312048-75ce-41bd-8c2f-3777467cca3c

📥 Commits

Reviewing files that changed from the base of the PR and between 98a2fcb and 1d5de98.

📒 Files selected for processing (4)
  • README.md
  • src/Results.php
  • tests/ResultsTest.php
  • tests/Types/result.php
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/results-helpers

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a new Results helper class containing static methods (try, combine, and flatten) to simplify the creation, combination, and flattening of Result instances, complete with comprehensive unit and PHPStan type-inference tests. The feedback suggests optimizing the Results::flatten method to avoid closure allocation overhead by directly checking isOk() and returning the unwrapped result.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread src/Results.php
Comment on lines +77 to +80
public static function flatten(Result $result): Result
{
return $result->andThen(static fn (Result $inner): Result => $inner);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Results::flatten は現在 andThen とクロージャを使用して実装されていますが、これだと呼び出しのたびにクロージャの生成と呼び出しのオーバーヘッドが発生します。

以下のように isOk()unwrap() を使用して直接インナーの Result を返すようにすることで、クロージャの割り当てを回避し、パフォーマンスを向上させることができます。

    public static function flatten(Result $result): Result
    {
        if ($result->isOk()) {
            return $result->unwrap();
        }

        return $result;
    }

@codecov

codecov Bot commented Jul 7, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (98a2fcb) to head (1d5de98).
✅ All tests successful. No failed tests found.

Additional details and impacted files
@@             Coverage Diff             @@
##                main       #96   +/-   ##
===========================================
  Coverage     100.00%   100.00%           
- Complexity        40        46    +6     
===========================================
  Files              2         3    +1     
  Lines             80        93   +13     
===========================================
+ Hits              80        93   +13     
Flag Coverage Δ
unittests 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

@valbeat valbeat marked this pull request as ready for review July 7, 2026 04:35
Copilot AI review requested due to automatic review settings July 7, 2026 04:35

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR introduces a new static helper class Valbeat\Result\Results to make it easier to interoperate with exception-throwing code (try), aggregate multiple Results (combine), and flatten nested Results (flatten), with both behavior tests and PHPStan type-inference tests.

Changes:

  • Add Results::try(callable): Result<T, Throwable> to wrap exception/error-throwing callables into Ok/Err.
  • Add Results::combine(iterable<Result<T,E>>): Result<list<T>, E> with short-circuiting on the first Err (supports generators).
  • Add Results::flatten(Result<Result<T,E2>,E1>): Result<T, E1|E2> plus corresponding tests and README examples.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.

File Description
src/Results.php Adds the new Results static helper class (try, combine, flatten).
tests/ResultsTest.php Adds behavior tests for the new helper methods (success, error, empty iterable, generator, flatten cases).
tests/Types/results.php Adds PHPStan assertType coverage for generic inference of try/combine/flatten.
README.md Documents the new helper APIs and provides usage examples.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread README.md
Comment on lines +144 to +150
use Valbeat\Result\Results;

// Wrap exception-throwing code: Ok on success, Err<Throwable> on throw
$result = Results::try(fn() => json_decode($raw, flags: JSON_THROW_ON_ERROR));

// Combine many Results: Ok with all values, or the first Err
$result = Results::combine([new Ok(1), new Ok(2), new Ok(3)]);
…om coverage

Review feedback:
- tests/Types/results.php duplicated the role of the existing
  tests/Types/result.php (same namespace, same purpose); fold the
  three assertType functions into the existing file per the
  edit-over-create convention
- the never-executed private constructor was the one uncovered diff
  line failing the codecov patch (92.85% < 100%) and project checks;
  mark it @codeCoverageIgnore

Claude-Session: https://claude.ai/code/session_017XTM7pxbWPVNLV639i5WgK
@valbeat

valbeat commented Jul 7, 2026

Copy link
Copy Markdown
Owner Author

レビュー指摘への対応: (1) tests/Types/results.php を廃止し、3 つの assertType 関数を既存の tests/Types/result.php に統合しました(新規ファイル作成より既存編集を優先する規約に準拠)。(2) codecov patch/project の fail は、実行され得ない private コンストラクタ 1 行が未カバー扱いだったのが原因のため、@codeCoverageIgnore を付与しました。

@valbeat valbeat merged commit dc383f0 into main Jul 7, 2026
9 checks passed
@valbeat valbeat deleted the feat/results-helpers branch July 7, 2026 06:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants