Completed
Push — master ( a787fa...dc9af5 )
by Vincent
05:35
created

AssertMemberName::assertIsValidMemberName()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 35
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 22
c 0
b 0
f 0
dl 0
loc 35
rs 9.568
cc 3
nc 1
nop 2
1
<?php
2
declare (strict_types=1);
3
4
namespace VGirol\JsonApiAssert\Asserts\Structure;
5
6
use PHPUnit\Framework\Assert as PHPUnit;
7
use VGirol\JsonApiAssert\Messages;
8
9
/**
10
 * Assertions relating to the member name
11
 */
12
trait AssertMemberName
13
{
14
    /**
15
     * Asserts that a member name is valid.
16
     *
17
     * @param string    $name
18
     * @param boolean   $strict     If true, unsafe characters are not allowed when checking members name.
19
     * @return void
20
     * @throws \PHPUnit\Framework\ExpectationFailedException
21
     */
22
    public static function assertIsValidMemberName($name, bool $strict): void
23
    {
24
        PHPUnit::assertIsString(
25
            $name,
26
            Messages::MEMBER_NAME_IS_NOT_STRING
27
        );
28
29
        PHPUnit::assertGreaterThanOrEqual(
30
            1,
31
            strlen($name),
32
            Messages::MEMBER_NAME_IS_TOO_SHORT
33
        );
34
35
        // Globally allowed characters
36
        $globally = '\x{0030}-\x{0039}\x{0041}-\x{005A}\x{0061}-\x{007A}';
37
        $globallyNotSafe = '\x{0080}-\x{FFFF}';
38
        // Allowed characters
39
        $allowed = '\x{002D}\x{005F}';
40
        $allowedNotSafe = '\x{0020}';
41
42
        $regex = "/[^{$globally}{$globallyNotSafe}{$allowed}{$allowedNotSafe}]+/u";
43
        $safeRegex = "/[^{$globally}{$allowed}]+/u";
44
45
        PHPUnit::assertNotRegExp(
46
            $strict ? $safeRegex : $regex,
47
            $name,
48
            Messages::MEMBER_NAME_HAVE_RESERVED_CHARACTERS
49
        );
50
51
        $regex = "/^[{$globally}{$globallyNotSafe}]{1}(?:.*[{$globally}{$globallyNotSafe}]{1})?$/u";
52
        $safeRegex = "/^[{$globally}]{1}(?:.*[{$globally}]{1})?$/u";
53
        PHPUnit::assertRegExp(
54
            $strict ? $safeRegex : $regex,
55
            $name,
56
            Messages::MEMBER_NAME_START_AND_END_WITH_ALLOWED_CHARACTERS
57
        );
58
    }
59
}
60