This repository has been archived by the owner on Apr 26, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 42
/
Dt.php
383 lines (333 loc) · 13.4 KB
/
Dt.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
<?php
namespace php_rutils;
use php_rutils\struct\TimeParams;
/**
* Russian dates without locales
* Class Dt
* @package php_rutils
*/
class Dt
{
public static $PREFIX_IN = "через"; //Prefix 'in' (i.e. B{in} three hours)
public static $SUFFIX_AGO = "назад"; //Prefix 'ago' (i.e. three hours B{ago})
private static $_DAY_NAMES = array(
array('пн', 'понедельник', 'понедельник', "в\xC2\xA0"),
array('вт', 'вторник', 'вторник', "во\xC2\xA0"),
array('ср', 'среда', 'среду', "в\xC2\xA0"),
array('чт', 'четверг', 'четверг', "в\xC2\xA0"),
array('пт', 'пятница', 'пятницу', "в\xC2\xA0"),
array('сб', 'суббота', 'субботу', "в\xC2\xA0"),
array('вск', 'воскресенье', 'воскресенье', "в\xC2\xA0")
); //Day alternatives (i.e. one day ago -> yesterday)
private static $_MONTH_NAMES = array(
array("янв", "январь", "января"),
array("фев", "февраль", "февраля"),
array("мар", "март", "марта"),
array("апр", "апрель", "апреля"),
array("май", "май", "мая"),
array("июн", "июнь", "июня"),
array("июл", "июль", "июля"),
array("авг", "август", "августа"),
array("сен", "сентябрь", "сентября"),
array("окт", "октябрь", "октября"),
array("ноя", "ноябрь", "ноября"),
array("дек", "декабрь", "декабря"),
); //Forms (1, 2, 5) for noun 'day'
private static $_PAST_ALTERNATIVES = array("вчера", "позавчера");
private static $_YEAR_VARIANTS = array("год", "года", "лет"); //Forms (1, 2, 5) for noun 'year'
private static $_MONTH_VARIANTS = array("месяц", "месяца", "месяцев");
private static $_DAY_VARIANTS = array("день", "дня", "дней");
private static $_HOUR_VARIANTS = array("час", "часа", "часов");
private static $_MINUTE_VARIANTS = array("минуту", "минуты", "минут");
private static $_DISTANCE_FIELDS = array('y', 'm', 'd', 'h', 'i');
/**
* Russian \DateTime::format
* @param array|\php_rutils\struct\TimeParams $params Params structure
* @return string Date/time string representation
*/
public function ruStrFTime($params = null)
{
//Params handle
if ($params === null) {
$params = new TimeParams();
} elseif (is_array($params)) {
$params = TimeParams::create($params);
} else {
$params = clone $params;
}
if ($params->date === null) {
$params->date = new \DateTime();
} else {
$params->date = $this->_processDateTime($params->date);
}
if (is_string($params->timezone)) {
$params->timezone = new \DateTimeZone($params->timezone);
}
if ($params->timezone) {
$params->date->setTimezone($params->timezone);
}
//Format processing
$weekday = $params->date->format('N') - 1;
$month = $params->date->format('n') - 1;
$prepos = $params->preposition ? self::$_DAY_NAMES[$weekday][3] : '';
$monthIdx = $params->monthInflected ? 2 : 1;
$dayIdx = ($params->dayInflected || $params->preposition) ? 2 : 1;
$search = array('D', 'l', 'M', 'F');
$replace = array(
$prepos.self::$_DAY_NAMES[$weekday][0],
$prepos.self::$_DAY_NAMES[$weekday][$dayIdx],
self::$_MONTH_NAMES[$month][0],
self::$_MONTH_NAMES[$month][$monthIdx],
);
//for russian typography standard,
//1 April 2007, but 01.04.2007
if (strpos($params->format, 'F') !== false || strpos($params->format, 'M') !== false) {
$search[] = 'd';
$replace[] = 'j';
}
$params->format = str_replace($search, $replace, $params->format);
//Create date/time string
return $params->date->format($params->format);
}
/**
* Process mixed format date
* @param mixed $dateTime
* @return \DateTime
* @throws \InvalidArgumentException
*/
private function _processDateTime($dateTime)
{
if (is_numeric($dateTime)) {
$timestamp = $dateTime;
$dateTime = new \DateTime();
$dateTime->setTimestamp($timestamp);
} elseif (empty($dateTime)) {
throw new \InvalidArgumentException('Date/time is empty');
} elseif (is_string($dateTime)) {
$dateTime = new \DateTime($dateTime);
}
if (!($dateTime instanceof \DateTime)) {
throw new \InvalidArgumentException('Incorrect date/time type');
}
return $dateTime;
}
/**
* Represents distance of time in words
* @param string|int|\DateTime $toTime Source time
* @param string|int|\DateTime $fromTime Target time
* @param int $accuracy Level of accuracy (year, month, day, hour, minute), default=year
* @throws \InvalidArgumentException
* @throws \RuntimeException
* @return string Distance of time in words
*/
public function distanceOfTimeInWords($toTime, $fromTime = null, $accuracy = RUtils::ACCURACY_YEAR)
{
$accuracy = (int)$accuracy;
if ($accuracy < 1 || $accuracy > 5) {
throw new \InvalidArgumentException('Wrong accuracy value (must be 1..5)');
}
/* @var $toTime \DateTime */
/* @var $fromTime \DateTime */
/* @var $timeZone \DateTimeZone */
/* @var $fromCurrent bool */
list($toTime, $fromTime, $timeZone, $fromCurrent) = $this->_processFunctionParams($toTime, $fromTime);
$interval = $toTime->diff($fromTime);
//if diff less than one minute
if ($interval->days == 0 && $interval->h == 0 && $interval->i == 0) {
if ($interval->invert) {
$result = 'менее чем через минуту';
} else {
$result = 'менее минуты назад';
}
return $result;
}
//create distance table
$distanceData = $this->_createDistanceData($interval);
$words = $this->_getResultWords($accuracy, $distanceData);
//check short result
if ($fromCurrent && min($accuracy, sizeof($words)) == 1) {
//if diff expressed in one word
$result = $this->_getOneWordResult($interval);
if ($result) {
return $result;
} elseif ($interval->days < 3) {
//if diff 1 or 2 days
$result = $this->_getTwoDaysResult($interval, $toTime, $timeZone);
if ($result) {
return $result;
}
}
}
//general case
$result = implode(', ', $words);
return $this->_addResultSuffix($interval, $result);
}
private function _processFunctionParams($toTime, $fromTime)
{
$toTime = $this->_processDateTime($toTime);
$timeZone = $toTime->getTimezone();
$fromCurrent = false;
if ($fromTime === null) {
$fromTime = new \DateTime('now', $timeZone);
$fromCurrent = true;
} else {
$fromTime = $this->_processDateTime($fromTime);
}
return array($toTime, $fromTime, $timeZone, $fromCurrent);
}
private function _createDistanceData(\DateInterval $interval)
{
$distanceData = array(); //table of word representations
$numeral = RUtils::numeral();
$years = $interval->y;
if ($years) {
$distanceData['y'] = $numeral->getPlural($years, self::$_YEAR_VARIANTS);
}
$months = $interval->m;
if ($months) {
$distanceData['m'] = $numeral->getPlural($months, self::$_MONTH_VARIANTS);
}
$days = $interval->d;
if ($days) {
$distanceData['d'] = $numeral->getPlural($days, self::$_DAY_VARIANTS);
}
$hours = $interval->h;
if ($hours) {
$distanceData['h'] = $numeral->getPlural($hours, self::$_HOUR_VARIANTS);
}
$minutes = $interval->i;
if ($minutes) {
$distanceData['i'] = $numeral->getPlural($minutes, self::$_MINUTE_VARIANTS);
}
return $distanceData;
}
private function _getYearResult(array $distanceData)
{
return $this->_getLevelResult('y', $distanceData);
}
private function _getMonthResult(array $distanceData)
{
list($words, $borderField) = $this->_getYearResult($distanceData);
return $this->_getLevelResult('m', $distanceData, $words, $borderField);
}
private function _getDaysResult(array $distanceData)
{
list($words, $borderField) = $this->_getMonthResult($distanceData);
return $this->_getLevelResult('d', $distanceData, $words, $borderField);
}
private function _getHoursResult(array $distanceData)
{
list($words, $borderField) = $this->_getDaysResult($distanceData);
return $this->_getLevelResult('h', $distanceData, $words, $borderField);
}
private function _getMinutesResult(array $distanceData)
{
list($words, $borderField) = $this->_getHoursResult($distanceData);
return $this->_getLevelResult('i', $distanceData, $words, $borderField);
}
private function _getLevelResult($fieldCode, array $distanceData, array $words = array(), $borderField = -1)
{
$curPos = array_search($fieldCode, self::$_DISTANCE_FIELDS);
if ($borderField >= $curPos) {
return array($words, $borderField);
}
$nextField = $borderField + 1;
$length = sizeof(self::$_DISTANCE_FIELDS);
for ($i = $nextField; $i < $length; ++$i) {
$field = self::$_DISTANCE_FIELDS[$i];
if ($borderField != -1 && $i > $curPos) {
break;
} elseif (isset($distanceData[$field])) {
$words[] = $distanceData[$field];
$borderField = $i;
break;
}
}
return array($words, $borderField);
}
private function _getOneWordResult(\DateInterval $interval)
{
$result = null;
if ($interval->days == 0 && $interval->h == 0 && $interval->i == 1) {
$result = 'минуту';
} elseif ($interval->days == 0 && $interval->h == 1) {
$result = 'час';
} elseif ($interval->y == 0 && $interval->m == 1) {
$result = 'месяц';
} elseif ($interval->y == 1) {
$result = 'год';
}
if ($result) {
$result = $this->_addResultSuffix($interval, $result);
}
return $result;
}
/**
* Add suffix or Postfix to string.
* @param \DateInterval $interval
* @param $result string
* @return string modified $result.
*/
private function _addResultSuffix(\DateInterval $interval, $result)
{
return $interval->invert ? self::$PREFIX_IN."\xC2\xA0".$result : $result."\xC2\xA0".self::$SUFFIX_AGO;
}
private function _getTwoDaysResult(\DateInterval $interval, \DateTime $toTime, \DateTimeZone $timeZone = null)
{
$result = null;
$days = $interval->days;
if ($interval->invert == 0 && ($days == 1 || $days == 2)) {
$variant = $days - 1;
$result = self::$_PAST_ALTERNATIVES[$variant];
} elseif ($interval->invert && ($days == 0 || $days == 1)) {
$tomorrow = new \DateTime('today', $timeZone);
$tomorrow->add(new \DateInterval('P1D'));
$afterTomorrow = new \DateTime('today', $timeZone);
$afterTomorrow->add(new \DateInterval('P2D'));
if ($toTime >= $tomorrow && $toTime < $afterTomorrow) {
$result = 'завтра';
} elseif ($days == 1 && $toTime >= $afterTomorrow) {
$result = 'послезавтра';
}
}
return $result;
}
private function _getResultWords($accuracy, $distanceData)
{
switch ($accuracy) {
case RUtils::ACCURACY_YEAR:
list($words,) = $this->_getYearResult($distanceData);
break;
case RUtils::ACCURACY_MONTH:
list($words,) = $this->_getMonthResult($distanceData);
break;
case RUtils::ACCURACY_DAY:
list($words,) = $this->_getDaysResult($distanceData);
break;
case RUtils::ACCURACY_HOUR:
list($words,) = $this->_getHoursResult($distanceData);
break;
case RUtils::ACCURACY_MINUTE:
list($words,) = $this->_getMinutesResult($distanceData);
break;
default:
throw new \RuntimeException("Unexpected accuracy level: $accuracy");
}
return $words;
}
/**
* Calculates age
* @param string|int|\DateTime $birthDate Date of birth
* @throws \InvalidArgumentException
* @return int Full years age
*/
public function getAge($birthDate)
{
$birthDate = $this->_processDateTime($birthDate);
$interval = $birthDate->diff(new \DateTime());
if ($interval->invert) {
throw new \InvalidArgumentException('Birth date is in future');
}
return $interval->y;
}
}