This repository has been archived on 2023-08-20. You can view files and clone it, but cannot push or open issues or pull requests.
symfony/src/Symfony/Component/Validator/Constraints/Regex.php

97 lines
2.3 KiB
PHP
Raw Normal View History

<?php
2010-10-02 11:42:31 +01:00
/*
* This file is part of the Symfony package.
2010-10-02 11:42:31 +01:00
*
* (c) Fabien Potencier <fabien@symfony.com>
2010-10-02 11:42:31 +01:00
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
2010-10-02 11:42:31 +01:00
*/
namespace Symfony\Component\Validator\Constraints;
2011-05-19 08:34:54 +01:00
use Symfony\Component\Validator\Constraint;
2011-07-20 09:37:57 +01:00
/**
* @Annotation
*
* @api
*/
2011-05-19 08:34:54 +01:00
class Regex extends Constraint
{
public $message = 'This value is not valid.';
public $pattern;
public $htmlPattern = null;
public $match = true;
/**
* {@inheritDoc}
*/
public function getDefaultOption()
{
return 'pattern';
}
/**
* {@inheritDoc}
*/
public function getRequiredOptions()
{
return array('pattern');
}
/**
* Returns htmlPattern if exists or pattern is convertible.
*
* @return string|null
*/
public function getHtmlPattern()
{
// If htmlPattern is specified, use it
if (null !== $this->htmlPattern) {
return empty($this->htmlPattern)
? null
: $this->htmlPattern;
}
return $this->getNonDelimitedPattern();
}
/**
* Convert the htmlPattern to a suitable format for HTML5 pattern.
* Example: /^[a-z]+$/ would be converted to [a-z]+
* However, if options are specified, it cannot be converted
2012-12-11 10:40:22 +00:00
*
* Pattern is also ignored if match=false since the pattern should
* then be reversed before application.
*
* @todo reverse pattern in case match=false as per issue #5307
*
* @link http://dev.w3.org/html5/spec/single-page.html#the-pattern-attribute
*
* @return string|null
*/
private function getNonDelimitedPattern()
{
// If match = false, pattern should not be added to HTML5 validation
if (!$this->match) {
return null;
}
2012-12-11 10:40:22 +00:00
if (preg_match('/^(.)(\^?)(.*?)(\$?)\1$/', $this->pattern, $matches)) {
$delimiter = $matches[1];
$start = empty($matches[2]) ? '.*' : '';
$pattern = $matches[3];
$end = empty($matches[4]) ? '.*' : '';
// Unescape the delimiter in pattern
$pattern = str_replace('\\'.$delimiter, $delimiter, $pattern);
2012-07-09 13:50:58 +01:00
return $start.$pattern.$end;
}
return null;
}
2011-06-08 11:16:48 +01:00
}