ILIAS  trunk Revision v11.0_alpha-3011-gc6b235a2e85
Map.php
Go to the documentation of this file.
1<?php
2
19declare(strict_types=1);
20
21namespace ILIAS\LegalDocuments;
22
23use Closure;
24use Exception;
25
26class Map
27{
31 public function __construct(
32 private readonly array $map = [],
33 ) {
34 }
35
36 public function add(string $name, $item): static
37 {
38 return $this->map($name, fn($list) => [...$list, $item]);
39 }
40
41 public function set(string $name, string $key, $item): static
42 {
43 return $this->map($name, fn(array $map) => [...$map, $key => $item]);
44 }
45
46 public function has(string $name, string $key): bool
47 {
48 return isset($this->map[$name][$key]);
49 }
50
51 public function append(self $other): self
52 {
53 array_map(function ($mine, $other) {
54 $mine ??= [];
55 $other ??= [];
56 if (count($mine) + count($other) !== count(array_merge($mine, $other))) {
57 throw new Exception('Cannot append maps. Keys must be distinct.');
58 }
59 }, $this->map, $other->value());
60 return new self(array_merge_recursive($this->map, $other->value()));
61 }
62
63 public function value(): array
64 {
65 return $this->map;
66 }
67
71 private function map(string $key, Closure $proc): static
72 {
73 return new self([...$this->map, $key => $proc($this->map[$key] ?? [])]);
74 }
75}
has(string $name, string $key)
Definition: Map.php:46
add(string $name, $item)
Definition: Map.php:36
append(self $other)
Definition: Map.php:51
map(string $key, Closure $proc)
Definition: Map.php:71
__construct(private readonly array $map=[],)
Definition: Map.php:31