Completed
Push — master ( 7d2660...4131bf )
by Loban
02:42
created

BaseArrayHelper   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 4
lcom 0
cbo 1
dl 0
loc 67
ccs 12
cts 12
cp 1
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B setValue() 0 22 4
1
<?php
2
/**
3
 * @link https://github.com/LAV45/yii2-settings
4
 * @copyright Copyright (c) 2016 LAV45
5
 * @author Alexey Loban <[email protected]>
6
 * @license http://opensource.org/licenses/BSD-3-Clause
7
 */
8
9
namespace lav45\settings\helpers;
10
11
/**
12
 * Class BaseArrayHelper
13
 * @package lav45\settings\helpers
14
 */
15
class BaseArrayHelper extends \yii\helpers\BaseArrayHelper
16
{
17
    /**
18
     * ```php
19
     *  $array = [
20
     *      'key' => [
21
     *          'in' => [
22
     *              'val1',
23
     *              'key' => 'val'
24
     *          ]
25
     *      ]
26
     *  ];
27
     * ```
28
     *
29
     * The result of `ArrayHelper::setValue($array, 'key.in.0', ['arr' => 'val']);` could be like the following:
30
     *
31
     * ```php
32
     *  [
33
     *      'key' => [
34
     *          'in' => [
35
     *              ['arr' => 'val'],
36
     *              'key' => 'val'
37
     *          ]
38
     *      ]
39
     *  ]
40
     *
41
     * ```
42
     * The result of `ArrayHelper::setValue($array, 'key.in', ['arr' => 'val']);` could be like the following:
43
     *
44
     * ```php
45
     *  [
46
     *      'key' => [
47
     *          'in' => [
48
     *              'arr' => 'val'
49
     *          ]
50
     *      ]
51
     *  ]
52
     * ```
53
     *
54
     * @param array $array
55
     * @param string $key
56
     * @param mixed $value
57
     * @return array
58
     */
59 14
    public static function setValue(array $array, $key, $value)
60
    {
61 14
        if (($pos = strpos($key, '.')) !== false) {
62 11
            $left_key = substr($key, 0, $pos);
63 11
            $right_key = substr($key, $pos + 1);
64
65 11
            if (isset($array[$left_key])) {
66 7
                $data = $array[$left_key];
67 7
                if (!is_array($data)) {
68 7
                    $data = [$data];
69
                }
70
            } else {
71 4
                $data = [];
72
            }
73
74 11
            $array[$left_key] = static::setValue($data, $right_key, $value);
75
        } else {
76 14
            $array[$key] = $value;
77
        }
78
79 14
        return $array;
80
    }
81
}