Completed
Push — master ( 33cd17...4bddcc )
by Arnold
02:40
created

Read::exists()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 8
c 1
b 0
f 0
nc 4
nop 3
dl 0
loc 17
ccs 9
cts 9
cp 1
crap 5
rs 9.6111
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Jasny\DotKey\Internal;
6
7
use Jasny\DotKey\ResolveException;
8
9
/**
10
 * Static methods to read subject using path.
11
 * @internal
12
 */
13
final class Read
14
{
15
    /**
16
     * Check if path exists in subject.
17
     *
18
     * @param object|array<string,mixed> $subject
19
     * @param string                     $path
20
     * @param string                     $delimiter
21
     * @return bool
22
     */
23 10
    public static function exists($subject, string $path, string $delimiter = '.'): bool
24
    {
25 10
        $index = Helpers::splitPath($path, $delimiter);
26
27 10
        foreach ($index as $key) {
28 10
            if (!\is_array($subject) && !\is_object($subject)) {
29 4
                return false;
30
            }
31
32 10
            $subject = Helpers::descend($subject, $key, $exists, true);
33
34 10
            if (!$exists) {
35 10
                return false;
36
            }
37
        }
38
39 10
        return true;
40
    }
41
42
    /**
43
     * Get a value from subject by path.
44
     *
45
     * @param object|array<string,mixed> $subject
46
     * @param string                     $path
47
     * @param string                     $delimiter
48
     * @return mixed
49
     * @throws ResolveException
50
     */
51 19
    public static function get($subject, string $path, string $delimiter = '.')
52
    {
53 19
        $index = Helpers::splitPath($path, $delimiter);
54
55 17
        while ($index !== []) {
56 17
            $key = \array_shift($index);
57
58 17
            if (!\is_array($subject) && !\is_object($subject)) {
59 5
                $msg = "Unable to get '$path': '%s' is of type " . \gettype($subject);
60 5
                throw ResolveException::create($msg, $path, $delimiter, $index, $key);
61
            }
62
63
            try {
64 17
                $subject = Helpers::descend($subject, $key, $exists);
65 3
            } catch (\Error $error) {
66 3
                $msg = "Unable to get '$path': error at '%s'";
67 3
                throw ResolveException::create($msg, $path, $delimiter, $index, null, $error);
68
            }
69
70 15
            if (!$exists) {
71 9
                return null;
72
            }
73
        }
74
75 9
        return $subject;
76
    }
77
}
78