webhappens/conditional-methods

通过在调用时简单添加 If 或 Unless 来使方法调用条件化。

v0.3.0 2021-01-23 15:27 UTC

This package is auto-updated.

Last update: 2024-09-23 23:19:57 UTC


README

tests

条件方法

通过在调用时简单添加 If 或 Unless 来使方法调用条件化。条件方法允许您传递一个条件来决定是否执行它们,从而无需将它们包裹在逻辑中。这在链式调用时特别有用。

安装

通过 composer 安装

composer require webhappens/conditional-methods

ConditionalMethods 特性插入到您的类中

use \WebHappens\ConditionalMethods\ConditionalMethods;

如果您的类已经使用 __call 方法,请向其中添加以下内容

public function __call($method, $arguments)
{
    if ($type = static::matchConditionalMethod($method)) {
        return $this->callConditionalMethod($type, $method, $arguments);
    }

    // ...

    // throw new \BadMethodCallException();
}

If

If 添加到任何方法调用的末尾,并将条件作为第一个参数传递。

$insurer->renewIf($car->insuranceIsDue(), $car);

这取代了需要做类似以下操作的需求:

if ($car->insuranceIsDue()) {
    $insurer->renew($car);
}

Unless

UnlessIf 的工作方式相同,只是条件被反转。

Unless 添加到任何方法调用的末尾,并将条件作为第一个参数传递。

$insurer->renewUnless($car->insuranceIsValid(), $car);

致谢

我们的 Str 类只是 Laravel 的 Str 辅助函数的一些功能的拷贝。

许可

MIT 许可证 (MIT)。有关更多信息,请参阅 许可文件