|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* @link https://github.com/lav45/yii2-activity-logger |
|
4
|
|
|
* @copyright Copyright (c) 2017 LAV45 |
|
5
|
|
|
* @author Aleksey Loban <[email protected]> |
|
6
|
|
|
* @license http://opensource.org/licenses/BSD-3-Clause |
|
7
|
|
|
*/ |
|
8
|
|
|
|
|
9
|
|
|
namespace lav45\activityLogger; |
|
10
|
|
|
|
|
11
|
|
|
use yii\base\Behavior; |
|
12
|
|
|
use yii\helpers\ArrayHelper; |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* Class LogInfoBehavior |
|
16
|
|
|
* @package lav45\activityLogger |
|
17
|
|
|
* |
|
18
|
|
|
* ======================= Example usage ====================== |
|
19
|
|
|
* public function behaviors() |
|
20
|
|
|
* { |
|
21
|
|
|
* return [ |
|
22
|
|
|
* [ |
|
23
|
|
|
* '__class' => 'lav45\activityLogger\LogInfoBehavior', |
|
24
|
|
|
* 'template' => '{username} ({profile.email})', |
|
25
|
|
|
* // OR |
|
26
|
|
|
* //'template' => function() { |
|
27
|
|
|
* // return "{$this->username} ({$this->profile->email})"; |
|
28
|
|
|
* //}, |
|
29
|
|
|
* ] |
|
30
|
|
|
* ]; |
|
31
|
|
|
* } |
|
32
|
|
|
* ============================================================ |
|
33
|
|
|
* |
|
34
|
|
|
* @since 1.6.0 |
|
35
|
|
|
*/ |
|
36
|
|
|
class LogInfoBehavior extends Behavior |
|
37
|
|
|
{ |
|
38
|
|
|
/** |
|
39
|
|
|
* @var string|\Closure information field that will be displayed at the beginning of the list of logs for more information. |
|
40
|
|
|
* |
|
41
|
|
|
* example: '{username} ({profile.email})' |
|
42
|
|
|
* result: 'Maxim ([email protected])' |
|
43
|
|
|
* {username} is an attribute of the `owner` model |
|
44
|
|
|
* {profile.email} is the relations attribute of the `profile` model |
|
45
|
|
|
*/ |
|
46
|
|
|
public $template; |
|
47
|
|
|
/** |
|
48
|
|
|
* add log data to start |
|
49
|
|
|
*/ |
|
50
|
|
|
public bool $prepend = true; |
|
51
|
|
|
|
|
52
|
4 |
|
public function events(): array |
|
53
|
|
|
{ |
|
54
|
4 |
|
return [ |
|
55
|
4 |
|
ActiveLogBehavior::EVENT_BEFORE_SAVE_MESSAGE => 'beforeSave', |
|
56
|
4 |
|
]; |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
4 |
|
public function beforeSave(MessageEvent $event): void |
|
60
|
|
|
{ |
|
61
|
4 |
|
if ($data = $this->getInfoData()) { |
|
62
|
3 |
|
if (true === $this->prepend) { |
|
63
|
3 |
|
array_unshift($event->logData, $data); |
|
64
|
|
|
} else { |
|
65
|
1 |
|
$event->logData[] = $data; |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
4 |
|
protected function getInfoData(): ?string |
|
71
|
|
|
{ |
|
72
|
4 |
|
if (null === $this->template) { |
|
73
|
1 |
|
return null; |
|
74
|
|
|
} |
|
75
|
3 |
|
if (is_callable($this->template)) { |
|
76
|
1 |
|
return call_user_func($this->template); |
|
77
|
|
|
} |
|
78
|
2 |
|
$callback = function ($matches) { |
|
79
|
2 |
|
return ArrayHelper::getValue($this->owner, $matches[1]); |
|
80
|
2 |
|
}; |
|
81
|
2 |
|
return preg_replace_callback('/\\{([\w\._]+)\\}/', $callback, $this->template); |
|
82
|
|
|
} |
|
83
|
|
|
} |