2015-08-17 17:00:26 -07:00
< ? php
/*
* This file is part of the Symfony package .
*
* ( c ) Fabien Potencier < fabien @ symfony . com >
*
* For the full copyright and license information , please view the LICENSE
* file that was distributed with this source code .
*/
namespace Symfony\Component\Validator\Constraints ;
use Symfony\Component\Validator\Constraint ;
use Symfony\Component\Validator\Exception\UnexpectedTypeException ;
/**
* @ author Bernhard Schussek < bschussek @ gmail . com >
2018-11-23 12:29:20 +00:00
* @ author Diego Saint Esteben < diego @ saintesteben . me >
2015-08-17 17:00:26 -07:00
*/
class DateTimeValidator extends DateValidator
{
2018-11-23 12:29:20 +00:00
/**
* @ deprecated since version 3.1 , to be removed in 4.0 .
*/
2015-08-17 17:00:26 -07:00
const PATTERN = '/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/' ;
/**
* { @ inheritdoc }
*/
public function validate ( $value , Constraint $constraint )
{
if ( ! $constraint instanceof DateTime ) {
throw new UnexpectedTypeException ( $constraint , __NAMESPACE__ . '\DateTime' );
}
2018-11-23 12:29:20 +00:00
if ( null === $value || '' === $value || $value instanceof \DateTimeInterface ) {
2015-08-17 17:00:26 -07:00
return ;
}
2018-11-23 12:29:20 +00:00
if ( ! is_scalar ( $value ) && ! ( \is_object ( $value ) && method_exists ( $value , '__toString' ))) {
2015-08-17 17:00:26 -07:00
throw new UnexpectedTypeException ( $value , 'string' );
}
$value = ( string ) $value ;
2018-11-23 12:29:20 +00:00
\DateTime :: createFromFormat ( $constraint -> format , $value );
$errors = \DateTime :: getLastErrors ();
if ( 0 < $errors [ 'error_count' ]) {
$this -> context -> buildViolation ( $constraint -> message )
-> setParameter ( '{{ value }}' , $this -> formatValue ( $value ))
-> setCode ( DateTime :: INVALID_FORMAT_ERROR )
-> addViolation ();
2015-08-17 17:00:26 -07:00
return ;
}
2018-11-23 12:29:20 +00:00
foreach ( $errors [ 'warnings' ] as $warning ) {
if ( 'The parsed date was invalid' === $warning ) {
2015-08-17 17:00:26 -07:00
$this -> context -> buildViolation ( $constraint -> message )
-> setParameter ( '{{ value }}' , $this -> formatValue ( $value ))
-> setCode ( DateTime :: INVALID_DATE_ERROR )
-> addViolation ();
2018-11-23 12:29:20 +00:00
} elseif ( 'The parsed time was invalid' === $warning ) {
2015-08-17 17:00:26 -07:00
$this -> context -> buildViolation ( $constraint -> message )
-> setParameter ( '{{ value }}' , $this -> formatValue ( $value ))
-> setCode ( DateTime :: INVALID_TIME_ERROR )
-> addViolation ();
} else {
2018-11-23 12:29:20 +00:00
$this -> context -> buildViolation ( $constraint -> message )
2015-08-17 17:00:26 -07:00
-> setParameter ( '{{ value }}' , $this -> formatValue ( $value ))
2018-11-23 12:29:20 +00:00
-> setCode ( DateTime :: INVALID_FORMAT_ERROR )
2015-08-17 17:00:26 -07:00
-> addViolation ();
}
}
}
}