petrknap / optional
Optional (like in Java Platform SE 8 but in PHP)
Fund package maintenance!
Other
Installs: 25 011
Dependents: 4
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
Open Issues: 0
Requires
- php: >=8.1
Requires (Dev)
- nunomaduro/phpinsights: ^2.11
- petrknap/shorts: ^3.0
- phpstan/phpstan: ^1.12
- phpunit/phpunit: ^10.5
- squizlabs/php_codesniffer: ^3.7
README
A container object which may or may not contain a non-null value. If a value is present,
isPresent()
will returntrue
andget()
will return the value.Additional methods that depend on the presence or absence of a contained value are provided, such as
orElse()
(return a default value if value not present) andifPresent()
(execute a block of code if the value is present).This is a value-based class; use of identity-sensitive operations (including reference equality (==), identity hash code, or synchronization) on instances of Optional may have unpredictable results and should be avoided.
It is an easy way to make sure that everyone has to check if they have (not) received a null
.
Examples
namespace PetrKnap\Optional; /** @var Optional<string> $optionalString */ $optionalString = Optional::of('data'); if ($optionalString->isPresent()) { echo $optionalString->get(); } OptionalResource::ofFalsable(tmpfile())->ifPresent(function ($tmpFile): void { fwrite($tmpFile, 'data'); fclose($tmpFile); });
Create and use your own typed optional
namespace PetrKnap\Optional; class YourClass {} /** * @extends OptionalObject<YourClass> */ class YourOptional extends OptionalObject { protected static function getInstanceOf(): string { return YourClass::class; } } TypedOptional::register(YourOptional::class); // optional recommended step function your_strong_typed_function(YourOptional $input): YourOptional { return YourOptional::empty(); } /** * @param Optional<YourClass> $input * @return Optional<YourClass> */ function your_weak_typed_function(Optional $input): Optional { return YourOptional::empty(); }
Run composer require petrknap/optional
to install it.
You can support this project via donation.
The project is licensed under the terms of the LGPL-3.0-or-later
.