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

Make abstraction over Translator #106

Merged
merged 2 commits into from Jan 23, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 1 addition & 2 deletions composer.json
Expand Up @@ -30,8 +30,7 @@
"yiisoft/arrays": "dev-master",
"yiisoft/friendly-exception": "^1.0",
"yiisoft/network-utilities": "dev-master",
"yiisoft/strings": "^1.0",
"yiisoft/translator": "dev-master"
"yiisoft/strings": "^1.0"
},
"require-dev": {
"phpunit/phpunit": "^9.5",
Expand Down
24 changes: 24 additions & 0 deletions src/Formatter.php
@@ -0,0 +1,24 @@
<?php

declare(strict_types=1);

namespace Yiisoft\Validator;

class Formatter implements FormatterInterface
{
public function format(string $message, array $parameters = []): string
{
$replacements = [];
foreach ($parameters as $key => $value) {
if (is_array($value)) {
$value = 'array';
} elseif (is_object($value)) {
$value = 'object';
} elseif (is_resource($value)) {
$value = 'resource';
}
$replacements['{' . $key . '}'] = $value;
}
return strtr($message, $replacements);
}
}
10 changes: 10 additions & 0 deletions src/FormatterInterface.php
@@ -0,0 +1,10 @@
<?php

declare(strict_types=1);

namespace Yiisoft\Validator;

interface FormatterInterface
{
public function format(string $message, array $parameters = []): string;
}
50 changes: 8 additions & 42 deletions src/Rule.php
Expand Up @@ -4,14 +4,12 @@

namespace Yiisoft\Validator;

use Yiisoft\Translator\TranslatorInterface;

/**
* Rule represents a single value validation rule.
*/
abstract class Rule
{
private ?TranslatorInterface $translator = null;
private ?FormatterInterface $formatter = null;
private ?string $translationDomain = null;
private ?string $translationLocale = null;
private bool $skipOnEmpty = false;
Expand Down Expand Up @@ -57,38 +55,22 @@ final public function validate($value, DataSetInterface $dataSet = null, bool $p
*/
abstract protected function validateValue($value, DataSetInterface $dataSet = null): Result;

public function translator(TranslatorInterface $translator): self
{
$new = clone $this;
$new->translator = $translator;
return $new;
}

public function translationDomain(string $translation): self
public function formatter(FormatterInterface $formatter): self
{
$new = clone $this;
$new->translationDomain = $translation;
$new->formatter = $formatter;
return $new;
}

public function translationLocale(string $locale): self
protected function formatMessage(string $message, array $parameters = []): string
{
$new = clone $this;
$new->translationLocale = $locale;
return $new;
}

protected function translateMessage(string $message, array $parameters = []): string
{
if ($this->translator === null) {
return $this->formatMessage($message, $parameters);
if ($this->formatter === null) {
$this->formatter = new Formatter();
}

return $this->translator->translate(
return $this->formatter->format(
$message,
$parameters,
$this->translationDomain ?? 'validators',
$this->translationLocale
$parameters
);
}

Expand Down Expand Up @@ -138,22 +120,6 @@ public function skipOnEmpty(bool $value): self
return $new;
}

private function formatMessage(string $message, array $arguments = []): string
{
$replacements = [];
foreach ($arguments as $key => $value) {
if (is_array($value)) {
$value = 'array';
} elseif (is_object($value)) {
$value = 'object';
} elseif (is_resource($value)) {
$value = 'resource';
}
$replacements['{' . $key . '}'] = $value;
}
return strtr($message, $replacements);
}

/**
* Checks if the given value is empty.
* A value is considered empty if it is null, an empty array, or an empty string.
Expand Down
4 changes: 2 additions & 2 deletions src/Rule/AtLeast.php
Expand Up @@ -54,7 +54,7 @@ protected function validateValue($value, DataSetInterface $dataSet = null): Resu

if ($filledCount < $this->min) {
$result->addError(
$this->translateMessage(
$this->formatMessage(
$this->message,
[
'min' => $this->min,
Expand Down Expand Up @@ -83,7 +83,7 @@ public function getOptions(): array
return array_merge(
parent::getOptions(),
['min' => $this->min],
['message' => $this->translateMessage($this->message, ['min' => $this->min])],
['message' => $this->formatMessage($this->message, ['min' => $this->min])],
);
}
}
4 changes: 2 additions & 2 deletions src/Rule/Boolean.php
Expand Up @@ -65,7 +65,7 @@ protected function validateValue($value, DataSetInterface $dataSet = null): Resu

if (!$valid) {
$result->addError(
$this->translateMessage(
$this->formatMessage(
$this->message,
[
'true' => $this->trueValue === true ? 'true' : $this->trueValue,
Expand All @@ -86,7 +86,7 @@ public function getOptions(): array
'strict' => $this->strict,
'trueValue' => $this->trueValue,
'falseValue' => $this->falseValue,
'message' => $this->translateMessage(
'message' => $this->formatMessage(
$this->message,
[
'true' => $this->trueValue === true ? 'true' : $this->trueValue,
Expand Down
2 changes: 1 addition & 1 deletion src/Rule/Callback.php
Expand Up @@ -34,7 +34,7 @@ protected function validateValue($value, DataSetInterface $dataSet = null): Resu

if ($callbackResult->isValid() === false) {
foreach ($callbackResult->getErrors() as $message) {
$result->addError($this->translateMessage($message));
$result->addError($this->formatMessage($message));
}
}
return $result;
Expand Down
4 changes: 2 additions & 2 deletions src/Rule/CompareTo.php
Expand Up @@ -136,7 +136,7 @@ protected function validateValue($value, DataSetInterface $dataSet = null): Resu

if (!$this->compareValues($this->operator, $this->type, $value, $this->compareValue)) {
$result->addError(
$this->translateMessage(
$this->formatMessage(
$this->getMessage(),
[
'value' => $this->compareValue,
Expand Down Expand Up @@ -197,7 +197,7 @@ public function getOptions(): array
'type' => $this->type,
'operator' => $this->operator,
'compareValue' => $this->compareValue,
'message' => $this->translateMessage($this->getMessage(), ['value' => $this->compareValue]),
'message' => $this->formatMessage($this->getMessage(), ['value' => $this->compareValue]),
],
);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Rule/Each.php
Expand Up @@ -40,7 +40,7 @@ protected function validateValue($value, DataSetInterface $dataSet = null): Resu
if ($itemResult->isValid() === false) {
foreach ($itemResult->getErrors() as $error) {
$result->addError(
$this->translateMessage(
$this->formatMessage(
$this->message,
[
'error' => $error,
Expand Down
4 changes: 2 additions & 2 deletions src/Rule/Email.php
Expand Up @@ -104,7 +104,7 @@ protected function validateValue($value, DataSetInterface $dataSet = null): Resu
}

if ($valid === false) {
$result->addError($this->translateMessage($this->message));
$result->addError($this->formatMessage($this->message));
}

return $result;
Expand Down Expand Up @@ -155,7 +155,7 @@ public function getOptions(): array
'allowName' => $this->allowName,
'checkDNS' => $this->checkDNS,
'enableIDN' => $this->enableIDN,
'message' => $this->translateMessage($this->message),
'message' => $this->formatMessage($this->message),
],
);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Rule/GroupRule.php
Expand Up @@ -23,7 +23,7 @@ protected function validateValue($value, DataSetInterface $dataSet = null): Resu
{
$result = new Result();
if (!$this->getRules()->validate($value, $dataSet)->isValid()) {
$result->addError($this->translateMessage($this->message));
$result->addError($this->formatMessage($this->message));
}

return $result;
Expand Down
12 changes: 6 additions & 6 deletions src/Rule/HasLength.php
Expand Up @@ -53,17 +53,17 @@ protected function validateValue($value, DataSetInterface $dataSet = null): Resu
$result = new Result();

if (!is_string($value)) {
$result->addError($this->translateMessage($this->message));
$result->addError($this->formatMessage($this->message));
return $result;
}

$length = mb_strlen($value, $this->encoding);

if ($this->min !== null && $length < $this->min) {
$result->addError($this->translateMessage($this->tooShortMessage, ['min' => $this->min]));
$result->addError($this->formatMessage($this->tooShortMessage, ['min' => $this->min]));
}
if ($this->max !== null && $length > $this->max) {
$result->addError($this->translateMessage($this->tooLongMessage, ['max' => $this->max]));
$result->addError($this->formatMessage($this->tooLongMessage, ['max' => $this->max]));
}

return $result;
Expand Down Expand Up @@ -109,11 +109,11 @@ public function getOptions(): array
return array_merge(
parent::getOptions(),
[
'message' => $this->translateMessage($this->message),
'message' => $this->formatMessage($this->message),
'min' => $this->min,
'tooShortMessage' => $this->translateMessage($this->tooShortMessage, ['min' => $this->min]),
'tooShortMessage' => $this->formatMessage($this->tooShortMessage, ['min' => $this->min]),
'max' => $this->max,
'tooLongMessage' => $this->translateMessage($this->tooLongMessage, ['max' => $this->max]),
'tooLongMessage' => $this->formatMessage($this->tooLongMessage, ['max' => $this->max]),
'encoding' => $this->encoding,
],
);
Expand Down
7 changes: 3 additions & 4 deletions src/Rule/InRange.php
Expand Up @@ -4,13 +4,12 @@

namespace Yiisoft\Validator\Rule;

use function is_iterable;
use Yiisoft\Arrays\ArrayHelper;
use Yiisoft\Validator\DataSetInterface;
use Yiisoft\Validator\HasValidationErrorMessage;
use Yiisoft\Validator\Result;

use Yiisoft\Validator\Rule;
use function is_iterable;

/**
* In validates that the attribute value is among a list of values.
Expand Down Expand Up @@ -62,7 +61,7 @@ protected function validateValue($value, DataSetInterface $dataSet = null): Resu
$result = new Result();

if ($this->not === $in) {
$result->addError($this->translateMessage($this->message));
$result->addError($this->formatMessage($this->message));
}

return $result;
Expand All @@ -87,7 +86,7 @@ public function getOptions(): array
return array_merge(
parent::getOptions(),
[
'message' => $this->translateMessage($this->message),
'message' => $this->formatMessage($this->message),
'range' => $this->range,
'strict' => $this->strict,
'not' => $this->not,
Expand Down
34 changes: 17 additions & 17 deletions src/Rule/Ip.php
Expand Up @@ -197,12 +197,12 @@ protected function validateValue($value, DataSetInterface $dataSet = null): Resu
}
$result = new Result();
if (!is_string($value)) {
$result->addError($this->translateMessage($this->message));
$result->addError($this->formatMessage($this->message));
return $result;
}

if (preg_match($this->getIpParsePattern(), $value, $matches) === 0) {
$result->addError($this->translateMessage($this->message));
$result->addError($this->formatMessage($this->message));
return $result;
}
$negation = !empty($matches['not'] ?? null);
Expand All @@ -213,28 +213,28 @@ protected function validateValue($value, DataSetInterface $dataSet = null): Resu
try {
$ipVersion = IpHelper::getIpVersion($ip, false);
} catch (\InvalidArgumentException $e) {
$result->addError($this->translateMessage($this->message));
$result->addError($this->formatMessage($this->message));
return $result;
}

if ($this->requireSubnet === true && $cidr === null) {
$result->addError($this->translateMessage($this->noSubnet));
$result->addError($this->formatMessage($this->noSubnet));
return $result;
}
if ($this->allowSubnet === false && $cidr !== null) {
$result->addError($this->translateMessage($this->hasSubnet));
$result->addError($this->formatMessage($this->hasSubnet));
return $result;
}
if ($this->allowNegation === false && $negation) {
$result->addError($this->translateMessage($this->message));
$result->addError($this->formatMessage($this->message));
return $result;
}
if ($ipVersion === IpHelper::IPV6 && !$this->allowIpv6) {
$result->addError($this->translateMessage($this->ipv6NotAllowed));
$result->addError($this->formatMessage($this->ipv6NotAllowed));
return $result;
}
if ($ipVersion === IpHelper::IPV4 && !$this->allowIpv4) {
$result->addError($this->translateMessage($this->ipv4NotAllowed));
$result->addError($this->formatMessage($this->ipv4NotAllowed));
return $result;
}
if (!$result->isValid()) {
Expand All @@ -244,12 +244,12 @@ protected function validateValue($value, DataSetInterface $dataSet = null): Resu
try {
IpHelper::getCidrBits($ipCidr);
} catch (\InvalidArgumentException $e) {
$result->addError($this->translateMessage($this->wrongCidr));
$result->addError($this->formatMessage($this->wrongCidr));
return $result;
}
}
if (!$this->isAllowed($ipCidr)) {
$result->addError($this->translateMessage($this->notInRange));
$result->addError($this->formatMessage($this->notInRange));
return $result;
}

Expand Down Expand Up @@ -468,19 +468,19 @@ public function getOptions(): array
return array_merge(
parent::getOptions(),
[
'message' => $this->translateMessage($this->message),
'message' => $this->formatMessage($this->message),
'allowIpv4' => $this->allowIpv4,
'ipv4NotAllowedMessage' => $this->translateMessage($this->ipv4NotAllowed),
'ipv4NotAllowedMessage' => $this->formatMessage($this->ipv4NotAllowed),
'allowIpv6' => $this->allowIpv6,
'ipv6NotAllowedMessage' => $this->translateMessage($this->ipv6NotAllowed),
'ipv6NotAllowedMessage' => $this->formatMessage($this->ipv6NotAllowed),
'allowSubnet' => $this->allowSubnet,
'hasSubnetMessage' => $this->translateMessage($this->hasSubnet),
'hasSubnetMessage' => $this->formatMessage($this->hasSubnet),
'requireSubnet' => $this->requireSubnet,
'noSubnetMessage' => $this->translateMessage($this->noSubnet),
'noSubnetMessage' => $this->formatMessage($this->noSubnet),
'allowNegation' => $this->allowNegation,
'wrongCidrMessage' => $this->translateMessage($this->wrongCidr),
'wrongCidrMessage' => $this->formatMessage($this->wrongCidr),
'ranges' => $this->ranges,
'notInRangeMessage' => $this->translateMessage($this->notInRange),
'notInRangeMessage' => $this->formatMessage($this->notInRange),
],
);
}
Expand Down