Skip to content

Instantly share code, notes, and snippets.

@juniorb2ss
Last active April 7, 2016 15:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juniorb2ss/90412c1c4944350e27650a971d9b72e0 to your computer and use it in GitHub Desktop.
Save juniorb2ss/90412c1c4944350e27650a971d9b72e0 to your computer and use it in GitHub Desktop.
<?php
$dates = [
'07/04/2016', # 0
'08/04/2016', # 1
'09/04/2016', # 2
'10/04/2016', # 3
'11/04/2016', # 4
'12/04/2016', # 5
'13/04/2016', # 6
'14/04/2016', # 7
'15/04/2016', # 8
'16/04/2016', # 9
];
# organiza as datas, menor para maior
usort($dates, function ($a, $b) {
$a = DateTime::createFromFormat('d/m/Y', $a)->getTimestamp(); # date timestamp
$b = DateTime::createFromFormat('d/m/Y', $b)->getTimestamp(); # date timestamp
return $a > $b;
});
# valida data
function validateDate($date, $pattern = 'd/m/Y') {
if (!empty($date) && is_string($date)) {
$d = DateTime::createFromFormat($pattern, $date);
return $d && $d->format($pattern) === $date;
}
return false;
}
$input = '14/04/2016'; # data que usuário informou
# perguntas devem serem feitas
#
# esta data é uma data correta?
# esta data esta no array de dates presente?
$isValidInput = (validateDate($input) && in_array($input, $dates) ?: false); # data é valida e esta registrada?
if ($isValidInput) {
$inputPositionInDates = array_search($input, $dates);
# explicação
# --a data que o usuário imputar é positiva?
# --- R: Sim
# ---- O numero é ultimo no indice de datas?
# ----- R: Sim
# ------ Pega-se o numero menos 4 posições. p.x: 9 - 4, 9
# ----- R: Não
# ------ monta o range, p.x: 5 - 2, 5 + 2 = 3,4,5,6,7
# --- R: Não
# ---- Monta o range da data inicial até a posição da digitada
#
$datesPositionsToShow = (ctype_digit((string) ($inputPositionInDates - 2)) ?
(
$inputPositionInDates !== key(array_slice($dates, -1, 1, TRUE)) ?
($inputPositionInDates == key(array_slice($dates, -1, 1, TRUE)) - 1) ? range($inputPositionInDates - 3, $inputPositionInDates + 1) : array_merge(range(($inputPositionInDates - 2), $inputPositionInDates), range($inputPositionInDates, $inputPositionInDates + 2)) : range($inputPositionInDates - 4, $inputPositionInDates)
)
: array_merge(range(0, $inputPositionInDates), range($inputPositionInDates, 5))
);
$datesPositionsToShow = array_unique($datesPositionsToShow);
$datesPositionsToShow = (count($datesPositionsToShow) > 5 ? array_slice($datesPositionsToShow, 0, -1) : $datesPositionsToShow);
dd(
array_intersect_key($dates,
array_flip($datesPositionsToShow))
);
}
# debug
function dd($input) {
echo '<pre>';
die(var_dump($input));
echo '</pre>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment