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\behaviors; |
10
|
|
|
|
11
|
|
|
use yii\base\Behavior; |
12
|
|
|
use lav45\settings\Settings; |
13
|
|
|
use lav45\settings\events\GetEvent; |
14
|
|
|
use lav45\settings\events\DecodeEvent; |
15
|
|
|
use lav45\settings\helpers\ArrayHelper; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Class QuickAccessBehavior |
19
|
|
|
* @package lav45\settings\behaviors |
20
|
|
|
* |
21
|
|
|
* @property Settings $owner |
22
|
|
|
*/ |
23
|
|
|
class QuickAccessBehavior extends Behavior |
24
|
|
|
{ |
25
|
|
|
/** |
26
|
|
|
* @var string |
27
|
|
|
*/ |
28
|
|
|
private $_originKey; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @param Settings $owner |
32
|
|
|
*/ |
33
|
4 |
|
public function attach($owner) |
34
|
|
|
{ |
35
|
4 |
|
parent::attach($owner); |
36
|
4 |
|
$owner->on(Settings::EVENT_BEFORE_GET, [$this, 'beforeGetValue'], null, false); |
37
|
4 |
|
$owner->on(Settings::EVENT_AFTER_DECODE_VALUE, [$this, 'afterDecodeValue']); |
38
|
4 |
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @param GetEvent $event |
42
|
|
|
*/ |
43
|
4 |
|
public function beforeGetValue(GetEvent $event) |
44
|
|
|
{ |
45
|
4 |
|
if (!is_string($event->key)) { |
46
|
|
|
return; |
47
|
|
|
} |
48
|
4 |
|
$key = $event->key; |
49
|
4 |
|
if (($pos = strpos($key, '.')) === false) { |
50
|
2 |
|
$this->_originKey = null; |
51
|
|
|
} else { |
52
|
3 |
|
$this->_originKey = $key; |
53
|
3 |
|
$event->key = substr($key, 0, $pos); |
54
|
|
|
} |
55
|
4 |
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* @param DecodeEvent $event |
59
|
|
|
*/ |
60
|
3 |
|
public function afterDecodeValue(DecodeEvent $event) |
61
|
|
|
{ |
62
|
3 |
|
if (!is_string($event->key)) { |
63
|
|
|
return; |
64
|
|
|
} |
65
|
3 |
|
if ($this->_originKey === null) { |
66
|
2 |
|
return; |
67
|
|
|
} |
68
|
|
|
|
69
|
2 |
|
$key = substr($this->_originKey, strlen($event->key) + 1); |
70
|
2 |
|
if ($key !== false) { |
71
|
2 |
|
$event->value = ArrayHelper::getValue($event->value, $key, $event->default); |
72
|
|
|
} |
73
|
2 |
|
} |
74
|
|
|
|
75
|
|
|
/** |
76
|
|
|
* @param string|array $key |
77
|
|
|
* @param string $path |
78
|
|
|
* @param mixed $value |
79
|
|
|
* @return bool |
80
|
|
|
*/ |
81
|
1 |
|
public function replace($key, $path, $value) |
82
|
|
|
{ |
83
|
1 |
|
$data = $this->owner->get($key, []); |
84
|
1 |
|
$data = ArrayHelper::setValue($data, $path, $value); |
85
|
1 |
|
return $this->owner->set($key, $data); |
86
|
|
|
} |
87
|
|
|
} |