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

99 lines
2.6 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
2014-04-23 11:57:22 +01:00
* @Target({"PROPERTY", "METHOD", "ANNOTATION"})
2011-07-20 09:37:57 +01:00
*
* @author Bernhard Schussek <bschussek@gmail.com>
*
2011-07-20 09:37:57 +01:00
* @api
*/
2011-05-19 08:34:54 +01:00
class Regex extends Constraint
{
public $message = 'This value is not valid.';
public $pattern;
public $htmlPattern;
public $match = true;
/**
* {@inheritdoc}
*/
public function getDefaultOption()
{
return 'pattern';
}
/**
* {@inheritdoc}
*/
public function getRequiredOptions()
{
return array('pattern');
}
/**
2014-01-07 03:21:50 +00:00
* Converts the htmlPattern to a suitable format for HTML5 pattern.
* Example: /^[a-z]+$/ would be converted to [a-z]+
2014-12-21 17:00:50 +00:00
* 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.
*
* @link http://dev.w3.org/html5/spec/single-page.html#the-pattern-attribute
*
* @return string|null
*/
public function getHtmlPattern()
{
// If htmlPattern is specified, use it
if (null !== $this->htmlPattern) {
return empty($this->htmlPattern)
? null
: $this->htmlPattern;
}
// Quit if delimiters not at very beginning/end (e.g. when options are passed)
if ($this->pattern[0] !== $this->pattern[strlen($this->pattern) - 1]) {
2014-04-16 08:15:58 +01:00
return;
}
2012-12-11 10:40:22 +00:00
$delimiter = $this->pattern[0];
// Unescape the delimiter
$pattern = str_replace('\\'.$delimiter, $delimiter, substr($this->pattern, 1, -1));
// If the pattern is inverted, we can simply wrap it in
// ((?!pattern).)*
if (!$this->match) {
return '((?!'.$pattern.').)*';
}
2012-07-09 13:50:58 +01:00
// If the pattern contains an or statement, wrap the pattern in
// .*(pattern).* and quit. Otherwise we'd need to parse the pattern
if (false !== strpos($pattern, '|')) {
return '.*('.$pattern.').*';
}
// Trim leading ^, otherwise prepend .*
$pattern = '^' === $pattern[0] ? substr($pattern, 1) : '.*'.$pattern;
// Trim trailing $, otherwise append .*
$pattern = '$' === $pattern[strlen($pattern) - 1] ? substr($pattern, 0, -1) : $pattern.'.*';
return $pattern;
}
2011-06-08 11:16:48 +01:00
}