-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTextFormatsBehavior.php
110 lines (100 loc) · 2.89 KB
/
TextFormatsBehavior.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<?php
/**
* @copyright Copyright (c) 2014 Vitaliy Syrchikov
* @link http://syrchikov.name
*/
namespace maddoger\textformats;
use Yii;
use yii\base\Behavior;
/**
* TextFormatsBehaviour
*
* @author Vitaliy Syrchikov <[email protected]>
* @link http://syrchikov.name
* @package
*/
class TextFormatsBehavior extends Behavior
{
/**
* @var array information about text formats
* Each item is format. Key is format id, value is format description.
* Description fields:
* `label` - format label;
* `formatter` - source to html Closure `string function($model, $language)`. If is null, copy will be used;
* `widgetClass` - widget class for editor
* `widgetOptions` - widget options
*/
public $textFormats;
/**
* @var array additional options for widget
*/
public $textEditorWidgetOptions = [];
/**
* @var string default: html
*/
public $defaultTextFormat;
/**
* @param \yii\base\Component $owner
*/
public function attach($owner)
{
parent::attach($owner);
if (!$this->textFormats && isset(Yii::$app->params['textFormats'])) {
$this->textFormats = Yii::$app->params['textFormats'];
}
if (!$this->textFormats) {
$this->textFormats = [
'text' => [
'label' => 'Text',
'formatter' => function ($text, $language) {
return Yii::$app->formatter->asNtext($text);
}
],
'html' => [
'label' => 'HTML',
'default' => true,
],
];
}
if (!$this->defaultTextFormat) {
foreach ($this->textFormats as $id=>$format) {
if (!$this->defaultTextFormat) {
$this->defaultTextFormat = $id;
}
if (isset($format['default']) && $format['default']) {
$this->defaultTextFormat = $id;
break;
}
}
}
}
/**
* @param string $format
* @return array|null
*/
public function getTextFormatInfo($format)
{
if (isset($this->textFormats[$format])) {
return $this->textFormats[$format];
}
return null;
}
/**
* @param string $format
* @param string $text
* @param string $language
* @return string
*/
public function getFormattedText($format, $text, $language=null)
{
$text = trim($text);
$format = $this->getTextFormatInfo($format);
if ($format && isset($format['formatter']) && $format['formatter'] instanceof \Closure) {
if (!$language) {
$language = Yii::$app->language;
}
return call_user_func($format['formatter'], $text, $language);
}
return $text;
}
}