Completed
Pull Request — master (#11)
by Carlos C
03:41
created

AbstractResult::get()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace PhpCfdi\Finkok\Services;
6
7
use InvalidArgumentException;
8
use stdClass;
9
10
abstract class AbstractResult
11
{
12
    /** @var stdClass */
13
    protected $data;
14
15
    /** @var stdClass */
16
    protected $root;
17
18 56
    public function __construct(stdClass $data, string ...$meanLocation)
19
    {
20 56
        $this->data = $data;
21 56
        $root = $this->findInDescendent($data, ...$meanLocation);
22 56
        if (! $root instanceof stdClass) {
23 1
            throw new InvalidArgumentException(
24 1
                sprintf('Unable to find mean object at /%s', implode('/', $meanLocation))
25
            );
26
        }
27 56
        $this->root = $root;
28 56
    }
29
30 3
    public function rawData(): stdClass
31
    {
32 3
        return clone $this->data;
33
    }
34
35
    /**
36
     * @param stdClass|array|mixed $haystack
37
     * @param string ...$location
38
     * @return mixed
39
     */
40 56
    protected function findInDescendent($haystack, string ...$location)
41
    {
42 56
        if (0 === count($location)) {
43 56
            return $haystack;
44
        }
45 56
        $search = array_shift($location);
46 56
        if (is_array($haystack)) {
47 2
            return (isset($haystack[$search])) ? $this->findInDescendent($haystack[$search], ...$location) : null;
48
        }
49 56
        if ($haystack instanceof stdClass) {
50 56
            return (isset($haystack->{$search})) ? $this->findInDescendent($haystack->{$search}, ...$location) : null;
51
        }
52 1
        throw new InvalidArgumentException('Cannot find descendent on non-array non-object haystack');
53
    }
54
55 35
    protected function get(string $keyword): string
56
    {
57 35
        return strval($this->root->{$keyword} ?? '');
58
    }
59
}
60