|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Chubbyphp\Parsing; |
| 6 | + |
| 7 | +/** |
| 8 | + * @phpstan-type ErrorAsJson array{code: string, template: string, variables: array<string, mixed>} |
| 9 | + * @phpstan-type ErrorWithPathJson array{error: ErrorAsJson, path: string} |
| 10 | + * @phpstan-type ErrorsWithPathJson array<ErrorWithPathJson> |
| 11 | + */ |
| 12 | +final class ErrorsWithPath implements \JsonSerializable |
| 13 | +{ |
| 14 | + /** |
| 15 | + * @var array<ErrorWithPath> |
| 16 | + */ |
| 17 | + private array $errorsWithPath = []; |
| 18 | + |
| 19 | + /** |
| 20 | + * @param array<Error|ErrorWithPath|self> $errors |
| 21 | + */ |
| 22 | + public function __construct(array $errors, private string $path = '') |
| 23 | + { |
| 24 | + foreach ($errors as $error) { |
| 25 | + $this->addError($error); |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + public function addError(Error|ErrorWithPath|self $error): self |
| 30 | + { |
| 31 | + if ($error instanceof self) { |
| 32 | + foreach ($error->errorsWithPath as $errorWithPath) { |
| 33 | + $this->errorsWithPath[] = new ErrorWithPath($errorWithPath->error, $this->buildPath($this->path, $errorWithPath->path)); |
| 34 | + } |
| 35 | + } elseif ($error instanceof ErrorWithPath) { |
| 36 | + $this->errorsWithPath[] = new ErrorWithPath($error->error, $this->buildPath($this->path, $error->path)); |
| 37 | + } else { |
| 38 | + $this->errorsWithPath[] = new ErrorWithPath($error, $this->path); |
| 39 | + } |
| 40 | + |
| 41 | + return $this; |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * @return ErrorsWithPathJson |
| 46 | + */ |
| 47 | + public function jsonSerialize(): array |
| 48 | + { |
| 49 | + return array_map(static fn ($errorWithPath) => $errorWithPath->jsonSerialize(), $this->errorsWithPath); |
| 50 | + } |
| 51 | + |
| 52 | + public function toTree(): array |
| 53 | + { |
| 54 | + $data = []; |
| 55 | + |
| 56 | + foreach ($this->errorsWithPath as $errorWithPath) { |
| 57 | + $current = &$data; |
| 58 | + $pathParts = explode('.', $errorWithPath->path); |
| 59 | + $pathPartsCount = \count($pathParts); |
| 60 | + |
| 61 | + foreach ($pathParts as $i => $pathPart) { |
| 62 | + if ($i + 1 < $pathPartsCount) { |
| 63 | + $current[$pathPart] ??= []; |
| 64 | + $current = &$current[$pathPart]; |
| 65 | + } else { |
| 66 | + $current[$pathPart] = array_merge($current[$pathPart] ?? [], [$errorWithPath->error]); |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + return $data; |
| 72 | + } |
| 73 | + |
| 74 | + private function buildPath(string $path, string $existingPath): string |
| 75 | + { |
| 76 | + return '' === $path ? $existingPath : $path.'.'.$existingPath; |
| 77 | + } |
| 78 | +} |
0 commit comments