Skip to content

Commit

Permalink
Trace paths instead of IDs
Browse files Browse the repository at this point in the history
  • Loading branch information
henriquemoody committed Dec 22, 2024
1 parent 2c21ed7 commit 177e3bd
Show file tree
Hide file tree
Showing 43 changed files with 515 additions and 485 deletions.
86 changes: 53 additions & 33 deletions library/Message/StandardFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,19 @@ public function __construct(
}

/**
* @param array<string, mixed> $templates
* @param array<string|int, mixed> $templates
*/
public function main(Result $result, array $templates, Translator $translator): string
{
$selectedTemplates = $this->selectTemplates($result, $templates);
if (!$this->isFinalTemplate($result, $selectedTemplates)) {
foreach ($this->extractDeduplicatedChildren($result) as $child) {
if ($result->path !== null && $child->path !== null) {
$child = $child->withPath(sprintf('%s.%s', $result->path, $child->path));
} elseif ($result->path !== null && $child->path === null) {
$child = $child->withPath($result->path);
}

return $this->main($child, $selectedTemplates, $translator);
}
}
Expand All @@ -50,7 +56,7 @@ public function main(Result $result, array $templates, Translator $translator):
}

/**
* @param array<string, mixed> $templates
* @param array<string|int, mixed> $templates
*/
public function full(
Result $result,
Expand Down Expand Up @@ -91,32 +97,36 @@ public function full(
}

/**
* @param array<string, mixed> $templates
* @param array<string|int, mixed> $templates
*
* @return array<string, mixed>
* @return array<string|int, mixed>
*/
public function array(Result $result, array $templates, Translator $translator): array
{
$selectedTemplates = $this->selectTemplates($result, $templates);
$deduplicatedChildren = $this->extractDeduplicatedChildren($result);
if (count($deduplicatedChildren) === 0 || $this->isFinalTemplate($result, $selectedTemplates)) {
return [
$result->id => $this->renderer->render($this->getTemplated($result, $selectedTemplates), $translator),
$result->path ?? $result->id => $this->renderer->render(
$this->getTemplated($result, $selectedTemplates),
$translator
),
];
}

$messages = [];
foreach ($deduplicatedChildren as $child) {
$messages[$child->id] = $this->array(
$key = $child->path ?? $child->id;
$messages[$key] = $this->array(
$child,
$this->selectTemplates($child, $selectedTemplates),
$translator
);
if (count($messages[$child->id]) !== 1) {
if (count($messages[$key]) !== 1) {
continue;
}

$messages[$child->id] = current($messages[$child->id]);
$messages[$key] = current($messages[$key]);
}

if (count($messages) > 1) {
Expand Down Expand Up @@ -165,56 +175,66 @@ private function isAlwaysVisible(Result $result, Result ...$siblings): bool
);
}

/** @param array<string, mixed> $templates */
/** @param array<string|int, mixed> $templates */
private function getTemplated(Result $result, array $templates): Result
{
if ($result->hasCustomTemplate()) {
return $result;
}

if (!isset($templates[$result->id]) && isset($templates['__root__'])) {
return $result->withTemplate($templates['__root__']);
}
foreach ([$result->path, $result->name, $result->id, '__root__'] as $key) {
if (!isset($templates[$key])) {
continue;
}

if (!isset($templates[$result->id])) {
return $result;
}
if (is_string($templates[$key])) {
return $result->withTemplate($templates[$key]);
}

$template = $templates[$result->id];
if (is_string($template)) {
return $result->withTemplate($template);
throw new ComponentException(
sprintf('Template for "%s" must be a string, %s given', $key, stringify($templates[$key]))
);
}

throw new ComponentException(
sprintf('Template for "%s" must be a string, %s given', $result->id, stringify($template))
);
return $result;
}

/**
* @param array<string, mixed> $templates
* @param array<string|int, mixed> $templates
*/
private function isFinalTemplate(Result $result, array $templates): bool
{
if (isset($templates[$result->id]) && is_string($templates[$result->id])) {
return true;
$keys = [$result->path, $result->name, $result->id];
foreach ($keys as $key) {
if (isset($templates[$key]) && is_string($templates[$key])) {
return true;
}
}

if (count($templates) !== 1) {
return false;
}

return isset($templates['__root__']) || isset($templates[$result->id]);
foreach ($keys as $key) {
if (isset($templates[$key])) {
return true;
}
}

return isset($templates['__root__']);
}

/**
* @param array<string, mixed> $templates
* @param array<string|int, mixed> $templates
*
* @return array<string, mixed>
* @return array<string|int, mixed>
*/
private function selectTemplates(Result $message, array $templates): array
private function selectTemplates(Result $result, array $templates): array
{
if (isset($templates[$message->id]) && is_array($templates[$message->id])) {
return $templates[$message->id];
foreach ([$result->path, $result->name, $result->id] as $key) {
if (isset($templates[$key]) && is_array($templates[$key])) {
return $templates[$key];
}
}

return $templates;
Expand All @@ -227,16 +247,16 @@ private function extractDeduplicatedChildren(Result $result): array
$deduplicatedResults = [];
$duplicateCounters = [];
foreach ($result->children as $child) {
$id = $child->id;
$id = $child->path ?? $child->id;
if (isset($duplicateCounters[$id])) {
$id .= '.' . ++$duplicateCounters[$id];
} elseif (array_key_exists($id, $deduplicatedResults)) {
$deduplicatedResults[$id . '.1'] = $deduplicatedResults[$id]?->withId($id . '.1');
$deduplicatedResults[$id . '.1'] = $child->path ? $deduplicatedResults[$id]?->withPath($id . '.1') : $deduplicatedResults[$id]?->withId($id . '.1');
unset($deduplicatedResults[$id]);
$duplicateCounters[$id] = 2;
$id .= '.2';
}
$deduplicatedResults[$id] = $child->isValid ? null : $child->withId($id);
$deduplicatedResults[$id] = $child->isValid ? null : ($child->path ? $child->withPath((string) $id) : $child->withId((string) $id));
}

return array_values(array_filter($deduplicatedResults));
Expand Down
10 changes: 7 additions & 3 deletions library/Message/StandardRenderer.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
namespace Respect\Validation\Message;

use ReflectionClass;
use Respect\Stringifier\Quoter;
use Respect\Stringifier\Quoters\StandardQuoter;
use Respect\Stringifier\Stringifier;
use Respect\Stringifier\Stringifiers\CompositeStringifier;
use Respect\Validation\Mode;
Expand All @@ -29,15 +31,17 @@ final class StandardRenderer implements Renderer

private readonly Stringifier $stringifier;

public function __construct(?Stringifier $stringifier = null)
{
public function __construct(
?Stringifier $stringifier = null,
private readonly Quoter $quoter = new StandardQuoter(120)
) {
$this->stringifier = $stringifier ?? CompositeStringifier::createDefault();
}

public function render(Result $result, Translator $translator, ?string $template = null): string
{
$parameters = $result->parameters;
$parameters['name'] ??= $result->name ?? $this->placeholder('input', $result->input, $translator);
$parameters['name'] ??= $result->name ?? ($result->path !== null ? $this->quoter->quote('.' . $result->path, 0) : null) ?? $this->placeholder('input', $result->input, $translator);
$parameters['input'] = $result->input;

$rendered = (string) preg_replace_callback(
Expand Down
25 changes: 14 additions & 11 deletions library/Result.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public function __construct(
?string $name = null,
?string $id = null,
public readonly ?Result $adjacent = null,
public readonly bool $unchangeableId = false,
public readonly string|int|null $path = null,
Result ...$children,
) {
$this->name = $rule->getName() ?? $name;
Expand Down Expand Up @@ -92,28 +92,29 @@ public static function fromAdjacent(
return $adjacent->withInput($input)->withChildren(...$childrenAsAdjacent);
}

public function withExtraParameters(array $parameters): self
{
return $this->clone(parameters: $parameters + $this->parameters);
}

public function withTemplate(string $template): self
{
return $this->clone(template: $template);
}

public function withId(string $id): self
{
if ($this->unchangeableId) {
return $this;
}

return $this->clone(id: $id);
}

public function withUnchangeableId(string $id): self
public function withPath(string|int $path): self
{
return $this->clone(id: $id, unchangeableId: true);
return $this->clone(adjacent: $this->adjacent?->withPath($path), path: $path);
}

public function withPrefix(string $prefix): self
{
if ($this->id === $this->name || $this->unchangeableId) {
if ($this->id === $this->name || $this->path !== null) {
return $this;
}

Expand Down Expand Up @@ -190,30 +191,32 @@ public function allowsAdjacent(): bool
}

/**
* @param array<string, mixed> $parameters
* @param array<Result>|null $children
*/
private function clone(
?bool $isValid = null,
mixed $input = null,
array|null $parameters = null,
?string $template = null,
?Mode $mode = null,
?string $name = null,
?string $id = null,
?Result $adjacent = null,
?bool $unchangeableId = null,
string|int|null $path = null,
?array $children = null
): self {
return new self(
$isValid ?? $this->isValid,
$input ?? $this->input,
$this->rule,
$this->parameters,
$parameters ?? $this->parameters,
$template ?? $this->template,
$mode ?? $this->mode,
$name ?? $this->name,
$id ?? $this->id,
$adjacent ?? $this->adjacent,
$unchangeableId ?? $this->unchangeableId,
$path ?? $this->path,
...($children ?? $this->children)
);
}
Expand Down
2 changes: 1 addition & 1 deletion library/Rules/Each.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ protected function evaluateNonEmptyArray(array $input): Result
{
$children = [];
foreach ($input as $key => $value) {
$children[] = $this->rule->evaluate($value)->withUnchangeableId((string) $key);
$children[] = $this->rule->evaluate($value)->withPath($key);
}
$isValid = array_reduce($children, static fn ($carry, $childResult) => $carry && $childResult->isValid, true);
if ($isValid) {
Expand Down
6 changes: 1 addition & 5 deletions library/Rules/Key.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ public function __construct(
private readonly int|string $key,
Rule $rule,
) {
$rule->setName($rule->getName() ?? (string) $key);
parent::__construct($rule);
}

Expand All @@ -39,9 +38,6 @@ public function evaluate(mixed $input): Result
return $keyExistsResult;
}

return $this->rule
->evaluate($input[$this->key])
->withUnchangeableId((string) $this->key)
->withNameIfMissing($this->rule->getName() ?? (string) $this->key);
return (new Binder($this, $this->rule))->evaluate($input[$this->key])->withPath($this->key);
}
}
2 changes: 1 addition & 1 deletion library/Rules/KeyExists.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public function getKey(): int|string

public function evaluate(mixed $input): Result
{
return new Result($this->hasKey($input), $input, $this, name: (string) $this->key, id: (string) $this->key);
return new Result($this->hasKey($input), $input, $this, path: $this->key);
}

private function hasKey(mixed $input): bool
Expand Down
6 changes: 1 addition & 5 deletions library/Rules/KeyOptional.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ public function __construct(
private readonly int|string $key,
Rule $rule,
) {
$rule->setName($rule->getName() ?? (string) $key);
parent::__construct($rule);
}

Expand All @@ -39,9 +38,6 @@ public function evaluate(mixed $input): Result
return $keyExistsResult->withInvertedMode();
}

return $this->rule
->evaluate($input[$this->key])
->withUnchangeableId((string) $this->key)
->withNameIfMissing($this->rule->getName() ?? (string) $this->key);
return (new Binder($this, $this->rule))->evaluate($input[$this->key])->withPath($this->key);
}
}
14 changes: 9 additions & 5 deletions library/Rules/Lazy.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,22 +21,26 @@
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
final class Lazy extends Standard
{
/** @var callable(mixed): Rule */
/** @var callable(mixed): Rule|callable(mixed): Result */
private $ruleCreator;

/** @param callable(mixed): Rule $ruleCreator */
/** @param callable(mixed): Rule|callable(mixed): Result $ruleCreator */
public function __construct(callable $ruleCreator)
{
$this->ruleCreator = $ruleCreator;
}

public function evaluate(mixed $input): Result
{
$rule = call_user_func($this->ruleCreator, $input);
if (!$rule instanceof Rule) {
$return = call_user_func($this->ruleCreator, $input);
if ($return instanceof Result) {
return $return;
}

if (!$return instanceof Rule) {
throw new ComponentException('Lazy failed because it could not create the rule');
}

return (new Binder($this, $rule))->evaluate($input);
return (new Binder($this, $return))->evaluate($input);
}
}
Loading

0 comments on commit 177e3bd

Please sign in to comment.