Test Setup Failed
Push — master ( 7a093e...068245 )
by Nick
05:17
created

ArrayQuery::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Meanbee\LibMageConf\Util;
4
5
/**
6
 * Provides a mechanism for querying the contents of an array using an xpath style query string, e.g.
7
 *
8
 * $array = [
9
 *     'product' => [
10
 *         'name' => 'Test Product'
11
 *     ]
12
 * ]
13
 *
14
 * The name of the product can be extracted using the query string 'product/name'.
15
 *
16
 * @package Meanbee\LibMageConf\Util
17
 */
18
class ArrayQuery
19
{
20
    protected $subject;
21
22
    /**
23
     * @param $array
24
     */
25
    public function __construct($array)
26
    {
27
        $this->subject = $array;
28
    }
29
30
    /**
31
     * @param $path string
32
     *
33
     * @return mixed
34
     */
35
    public function query($path)
36
    {
37
        $pathParts = explode('/', $path);
38
39
        $pointer = &$this->subject;
40
41
        foreach ($pathParts as $pathPart) {
42
            if (isset($pointer[$pathPart])) {
43
                $pointer = &$pointer[$pathPart];
44
            } else {
45
                return null;
46
            }
47
        }
48
49
        return $pointer;
50
    }
51
}