Skip to content

Instantly share code, notes, and snippets.

@joubertredrat
Last active August 29, 2015 14:13
Show Gist options
  • Save joubertredrat/f1c9482b8d018ad27519 to your computer and use it in GitHub Desktop.
Save joubertredrat/f1c9482b8d018ad27519 to your computer and use it in GitHub Desktop.
<?php
/**
* Valida os tipos de dados recebidos no método __set().
*
* @param mixed $valor Valor a ser validado.
* @param string $tipo Tipo de dado a ser validado.
* @return bool Retorna true caso seja um tipo válido ou false caso contra.
*/
public static function validarTipo($valor, $tipo)
{
switch ($tipo)
{
case 'string':
$retorno = is_string($valor);
break;
case 'integer':
$retorno = filter_var($valor, FILTER_VALIDATE_INT) !== false;
break;
case 'float':
$retorno = filter_var($valor, FILTER_VALIDATE_FLOAT) !== false;
break;
case 'boolean':
$retorno = is_bool($valor);
break;
case 'datetime':
if (self::validarTipo(substr($valor, 0, 4), 'datetime_year'))
{
DateTime::createFromFormat('Y-m-d H:i:s', $valor);
$validar = DateTime::getLastErrors();
$retorno = ($validar['warning_count'] == 0 && $validar['error_count'] == 0);
}
else
$retorno = false;
break;
case 'datetime_year':
if ($valor == '0000')
$retorno = true;
else
$retorno = filter_var((int) $valor, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1000, 'max_range' => 9999]]) !== false;
break;
case 'datetime_date':
if ($valor === '0000-00-00')
$retorno = true;
else
$retorno = self::validarTipo($valor.' '.date('H:i:s'), 'datetime');
break;
case 'datetime_time':
if ($valor === '00:00:00')
$retorno = true;
else
$retorno = self::validarTipo(date('Y-m-d').' '.$valor, 'datetime');
break;
case 'datetime_timestamp':
$retorno = filter_var((int) $valor, FILTER_VALIDATE_INT, ['options' => ['min_range' => -2147483647, 'max_range' => 2147483647]]) !== false;
break;
default:
$retorno = false;
break;
}
return $retorno;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment