Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add RegexValidator #19

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions src/RegexValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?php

namespace ipl\Validator;

use Exception;
use ipl\I18n\Translation;

/**
* Validates value with given regex pattern
*
* Available options:
* - pattern: (string) Regex pattern
* - notMatchMessage: (string) Message to show if value isn't valid. if not set, default message will be used
*/
class RegexValidator extends BaseValidator
{
use Translation;

/** @var string Regex pattern */
protected $pattern;

/** @var string Message to show if value isn't valid. if not set, default message will be used */
protected $notMatchMessage;

public function __construct($pattern)
{
if (is_array($pattern)) {
if (! isset($pattern['pattern'])) {
throw new Exception("Missing option 'pattern'");
}

$this->pattern = $pattern['pattern'];
$this->notMatchMessage = $pattern['notMatchMessage'] ?? null;
} else {
$this->pattern = (string) $pattern;
}
}

public function isValid($value)
{
// Multiple isValid() calls must not stack validation messages
$this->clearMessages();

$status = @preg_match($this->pattern, $value);
if ($status === false) {
$this->addMessage(sprintf(
"There was an internal error while using the pattern '%s'",
$this->pattern
));

return false;
}

if ($status === 0) {
if (empty($this->notMatchMessage)) {
$this->addMessage(sprintf(
$this->translate("'%s' does not match against pattern '%s'"),
$value,
$this->pattern
));
} else {
$this->addMessage($this->notMatchMessage);
}

return false;
}

return true;
}
}