ILIAS  trunk Revision v11.0_alpha-1713-gd8962da2f67
All Data Structures Namespaces Files Functions Variables Enumerations Enumerator Modules Pages
Map.php
Go to the documentation of this file.
1 <?php
2 
19 declare(strict_types=1);
20 
21 namespace ILIAS\LegalDocuments;
22 
23 use Closure;
24 use Exception;
25 
26 class 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 }
__construct(private readonly array $map=[],)
Definition: Map.php:31
map(string $key, Closure $proc)
Definition: Map.php:71
append(self $other)
Definition: Map.php:51
add(string $name, $item)
Definition: Map.php:36
has(string $name, string $key)
Definition: Map.php:46