This repository has been archived by the owner on Sep 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Examples.php
79 lines (64 loc) · 1.97 KB
/
Examples.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<?php
declare(strict_types=1);
namespace Shrink\Examples;
use InvalidArgumentException;
use function array_filter;
use function array_key_exists;
use function array_map;
use function array_merge;
final class Examples
{
/**
* List of example definitions keyed by the example type.
*
* @var array<\Shrink\Examples\DefinesExample>
*/
private array $definitions = [];
/**
* Register a new example definition.
*/
public function register(DefinesExample $definition): void
{
$this->definitions[$definition->type()] = $definition;
}
/**
* Make an example instance from the Example configuration.
*/
public function make(ConfiguresExample $configuration): object
{
$type = $configuration->type();
if (!array_key_exists($type, $this->definitions)) {
throw new InvalidArgumentException(
"{$type} is not registered, an example cannot be built."
);
}
$definition = $this->definitions[$configuration->type()];
$parameters = $this->fillParameters(
array_merge($definition->defaults(), $configuration->parameters())
);
return $definition->build($parameters);
}
/**
* Fill parameters with any nested Examples.
*
* @param array<mixed> $parameters
*
* @return array<mixed>
*/
private function fillParameters(array $parameters): array
{
$filterNestedExamples =
/** @param mixed $parameter */
static function ($parameter): bool {
return $parameter instanceof ConfiguresExample;
};
$makeNestedExamples = function (ConfiguresExample $parameter): object {
return $this->make($parameter);
};
$nestedExamples = array_map(
$makeNestedExamples,
array_filter($parameters, $filterNestedExamples)
);
return array_merge($parameters, $nestedExamples);
}
}