Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
| 1 | <?php |
||
| 17 | class DateRangeValidator extends ConstraintValidator |
||
| 18 | { |
||
| 19 | |||
| 20 | /** |
||
| 21 | * @param string $message Violation message |
||
| 22 | * @param array $parameters Message parameters |
||
| 23 | */ |
||
| 24 | protected function addViolation($message, $parameters) |
||
| 39 | |||
| 40 | /** |
||
| 41 | * {@inheritDoc} |
||
| 42 | */ |
||
| 43 | public function validate($value, Constraint $constraint) |
||
| 44 | { |
||
| 45 | if (null === $value) { |
||
| 46 | return; |
||
| 47 | } |
||
| 48 | |||
| 49 | if (!($value instanceof \DateTime)) { |
||
| 50 | $this->addViolation($constraint->invalidMessage, |
||
| 51 | array('{{ value }}' => $value)); |
||
| 52 | |||
| 53 | return; |
||
| 54 | } |
||
| 55 | |||
| 56 | // evaluate now |
||
| 57 | View Code Duplication | if (null !== $constraint->min) { |
|
| 58 | $dateMin = new \DateTime($constraint->min); |
||
| 59 | |||
| 60 | if ($value < $dateMin) { |
||
| 61 | $this->addViolation($constraint->minMessage, array( |
||
| 62 | '{{ value }}' => $this->formatDate($value), |
||
| 63 | '{{ limit }}' => $this->formatDate($dateMin) |
||
| 64 | )); |
||
| 65 | } |
||
| 66 | } |
||
| 67 | |||
| 68 | View Code Duplication | if (null !== $constraint->max) { |
|
| 69 | $dateMax = new \DateTime($constraint->max); |
||
| 70 | |||
| 71 | if ($value > $dateMax) { |
||
| 72 | $this->addViolation($constraint->maxMessage, array( |
||
| 73 | '{{ value }}' => $this->formatDate($value), |
||
| 74 | '{{ limit }}' => $this->formatDate($dateMax) |
||
| 75 | )); |
||
| 76 | } |
||
| 77 | } |
||
| 78 | } |
||
| 79 | |||
| 80 | protected function formatDate($date) |
||
| 92 | |||
| 93 | /** |
||
| 94 | * @param \IntlDateFormatter $formatter |
||
| 95 | * @param \Datetime $date |
||
| 96 | * @return string |
||
| 97 | */ |
||
| 98 | protected function processDate(\IntlDateFormatter $formatter, \Datetime $date) |
||
| 102 | } |
||
| 103 |