functions.php ➔ enforce()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 2
dl 0
loc 6
ccs 0
cts 0
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Dgame\Ensurance;
4
5
use AssertionError;
6
use Throwable;
7
8
/**
9
 * @param mixed $value
10
 *
11
 * @return Ensurance
12 57
 * @throws Throwable
13
 */
14
function ensure($value): Ensurance
15
{
16
    return new Ensurance($value);
17
}
18
19
/**
20
 * @param bool        $condition
21
 * @param string|null $message
22 3
 *
23
 * @return BooleanEnsurance
24
 * @throws Throwable
25
 */
26
function enforce(bool $condition, string $message = null): BooleanEnsurance
27
{
28
    $error = new AssertionError($message ?? 'Assertion failed');
0 ignored issues
show
Unused Code introduced by
The call to AssertionError::__construct() has too many arguments starting with $message ?? 'Assertion failed'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
29
30
    return ensure($condition)->isTrue()->orThrowWith($error);
31
}
32
33
/**
34
 * @param string $message
35
 * @param mixed  ...$args
36
 *
37
 * @return string
38
 */
39
function format(string $message, ...$args): string
40
{
41
    if (empty($args)) {
42
        return $message;
43
    }
44
45
    foreach ($args as &$arg) {
46
        if (is_array($arg) || is_object($arg)) {
47
            $arg = print_r($arg, true);
48
        }
49
    }
50
51
    return sprintf($message, ...$args);
52
}
53