texthtml / maybe
Option & Result types
Installs: 4 851
Dependents: 0
Suggesters: 0
Security: 0
Stars: 17
Watchers: 3
Forks: 3
Open Issues: 3
pkg:composer/texthtml/maybe
Requires
- php: ^8.1
- texthtml/object-reaper: ^1.0
Requires (Dev)
- phpspec/prophecy-phpunit: ^2.0
- phpstan/extension-installer: ^1.1
- phpstan/phpstan: ^2.0
- phpstan/phpstan-phpunit: ^2.0
- phpstan/phpstan-strict-rules: ^2.0
- phpunit/phpunit: ^10.0|^11.0|^12.0
- slevomat/coding-standard: ^8.0
- squizlabs/php_codesniffer: ^3.6
- symfony/console: ^6.0|^7.0
- symfony/finder: ^6.0|^7.0
- texthtml/doctest: ^0.3
- vimeo/psalm: ^6.0
- dev-main
- v0.8.0
- v0.7.0
- v0.6.0
- v0.5.0
- v0.4.0
- v0.3.0
- v0.2.0
- v0.1.0
- dev-codex/find-and-fix-a-bug-in-codebase
- dev-renovate/actions-upload-pages-artifact-4.x
- dev-renovate/actions-checkout-5.x
- dev-phpunit-12
- dev-renovate/squizlabs-php_codesniffer-4.x
- dev-q4wvxi-codex/convert-phpunit-annotations-to-attributes
- dev-codex/convert-phpunit-annotations-to-attributes
- dev-renovate/phpunit-phpunit-11.x
- dev-github-actions
This package is auto-updated.
Last update: 2025-10-01 15:35:57 UTC
README
Help yourself by not returning null, false, -1 or throwing exception
for everything by using Option & Result instead.
Using those makes it harder to make mistake, make it easy to do common operations on unknown returned values and can help static analysis tool detect incorrect logic in PHP code.
Installation
composer req texthtml/maybe
Documentation
Read the documentation full API description, detailed explainations and usages.
Usage
Option
TH\Maybe\Option is a type that represents an optional value: every Option is either Some and contains a value, or None, and does not.
/** * @return Option<float> */ function divide(float $numerator, float $denominator): Option { return match ($denominator) { 0.0 => Option\none(), default => Option\some($numerator / $denominator), }; } // The return value of the function is an option $result = divide(2.0, 3.0); // Pattern match to retrieve the value if ($result->isSome()) { // The division was valid echo "Result: {$result->unwrap()}"; } else { // The division was invalid echo "Cannot divide by 0"; }
Result
TH\Maybe\Result is a type that represents either success (Ok), containing the result of an operation or failure (Err), containing the reason of the failure.
/** * @return Result<int,string> */ function parse_version(string $header): Result { return match ($header[0] ?? null) { null => Result\err("invalid header length"), "1" => Result\ok(1), "2" => Result\ok(2), default => Result\err("invalid version"), }; } $version = parse_version("1.x"); if ($version->isOk()) { echo "working with version: {$version->unwrap()}"; } else { echo "error parsing header: {$version->unwrapErr()}"; } // @prints working with version: 1