PHP 抛出辅助函数。用于抛出异常的简写函数

1.0.0 2019-04-10 19:08 UTC

This package is auto-updated.

Last update: 2024-09-11 14:48:19 UTC


README

Latest Version on Packagist Software License Build Status Coverage Status Quality Score Total Downloads

PHP 库,提供抛出异常的函数

安装

通过 Composer

$ composer require aurimasniekis/throws

使用方法

所有函数都定义在 Throws\\ 命名空间下,非常简单。

最简单的函数是 thr,它接受异常作为参数并抛出

<?php

use function Throws\thr;

thr(new Exception("FooBar"));

或者您可以直接使用格式化的字符串抛出特定的异常

<?php

use function Throws\thrException;

thrException('Oh now "%s" error occurred', 'Big Error'); 

可用方法

thr(new Exception('FooBar'));

thrBadFunctionCallException('FooBar');

thrBadMethodCallException('FooBar');

thrDomainException('FooBar');

thrInvalidArgumentException('FooBar');

thrLengthException('FooBar');

thrLogicException('FooBar');

thrOutOfBoundsException('FooBar');

thrOutOfRangeException('FooBar');

thrOverflowException('FooBar');

thrRangeException('FooBar');

thrRuntimeException('FooBar');

thrUnderflowException('FooBar');

thrUnexpectedValueException('FooBar');

thrErrorException('FooBar');

thrError('FooBar');

thrArgumentCountError('FooBar');

thrArithmeticError('FooBar');

thrAssertionError('FooBar');

thrDivisionByZeroError('FooBar');

thrCompileError('FooBar');

thrParseError('FooBar');

thrTypeError('FooBar');

为什么?

你可能想知道为什么需要这样的库,以下是一些示例

// Instead of this
if ($foo !== 'bar') {
    throw new InvalidArgumentException(
        sprintf(
            'Oh no $foo is "%s"',
            $foo
        )
    );   
}

// Much simpler
$foo !== 'bar' || thrInvalidArgumentException('Oh no $foo is "%s"', $foo);

或者这个

// Instead of this
if (false === isset($array['key'])) {
    throw new InvalidArgumentException('Oh no key is missing');
} 

// Much simpler
$array['key'] ?? thrInvalidArgumentException('Oh no key is missing');
  

测试

运行测试用例

$ composer test

运行测试用例并生成覆盖率报告(HTML格式)

$ composer test-coverage

运行 PHP 风格检查器

$ composer check-style

运行 PHP 风格修复器

$ composer fix-style

贡献

请参阅 CONTRIBUTINGCONDUCT 了解详细信息。

许可

请参阅 License File 获取更多信息。