1 <?php
2 3 4 5 6 7 8 9 10
11 class WhTimeAgoFormatter extends CFormatter
12 {
13 14 15
16 public $locale;
17
18 19 20
21 public $allowFuture = true;
22
23 24 25
26 private $data;
27
28
29 30 31
32 public function init()
33 {
34 if (empty($this->locale)) {
35 $this->locale = Yii::app()->language;
36 }
37 $this->setLocale($this->locale);
38 parent::init();
39 }
40
41 42 43 44
45 private function setLocale($locale)
46 {
47 $path = __DIR__ . DIRECTORY_SEPARATOR .
48 'assets' . DIRECTORY_SEPARATOR .
49 'php' . DIRECTORY_SEPARATOR .
50 'locale' . DIRECTORY_SEPARATOR . $locale . '.php';
51
52 if (!file_exists($path)) {
53 $this->locale = 'en';
54 $path = __DIR__ . DIRECTORY_SEPARATOR .
55 'assets' . DIRECTORY_SEPARATOR .
56 'php' . DIRECTORY_SEPARATOR .
57 'locale' . DIRECTORY_SEPARATOR . $this->locale . '.php';
58 }
59 $this->data = require_once($path);
60 }
61
62 63 64 65 66
67 public function formatTimeago($value)
68 {
69 if ($value instanceof DateTime) {
70 $value = date_timestamp_get($value);
71
72 } else if (!is_numeric($value) && is_string($value)) {
73 $value = strtotime($value);
74 }
75
76 return $this->inWords((time() - $value));
77 }
78
79 80 81 82 83
84 public function inWords($seconds)
85 {
86 $prefix = $this->data['prefixAgo'];
87 $suffix = $this->data['suffixAgo'];
88 if ($this->allowFuture && $seconds < 0) {
89 $prefix = $this->data['prefixFromNow'];
90 $suffix = $this->data['suffixFromNow'];
91 }
92
93 $seconds = abs($seconds);
94
95 $minutes = $seconds / 60;
96 $hours = $minutes / 60;
97 $days = $hours / 24;
98 $years = $days / 365;
99
100 $separator = $this->data['wordSeparator'] === null ? " " : $this->data['wordSeparator'];
101
102 $wordsConds = array(
103 $seconds < 45,
104 $seconds < 90,
105 $minutes < 45,
106 $minutes < 90,
107 $hours < 24,
108 $hours < 42,
109 $days < 30,
110 $days < 45,
111 $days < 365,
112 $years < 1.5,
113 true
114 );
115
116 $wordResults = array(
117 array('seconds', round($seconds)),
118 array('minute', 1),
119 array('minutes', round($minutes)),
120 array('hour', 1),
121 array('hours', round($hours)),
122 array('day', 1),
123 array('days', round($days)),
124 array('month', 1),
125 array('months', round($days / 30)),
126 array('year', 1),
127 array('years', round($years))
128 );
129
130 for ($i = 0; $i < $count = count($wordsConds); ++$i) {
131 if ($wordsConds[$i]) {
132 $key = $wordResults[$i][0];
133 $number = $wordResults[$i][1];
134 if (is_array($this->data[$key]) && is_callable($this->data['rules'])) {
135 $n = call_user_func($this->data['rules'], $wordResults[$i][1]);
136 $message = $this->data[$key][$n];
137 } else {
138 $message = $this->data[$key];
139 }
140 return trim(implode($separator, array($prefix, preg_replace('/%d/i', $number, $message), $suffix)));
141 }
142 }
143 }
144
145 }