定制 kafkiansky/option 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

kafkiansky/option

最新稳定版本:v0.1.0

Composer 安装命令:

composer require kafkiansky/option

包简介

The Option that takes care of what you unwrap.

README 文档

README

Option that takes care of what you unwrap.

Requirements

  • PHP 8.1 or higher.

Installation

The package could be installed with composer:

composer require kafkiansky/option

Motivation

Every Option pattern implementation I've seen has allowed you to call unwrap and get either a value or an exception, which, in my opinion, is no different from calling methods from null. Same behaviour. Same error on production. But what if static analysis would make you check for a value before getting it? No problem.

<?php

declare(strict_types=1);

use Kafkiansky\Option\Option;

/**
 * @param Option<non-empty-string> $option
 */
function withName(Option $option): void
{
    echo $option->unwrap();
}

With this code you will get an IfThisIsMismatch error from psalm, because unwrap can only be called on type Some<T>, not None.

Let's fix that:

<?php

declare(strict_types=1);

use Kafkiansky\Option\Option;

/**
 * @param Option<non-empty-string> $option
 */
function withName(Option $option): void
{
    if ($option->isSome()) {
        echo $option->unwrap();
    }
}

Everything is fine now.

This code is also error-prone with NoValue issue:

<?php

declare(strict_types=1);

use Kafkiansky\Option\Option;

/**
 * @param Option<non-empty-string> $option
 */
function withName(Option $option): void
{
    if ($option->isNone()) {
        echo $option->unwrap();
    }
}

But this code has no errors because you have passed a default value for None type, so you can call unwrap without calling isSome.

<?php

declare(strict_types=1);

use Kafkiansky\Option\Option;

/**
 * @param Option<non-empty-string> $option
 */
function withName(Option $option): void
{
    echo $option
        ->map(
            fn (string $name): string => 'User: '. $name,
            fn (): string => 'anonymous',
        )
        ->unwrap()
    ;
}

And this code also contains no errors:

<?php

declare(strict_types=1);

use Kafkiansky\Option\Option;

/**
 * @param Option<non-empty-string> $option
 */
function withName(Option $option): void
{
    echo $option->unwrapOr('anonymous');
}

Limitations

At the moment this package works best with Psalm, because PHPStan does not yet know how to understand the if-this-is annotation.

Testing

$ composer phpunit

License

The MIT License (MIT). See License File for more information.

统计信息

  • 总下载量: 3
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2023-07-07