如何阻止超过4位数的年份?

时间:2017-05-12 08:27:33

标签: php symfony date twig

情况,我使用树枝,当用户错误地输入日期为15.05.20177(欧洲格式,我们只使用这一个)时,树枝无法解析日期。

("DateTime::__construct(): Failed to parse time string (12.04.20177) at position 10 (7): Unexpected character").

我试过preg_match,字符串比较,日期比较,但没有任何作用......

        if (!preg_match("/^[0-9]{2}.[0-9]{2}.[0-9]{4}$/", $date)) {
            throw new RuntimeException("Bug of year 10'000.");
        }

        $dateToCompare = strtotime($date);
        $maxDate = strtotime("31.12.9999");
        if ($dateToCompare > $maxDate) {
            throw new RuntimeException("Bug of year 10'000.");
        }

        if ($date > strtotime("31.12.9999")) {
            throw new RuntimeException("Bug of year 10'000.");
        }

可以在此处添加修复:

        $this->twig->addFilter(new Twig_SimpleFilter('date', function($date, $formatOrOptions = null, $timezone = null) {

        // Handle a larger option array but keep the backward compatibility with the Twig date helper
        $defaults = [
            'format' => null,
            'timezone' => null,
            'empty_output' => ''
        ];
        if ($formatOrOptions == null || is_string($formatOrOptions)) {
            $options = array_merge($defaults, ['format'=>$formatOrOptions, 'timezone'=> $timezone]);
        }
        elseif (is_array($formatOrOptions)) {
            if ($diff = array_diff(array_keys($formatOrOptions), array_keys($defaults))) {
                throw new RuntimeException("Invalid options: [".implode(', ', $diff)."]");
            }
            $options = array_merge($defaults, $formatOrOptions);
        }
        else {
            throw new RuntimeException("First filter parameter must be a string or an array");
        }

        // This is because by default Twig return the today date for null values
        if ($date == null || $date == '' || $date == '0000-00-00'){
            return $options['empty_output'];
        }

        return twig_date_format_filter($this->twig, $date, $options['format'], $options['timezone']);

谢谢,并抱歉“愚蠢”的问题:)

1 个答案:

答案 0 :(得分:3)

您可以尝试传递DateTime对象,而不是将字符串传递给Twig。这样,日期格式验证可以直接在PHP代码中完成。在将变量传递给Twig环境之前,您应该尝试构建DateTime对象,如下所示:

$myDate = DateTime::createFromFormat('d.m.Y', $stringDate);

然后,您应该检查日期变量的内容。如果它是假的,则解析失败。检查一下:

// Do a strict equality check here
if ($myDate === false) {
    throw new RuntimeException("Invalid date");
}

当然,根据您的需要以您认为合适的方式处理您的例外情况。这只是一个例子

然后,您可以传递$ myDate变量而不是字符串,并将其集成到您的树枝模板中

{{ myDate|date(d.m.Y) }}