1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @link https://github.com/lav45/yii2-settings |
4
|
|
|
* @copyright Copyright (c) 2016 LAV45 |
5
|
|
|
* @author Aleksey 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 yii\helpers\ArrayHelper; |
13
|
|
|
use lav45\settings\Settings; |
14
|
|
|
use lav45\settings\events\GetEvent; |
15
|
|
|
use lav45\settings\events\DecodeEvent; |
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, [$this, 'afterDecodeValue']); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @param GetEvent $event |
42
|
|
|
*/ |
43
|
4 |
|
public function beforeGetValue(GetEvent $event) |
44
|
|
|
{ |
45
|
4 |
|
$key = $event->key; |
46
|
4 |
|
if (($pos = strpos($key, '.')) === false) { |
47
|
2 |
|
$this->_originKey = null; |
48
|
|
|
} else { |
49
|
3 |
|
$this->_originKey = $key; |
50
|
3 |
|
$event->key = substr($key, 0, $pos); |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* @param DecodeEvent $event |
56
|
|
|
*/ |
57
|
4 |
|
public function afterDecodeValue(DecodeEvent $event) |
58
|
|
|
{ |
59
|
4 |
|
if ($this->_originKey === null) { |
60
|
2 |
|
return; |
61
|
|
|
} |
62
|
|
|
|
63
|
3 |
|
$key = substr($this->_originKey, strlen($event->key) + 1); |
|
|
|
|
64
|
3 |
|
if ($key !== false) { |
65
|
3 |
|
$event->value = ArrayHelper::getValue($event->value, $key, $event->default); |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* @param string|array $key |
71
|
|
|
* @param string $path |
72
|
|
|
* @param mixed $value |
73
|
|
|
* @return bool |
74
|
|
|
*/ |
75
|
1 |
|
public function replace($key, $path, $value) |
76
|
|
|
{ |
77
|
1 |
|
$data = $this->owner->get($key, []); |
78
|
1 |
|
ArrayHelper::setValue($data, $path, $value); |
|
|
|
|
79
|
1 |
|
return $this->owner->set($key, $data); |
80
|
|
|
} |
81
|
|
|
} |