Completed
Push — master ( 94c100...88acb8 )
by Andrii
02:56
created

Interpolator::interpolateArray()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 0
cts 11
cp 0
rs 9.2
c 0
b 0
f 0
cc 4
eloc 8
nc 4
nop 1
crap 20
1
<?php
2
/**
3
 * Automation tool mixed with code generator for easier continuous development.
4
 *
5
 * @link      https://github.com/hiqdev/hidev
6
 * @package   hidev
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hidev\base;
12
13
use Yii;
14
use yii\helpers\ArrayHelper;
15
16
/**
17
 * Interpolates array recursively.
18
 * @author Andrii Vasyliev <[email protected]>
19
 */
20
class Interpolator
21
{
22
    public $data;
23
24
    public function interpolate(&$data)
25
    {
26
        $this->data = &$data;
27
        $this->interpolateArray($data);
28
    }
29
30
    private function interpolateArray(&$data)
31
    {
32
        if (is_array($data)) {
33
            foreach ($data as &$item) {
34
                $this->interpolateArray($item);
35
            }
36
        } elseif (is_string($data)) {
37
            $data = preg_replace_callback('/\\$(\\w+)\\[\'(.+?)\'\\]/', function ($matches) {
38
                return $this->get($matches[1], $matches[2]);
39
            }, $data);
40
        }
41
    }
42
43
    public function get($scope, $name)
0 ignored issues
show
Coding Style introduced by
get uses the super-global variable $_ENV which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
44
    {
45
        if ($scope === 'params') {
46
            return $this->data['params'][$name];
47
        } elseif ($scope === '_ENV') {
48
            return $_ENV[$name];
49
        } else {
50
            return "\$${scope}['$name']";
51
        }
52
    }
53
54
    public function getConfig($name)
55
    {
56
        list($goal, $subname) = explode('.', $name, 2);
57
58
        return ArrayHelper::getValue(Yii::$app->get('config')->getGoal($goal), $subname);
59
    }
60
}
61