larapie/guard

Guard 对象用于条件性异常抛出。

v1.1 2019-03-30 14:55 UTC

This package is auto-updated.

Last update: 2024-09-29 03:41:53 UTC


README

Latest Stable Version Total Downloads Scrutinizer Code Quality Build Status Code Coverage StyleCI

安装

您可以通过 composer 安装此包

composer require larapie/guard

您是否曾经…

…遇到过一个情况,您需要抛出特定的错误,而条件又有很多 if 语句?

以下是一个例子

public function foo()
{
    if($user==null)
        throw new UserNotFoundException();
        
    if($user->age < 18)
        throw new NotOldEnoughException(18);
        
    ...
}

此包的目标是在 Guard 对象中解耦这些条件和它们的异常。然后这个 Guard 对象可以被 GuardHandler 处理。通过在 Guard 对象中组织代码,我们获得了几个优点

  • 我们可以在代码的其他地方重用相同的条件。
  • 代码变得更加容易阅读。
  • 对将要抛出的异常有更细粒度的控制。

让我们用 Guard 重新编写上面的例子

public function foo()
{
    guard(new UserDoesNotExistsGuard($user), new UserInsufficientAgeGuard($user, 18));
}

请注意,Guard 的顺序将决定首先抛出哪个异常。

class UserDoesNotExistsGuard extends Guard
{

    /**
     * The exception that will be thrown when the condition is met
     *
     * @var string
     */
    protected $exception = UserNotFoundException::class;


    /**
     * @var User
     */
    protected $user;

    /**
     * UserDoesNotExistsGuard constructor.
     * @param $user
     */
    public function __construct(User $user)
    {
        $this->user = $user;
    }

    /**
     * The condition that needs to be satisfied in order to throw the exception.
     *
     * @return bool
     */
    public function condition(): bool
    {
        return $this->user===null;
    }
}
class UserInsufficientAgeGuard extends Guard
{
    /**
     * @var User
     */
    protected $user;
    
    /**
     * @var int
     */
    protected $age;    

    /**
     * UserDoesNotExistsGuard constructor.
     * @param $user
     */
    public function __construct(User $user, int $age)
    {
        $this->user = $user;
        $this->age = $age;
    }

    /**
     * The condition that needs to be satisfied in order to throw the exception.
     *
     * @return bool
     */
    public function condition(): bool
    {
        return $this->user->age < this->age;
    }
    
    /**
     * The exception that gets thrown when the condition is satisfied.
     *
     * @return \Throwable
     */
    public function exception(): \Throwable
    {
        return new NotOldEnoughException(18);
    }    
}

未来

  • 实现一个功能,允许 GuardHandler 处理 OR 语句。

变更日志

请参阅 CHANGELOG 以获取有关最近更改的更多信息。

贡献

请参阅 CONTRIBUTING 以获取详细信息。

安全

如果您发现任何与安全相关的问题,请通过电子邮件 anthony.vanc@gmail.com 而不是使用问题跟踪器。

致谢

许可

MIT 许可证 (MIT)。请参阅 许可文件 以获取更多信息。