aharisu/option

PHP Option 对象,类似 Rust 语言

1.3.0 2023-07-15 03:08 UTC

This package is auto-updated.

Last update: 2024-09-15 05:39:31 UTC


README

Software License Software License Build Status Coverage Status Latest Version

版本信息

它将同时与 PHP 7.x 和 PHP 8.x 兼容。
以下 PHP 版本进行了测试

  • 7.0
  • 7.1
  • 7.2
  • 7.3
  • 7.4
  • 8.0
  • 8.1
  • 8.2

安装

composer require aharisu/option

使用方法

// make some object
$some = some(1);

// make none object
$none = none();

if ($some->isSome()) {
    $v = $some->unwrap();
}
if ($none->isNone()) {
    //do something
}

if (null != $v = $some->tryUnwrap()) {
    //do something
    print_r($v);
}

$some->someThen(function ($v) {
    //do something
    print_r($v);
});

$v2 = $none->unwrapOr(2);
$k = 10;
$v3 = $none->unwrapOrElse(fn () => 2 * $k);

// true
if (some(1)->equals(1)) {
}
if (some(1)->equals(some(1))) {
}
// false
if (none()->equals(null)) {
}

// false and type mismatch warning
if (some(1)->equals(1.0)) {
}
// false and type mismatch warning
if (some(1)->equals('1')) {
}

使用类属性

use aharisu\Option;

class ValueType
{
    /**
     * @param Option<string> $text
     * @param Option<int>    $value
     */
    public function __construct(
        public readonly int $id,
        public readonly Option $text,
        public readonly Option $value,
    ) {
    }
}

new ValueType(
    1,
    toOption('text'), //some
    toOption(null),   //none
);

许可证

Apache 2.0 & MIT