Skip to content

Instantly share code, notes, and snippets.

@xabbuh
Last active March 20, 2020 07:40
Show Gist options
  • Save xabbuh/ac96bb561edd7f6dbc1c22cccd0b6816 to your computer and use it in GitHub Desktop.
Save xabbuh/ac96bb561edd7f6dbc1c22cccd0b6816 to your computer and use it in GitHub Desktop.
<?php
namespace App\Validator;
use Symfony\Component\Validator\Constraints\Range;
use Symfony\Component\Validator\Constraints\RangeValidator;
class YearRange extends Range
{
public function __construct($options)
{
$options['max'] = date('Y');
parent::__construct($options);
}
public function validatedBy(): string
{
return RangeValidator::class;
}
}
@OskarStark
Copy link

I extended this a bit, to always allow the current year as max:

<?php

declare(strict_types=1);

namespace App\Validator\Constraints;

use Symfony\Component\Validator\Constraints\Range;
use Symfony\Component\Validator\Constraints\RangeValidator;
use Symfony\Component\Validator\Exception\ConstraintDefinitionException;

/**
 * @Annotation
 * @Target({"PROPERTY", "METHOD", "ANNOTATION"})
 */
final class MaxCurrentYearRange extends Range
{
    public function __construct($options)
    {
        if (\array_key_exists('max', $options)) {
            throw new ConstraintDefinitionException(sprintf(
                'You are not allowed to provide "max" option for "%s".',
                self::class
            ));
        }

        $options['max'] = (int) date('Y');
        $options['minMessage'] = 'Das Jahr muss größer/gleich {{ limit }} sein.';
        $options['maxMessage'] = 'Das Jahr muss kleiner/gleich {{ limit }} sein.';

        parent::__construct($options);
    }

    public function validatedBy(): string
    {
        return RangeValidator::class;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment