mirror of
https://github.com/Respect/Validation.git
synced 2026-03-17 15:50:03 +01:00
Currently, we’re using scalar values to trace paths. The problem with that approach is that we can’t create a reliable hierarchy with them, as we can’t know for sure when a path is the same for different rules. By using an object, we can easily compare and create a parent-child relationship with it. While making these changes, I deemed it necessary to also create objects to handle Name and Id, which makes the code simpler and more robust. By having Name and Path, we can create specific stringifiers that allow us to customise how we render those values. I didn’t manage to make those changes atomically, which is why this commit makes so many changes. I found myself moving back and forth, and making all those changes at once was the best solution I found.
49 lines
1.1 KiB
PHP
49 lines
1.1 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
/*
|
|
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
|
|
* SPDX-License-Identifier: MIT
|
|
*/
|
|
|
|
namespace Respect\Validation\Message\Stringifier;
|
|
|
|
use Respect\Stringifier\Quoter;
|
|
use Respect\Stringifier\Stringifier;
|
|
use Respect\Validation\Message\Placeholder\Path;
|
|
|
|
use function array_reverse;
|
|
use function implode;
|
|
|
|
final readonly class PathStringifier implements Stringifier
|
|
{
|
|
public function __construct(
|
|
private Quoter $quoter,
|
|
) {
|
|
}
|
|
|
|
public function stringify(mixed $raw, int $depth): string|null
|
|
{
|
|
if (!$raw instanceof Path) {
|
|
return null;
|
|
}
|
|
|
|
return $this->quoter->quote('.' . implode('.', array_reverse($this->getNodes($raw, []))), $depth);
|
|
}
|
|
|
|
/**
|
|
* @param array<string|int> $nodes
|
|
*
|
|
* @return non-empty-array<string|int>
|
|
*/
|
|
public function getNodes(Path $path, array $nodes): array
|
|
{
|
|
$nodes[] = $path->value;
|
|
if ($path->parent !== null) {
|
|
return $this->getNodes($path->parent, $nodes);
|
|
}
|
|
|
|
return $nodes;
|
|
}
|
|
}
|