forked from yiidoc/yii2-timeago
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTimeAgo.php
96 lines (85 loc) · 2.51 KB
/
TimeAgo.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
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\timeago;
use Yii;
use yii\base\InvalidConfigException;
use yii\helpers\Html;
use yii\base\Widget;
use yii\helpers\ArrayHelper;
/**
*
* @author Nghia Nguyen <[email protected]>
* @since 2.0
*/
class TimeAgo extends Widget
{
/**
* @var string The html tag to display data time. You can use abbr, span, time ...
* Default value "time"
*/
public $tag = 'time';
/**
* @var array Options attribute for html tag
*/
public $options;
/**
* @var bool
*/
public $localTitle = false;
/**
* @var string
* @see https://github.com/rmm5t/jquery-timeago/tree/master/locales
*/
public $language = 'en';
/**
* @var integer Unix timestamp
*/
public $timestamp;
private $_assetBundle;
public function init()
{
$this->options['data-toggle'] = ArrayHelper::getValue($this->options, 'data-toggle', 'timeago');
$this->registerLocale();
if($this->localTitle) {
$this->getView()->registerJs("jQuery.timeago.settings.localeTitle = true", 4, 'timeagoSetting');
}
$this->getView()->registerJs("jQuery('{$this->tag}[data-toggle=\"{$this->options['data-toggle']}\"]').timeago();", 4, 'timeago');
}
protected function registerLocale()
{
if (file_exists(Yii::getAlias($this->getAssetBundle()->sourcePath) . DIRECTORY_SEPARATOR . "locales" . DIRECTORY_SEPARATOR . "jquery.timeago.{$this->language}.js")) {
$this->getAssetBundle()->js[] = "locales/jquery.timeago.{$this->language}.js";
} else {
throw new InvalidConfigException("Language '{$this->language}' do not exist.");
}
}
protected function registerAssetBundle()
{
$this->_assetBundle = TimeAgoAsset::register($this->getView());
}
/**
* @return TimeAgoAsset
*/
public function getAssetBundle()
{
if (!$this->_assetBundle) {
$this->registerAssetBundle();
}
return $this->_assetBundle;
}
public function run()
{
if ($this->timestamp) {
echo Html::tag($this->tag,
Yii::$app->formatter->asDatetime($this->timestamp),
ArrayHelper::merge([
'datetime' => Yii::$app->formatter->asDatetime($this->timestamp, "php:c")
], $this->options)
);
}
}
}