Completed
Push — master ( ce9b1c...c08493 )
by Vincent
02:22
created

AssertArrays::isArrayOfObjects()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
namespace VGirol\JsonApiAssert\Asserts;
3
4
use PHPUnit\Framework\Assert as PHPUnit;
5
use PHPUnit\Util\InvalidArgumentHelper;
6
use VGirol\JsonApiAssert\Messages;
7
8
trait AssertArrays
9
{
10
    /**
11
     * Asserts that an array is an array of objects.
12
     *
13
     * @param array     $json
14
     * @param string    $message   An optional message to explain why the test failed
15
     *
16
     * @throws \PHPUnit\Framework\ExpectationFailedException
17
     */
18
    public static function assertIsArrayOfObjects($json, $message = '')
19
    {
20
        if (!\is_array($json)) {
0 ignored issues
show
introduced by
The condition is_array($json) is always true.
Loading history...
21
            throw InvalidArgumentHelper::factory(
22
                1,
23
                'array',
24
                $json
25
            );
26
        }
27
28
        $message = $message ?: Messages::MUST_BE_ARRAY_OF_OBJECTS;
29
        PHPUnit::assertTrue(static::isArrayOfObjects($json), $message);
30
    }
31
32
    /**
33
     * Asserts that an array is not an array of objects.
34
     *
35
     * @param array     $json
36
     * @param string    $message   An optional message to explain why the test failed
37
     *
38
     * @throws \PHPUnit\Framework\ExpectationFailedException
39
     */
40
    public static function assertIsNotArrayOfObjects($json, $message = '')
41
    {
42
        if (!\is_array($json)) {
0 ignored issues
show
introduced by
The condition is_array($json) is always true.
Loading history...
43
            throw InvalidArgumentHelper::factory(
44
                1,
45
                'array',
46
                $json
47
            );
48
        }
49
50
        $message = $message ?: Messages::MUST_NOT_BE_ARRAY_OF_OBJECTS;
51
        PHPUnit::assertFalse(static::isArrayOfObjects($json), $message);
52
    }
53
54
    private static function isArrayOfObjects($arr)
55
    {
56
        if (empty($arr)) {
57
            return true;
58
        }
59
60
        return !static::arrayIsAssociative($arr);
61
    }
62
63
    private static function arrayIsAssociative($arr)
64
    {
65
        return (array_keys($arr) !== range(0, count($arr) - 1));
66
    }
67
}
68