Test Failed
Branch master (a8f59d)
by Ondra
04:16
created

assertLength()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
c 0
b 0
f 0
nc 2
nop 3
dl 0
loc 5
rs 10
1
<?php
2
3
/**
4
 * This file is part of the Pixidos package.
5
 *
6
 *  (c) Ondra Votava <[email protected]>
7
 *
8
 *  For the full copyright and license information, please view the LICENSE
9
 *  file that was distributed with this source code.
10
 *
11
 */
12
13
declare(strict_types=1);
14
15
namespace Pixidos\GPWebPay;
16
17
use Pixidos\GPWebPay\Exceptions\InvalidArgumentException;
18
19
/**
20
 * @param mixed  $value
21
 * @param string $name
22
 *
23
 * @throws InvalidArgumentException
24
 */
25
function assertIsInteger($value, string $name): void
26
{
27
    if (!is_numeric($value)) {
28
        throw new InvalidArgumentException(
29
            sprintf('%s must be numeric scalar type "%s" given.', $name, gettype($value))
30
        );
31
    }
32
33
    if (false === (bool)preg_match('#^[1-9]\d*$#', (string)$value)) {
34
        throw new InvalidArgumentException(sprintf('%s must be integer "%s" given.', $name, $value));
35
    }
36
}
37
38
/**
39
 * @throws InvalidArgumentException
40
 */
41
function assertMaxLength(string|int|float $value, int $length, string $name): void
42
{
43
    $strlen = strlen((string)$value);
44
    if ($strlen > $length) {
45
        throw new InvalidArgumentException(sprintf('%s max. length is %s! "%s" given.', $name, $length, $strlen));
46
    }
47
}
48
49
/**
50
 * @throws InvalidArgumentException
51
 */
52
function assertLength(string|int|float $value, int $length, string $name): void
53
{
54
    $strlen = strlen((string)$value);
55
    if ($strlen !== $length) {
56
        throw new InvalidArgumentException(sprintf('%s max. length is %s! "%s" given.', $name, $length, $strlen));
57
    }
58
}
59
60
/**
61
 * @throws InvalidArgumentException
62
 */
63
function assertIsEmail(string $value): void
64
{
65
    $atom = "[-a-z0-9!#$%&'*+/=?^_`{|}~]"; // RFC 5322 unquoted characters in local-part
66
    $alpha = "a-z\x80-\xFF"; // superset of IDN
67
68
    $result = (bool)preg_match(
69
        "(^
70
            (\"([ !#-[\\]-~]*|\\\\[ -~])+\"|$atom+(\\.$atom+)*)  # quoted or unquoted
71
            @
72
            ([0-9$alpha]([-0-9$alpha]{0,61}[0-9$alpha])?\\.)+    # domain - RFC 1034
73
            [$alpha]([-0-9$alpha]{0,17}[$alpha])?                # top domain
74
            \\z)ix",
75
        $value
76
    );
77
78
    if (false === $result) {
79
        throw new InvalidArgumentException(sprintf('EMAIL is not valid! "%s" given.', $value));
80
    }
81
}
82
83
/**
84
 * @throws InvalidArgumentException
85
 */
86
function assertUrl(string $url): void
87
{
88
    if (false === filter_var($url, FILTER_VALIDATE_URL)) {
89
        throw new InvalidArgumentException('URL is Invalid.');
90
    }
91
}
92