-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDateFilter.php
414 lines (346 loc) · 11 KB
/
DateFilter.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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
<?php declare(strict_types = 1);
/**
* @file DateFilter.php
* @author Giorgio Sanfilippo <[email protected]>
* @package DoPhp
* @brief Classes for handling Date Filter
*/
namespace dophp;
/**
* Define a date filter
*
*/
class DateFilter implements \JsonSerializable {
const PRECISON_Y = 'y';
const PRECISON_MY = 'my';
const PRECISON_DMY = 'dmy';
const DATE_SEPARATORS = ['.', '-', '/'];
/// The date where filter start
protected $_startDate = null;
/// The date where filter end
protected $_endDate = null;
// true if the dateFilter is valid
protected $_valid = true;
/**
* Constructs the DateFilter
*
* @param $search string: The string defining the filter parameters ('10.2018,11.2018' '19' '01.10.2010')
* @param $divider The char/string used to separate two dates from a period
*/
public function __construct(string $search, string $divider=',') {
// Parse the $search string, splitting in 1 or 2 dates
$count = substr_count($search, $divider);
switch($count) {
case 0:
$startDate = trim($search);
$endDate = null;
break;
case 1:
list($startDate, $endDate) = explode($divider, trim($search));
$startDate = trim($startDate);
$endDate = trim($endDate);
break;
default:
$this->_valid = false;
return;
}
// The filter set automatically the missing date, calculating it from the given date and precision
// If precion it's PRECISON_DMY, leave the missing date as null, to implement 'from' and 'until'
if((is_null($startDate) || $startDate == '') && (is_null($endDate) || $endDate == ''))
throw new \InvalidArgumentException('Date filter need at least one date');
if(is_null($startDate) || $startDate == '') {
$this->_startDate = self::strToDateWithPrecision($endDate, true);
if (!is_null($this->_startDate) && $this->_startDate->getPrecision() == self::PRECISON_DMY)
$this->_startDate = null;
}
else
$this->_startDate = self::strToDateWithPrecision($startDate, true);
if(is_null($endDate) || $endDate == '') {
$this->_endDate = self::strToDateWithPrecision($startDate, false);
if (!is_null($this->_endDate) && $this->_endDate->getPrecision() == self::PRECISON_DMY)
$this->_endDate = null;
}
else
$this->_endDate = self::strToDateWithPrecision($endDate, false);
if(is_null($this->_startDate) && is_null($this->_endDate))
$this->_valid = false;
}
public function getStartDate(): ?DateWithPrecision {
return $this->_startDate;
}
public function getEndDate(): ?DateWithPrecision {
return $this->_EndDate;
}
public function isValid(): bool{
return $this->_valid;
}
/**
* Returns the date separator found in the given unformatted $date
*
* @param $date string: The unformatted filter date (eg. 2018, 10.2018, 01-11-2018)
*
* @return string The found date separator, if it is in DATE_SEPARATORS array, false otherwise
*
*/
protected static function getDateSeparatot(string $date) {
foreach (self::DATE_SEPARATORS as $ds)
if (strpos($date, $ds) !== false )
return $ds;
return false;
}
/**
* Returns an array of strings representing the given unformatted $date
*
* @param $date string: The unformatted filter date (eg. 2018, 10.2018, 01-11-2018)
*
* @return array An array of strings representing the give date
*
*/
protected static function getSplittedDate(string $date): array {
$ds = self::getDateSeparatot($date);
if($ds)
return explode($ds, $date);
else
return [$date];
}
/**
* Returns date precision as string from given $date
*
* Supported date formats
* 18, 2018
* 1.18, 10.18, 1.2018, 10.2018
* 1.1.18, 1.10.18, 10.1.18, 10.10.18
* 1.1.2018, 1.10.2018, 10.1.2018, 10.10.2018
*
* @param $date string: The unformatted filter date (eg. 2018, 10.2018, 01-11-2018)
*
* @return string date precision as string
* @throws WrongFormatException
*/
protected static function getDatePrecision(string $date): string {
$separator = self::getDateSeparatot($date);
if(!$separator)
return self::PRECISON_Y;
$count = substr_count($date, $separator);
switch ($count) {
case 1:
return self::PRECISON_MY;
break;
case 2:
return self::PRECISON_DMY;
break;
default:
throw new WrongFormatException('Wrong Date Format');
}
}
/**
* Returns true if the given date it's well formed
*
* eg. true: '19', '1.18', '2-10-2018'
* eg. false: '9', 'a', '10.209', '01-011-2019'
*
* @param string $date: The date to check validity (eg. 2018, 10.2018, 01-11-2018)
* @param bool $precision: the date precision
*
* @return bool true if it's a supported date format, false otherwise
*
*/
protected static function isValidYear(string $year) : bool {
$len = \strlen($year);
// Check if the year is numeric and it's 2 o 4 digit
if(($len != 2 && $len != 4 ) || !\is_numeric($year))
return false;
return true;
}
protected static function isValidMonth(string $month) : bool {
// Check if $month is numeric
if(!\is_numeric($month))
return false;
// Check if the $month is 2 o 4 digit
$len = \strlen($month);
if($len < 1 || $len >2 )
return false;
$monthNum = \intval($month);
if($monthNum < 1 || $monthNum > 12)
return false;
return true;
}
protected static function isValidDay(string $day) : bool {
// Check if $day is numeric
if(!\is_numeric($day))
return false;
// Check if the $day is 2 o 4 digit
$len = \strlen($day);
if($len < 1 || $len >2 )
return false;
$dayNum = \intval($day);
if($dayNum < 1 || $dayNum > 31)
return false;
return true;
}
/**
* Returns true if the given $date it's formatted like the supported formats
*
* @param string $date: The date to be validated (eg. 2018, 10.2018, 01-11-2018)
* @param string $precision: The precisiono of the given $date
*
* @return bool: true if all the parts of the $date are in the right format
*
*/
protected static function validateFormat($date, $precision) : bool {
switch($precision) {
case self::PRECISON_Y :
return self::isValidYear($date);
break;
case self::PRECISON_MY :
$splitDate = self::getSplittedDate($date);
return self::isValidMonth($splitDate[0]) && self::isValidYear($splitDate[1]);
break;
case self::PRECISON_DMY :
$splitDate = self::getSplittedDate($date);
return
self::isValidDay($splitDate[0]) &&
self::isValidMonth($splitDate[1]) &&
self::isValidYear($splitDate[2]);
break;
default :
return false;
}
}
/**
* Returns a new DateTime object from given string $date, according to $isStart parameter
*
* @param string $date: The unformatted filter date (eg. 2018, 10.2018, 01-11-2018)
* @param bool $isStart: It's true if the $date have to be considered a start date
*
* @return DateTime object from the given $date according to $isStart parameter or
* null if $date format is wrong or not supported
*
*/
public static function formatDate(string $date, bool $isStart = true): ?\DateTime {
// Supported date formats
// 18, 2018, 1.18, 10.18, 1.2018, 10.2018
// 1.1.18, 1.10.18, 10.1.18, 10.10.18
// 1.1.2018, 1.10.2018, 10/1/2018, 10-10-2018
$df = self::getDatePrecision($date);
// Check if $date it's well formed (eg. not well formed date 201.1.2019)
if(!self::validateFormat($date, $df))
return null;
switch($df) {
case self::PRECISON_Y :
$year = $date;
if(strlen($year) == 2)
$year = \DateTime::createFromFormat('y', $year)->format('Y');
return $isStart ?
new \DateTime('first day of January '.$year) :
new \DateTime('last day of December '.$year);
break;
case self::PRECISON_MY :
$splitDate = self::getSplittedDate($date);
$year = $splitDate[1];
if(strlen($year) == 2)
$year = \DateTime::createFromFormat('y', $year)->format('Y');
$monthName = \DateTime::createFromFormat('!m', $splitDate[0])->format('F');
return $isStart ?
new \DateTime('first day of '.$monthName.' '. $year) :
new \DateTime('last day of '.$monthName.' '. $year);
break;
case self::PRECISON_DMY :
$splitDate = self::getSplittedDate($date);
$year = $splitDate[2];
if(strlen($year) == 2)
$year = \DateTime::createFromFormat('y', $year)->format('Y');
$monthName = \DateTime::createFromFormat('!m', $splitDate[1])->format('F');
return \DateTime::createFromFormat('j-F-Y', $splitDate[0].'-'.$monthName.'-'.$year);
break;
}
throw new \dophp\NotImplementedException("Unsupported format $df");
}
/**
* Returns a new DateWithPrecision object from given string $date, according to $isStart parameter
*
* @param $date string: The unformatted filter date (eg. 2018, 10.2018, 01-11-2018)
* @param $isStart bool: It's true if the $date have to be considered a start date
*
* @return DateWithPrecision or null on error
*
*/
public static function strToDateWithPrecision(string $date, bool $isStart): ?DateWithPrecision {
$prec = self::getDatePrecision($date);
$formattedDate = self::formatDate($date, $isStart);
return !is_null($formattedDate) ? new DateWithPrecision($formattedDate, $prec) : null;
}
public function jsonSerialize() {
$json = array();
foreach($this as $key => $value) {
$json[$key] = $value;
}
return $json;
}
/**
* Returns the SQL code and params for building a date filter
*
* When this is not valid or empty, returns null instead of SQL
*
* @param $columnName string: The column to search into (already quoted if needed)
* @param $parPrefix string: The prefix for parameters (must begin with ':')
*
* @return [ string: sql or null, array: associative array of params ]
*/
public function getSqlSearchFilter(string $columnName, string $parPrefix=':dateFilter_'): array {
if( ! $this->isValid() )
return [ null, [] ];
if( $this->_startDate && $this->_endDate )
return [
"$columnName BETWEEN {$parPrefix}start AND {$parPrefix}end",
[ "{$parPrefix}start" => $this->_startDate, "{$parPrefix}end" => $this->_endDate ]
];
if( $this->_startDate )
return [
"$columnName >= {$parPrefix}start",
[ "{$parPrefix}start" => $this->_startDate ]
];
if( $this->endDate )
return [
"$columnName <= {$parPrefix}end",
[ "{$parPrefix}end" => $this->_endDate ]
];
// Empty / no filter
return [ null, [] ];
}
}
/**
* Define a date class with precision level
*
*/
class DateWithPrecision extends \dophp\Date implements \JsonSerializable {
const SUPPORTED_PRECISON = [
DateFilter::PRECISON_Y,
DateFilter::PRECISON_MY,
DateFilter::PRECISON_DMY
];
protected $_precision;
public function __construct(\DateTime $date, string $precision) {
if(!in_array($precision, self::SUPPORTED_PRECISON))
throw new UnsupportedPrecisionException();
$this->_precision = $precision;
parent::__construct($date);
}
public function getPrecision() {
return $this->_precision;
}
public function setPrecision($precision) {
if(!in_array($precision, self::SUPPORTED_PRECISON))
throw new UnsupportedPrecisionException();
$this->_precision = $precision;
}
public function jsonSerialize() {
$json = array();
foreach($this as $key => $value) {
$json[$key] = $value;
}
return $json;
}
}
class UnsupportedPrecisionException extends \Exception {}
class WrongFormatException extends \Exception {}