feat: add Results helper class (try / combine / flatten)#96
Conversation
- 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
|
Warning Review limit reached
Next review available in: 44 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the 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 configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (4)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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.
| public static function flatten(Result $result): Result | ||
| { | ||
| return $result->andThen(static fn (Result $inner): Result => $inner); | ||
| } |
There was a problem hiding this comment.
Results::flatten は現在 andThen とクロージャを使用して実装されていますが、これだと呼び出しのたびにクロージャの生成と呼び出しのオーバーヘッドが発生します。
以下のように isOk() と unwrap() を使用して直接インナーの Result を返すようにすることで、クロージャの割り当てを回避し、パフォーマンスを向上させることができます。
public static function flatten(Result $result): Result
{
if ($result->isOk()) {
return $result->unwrap();
}
return $result;
}
Codecov Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. |
There was a problem hiding this comment.
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 intoOk/Err. - Add
Results::combine(iterable<Result<T,E>>): Result<list<T>, E>with short-circuiting on the firstErr(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.
| 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
|
レビュー指摘への対応: (1) tests/Types/results.php を廃止し、3 つの assertType 関数を既存の tests/Types/result.php に統合しました(新規ファイル作成より既存編集を優先する規約に準拠)。(2) codecov patch/project の fail は、実行され得ない private コンストラクタ 1 行が未カバー扱いだったのが原因のため、 |
概要
コードレビューで提案した 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 がなくテンプレートTをResult<U, F>に分解できないため、インスタンス版は正確に型付けできません。静的ヘルパーなら@paramのテンプレートで内側の型まで完全に推論でき、assertTypeテストでResult<int, LogicException|RuntimeException>の推論をピン留めしていますtryはメソッド名として予約語ですが PHP 7 以降クラスメソッド名に使用可能ですResults(Java のObjects/Collections流)。ResultFactory等が好みであれば改名は容易ですTDD
https://claude.ai/code/session_017XTM7pxbWPVNLV639i5WgK