Repository navigation
Expand file tree
/
Copy pathBaseTestEntity.php
More file actions
102 lines (84 loc) · 2.63 KB
/
Copy pathBaseTestEntity.php
File metadata and controls
102 lines (84 loc) · 2.63 KB
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<?php
declare(strict_types=1);
namespace MsgPhp\Domain\Tests\Fixtures\Entities;
use MsgPhp\Domain\DomainId;
abstract class BaseTestEntity
{
/**
* @return static
*/
final public static function create(array $fields = []): self
{
$entity = new static();
foreach ($fields as $field => $value) {
if (method_exists($entity, $method = 'set'.ucfirst($field))) {
$entity->{$method}($value);
} else {
$entity->{$field} = $value;
}
}
return $entity;
}
/**
* @return array<string, mixed>
*/
final public static function getPrimaryIds(self $entity, array &$primitives = []): array
{
$ids = $primitives = [];
foreach ($entity::getIdFields() as $field) {
$ids[$field] = $id = method_exists($entity, $method = 'get'.ucfirst($field)) ? $entity->{$method}() : $entity->{$field};
if ($id instanceof DomainId) {
$primitives[$field] = $id->isNil() ? null : $id->toString();
} elseif ($id instanceof self) {
$nestedPrimitiveIds = [];
self::getPrimaryIds($id, $nestedPrimitiveIds);
$primitives[$field] = $nestedPrimitiveIds;
} else {
$primitives[$field] = $id;
}
}
return $ids;
}
/**
* @return iterable<int, self>
*/
final public static function createEntities(): iterable
{
foreach (self::getFields() as $fields) {
yield self::create($fields);
}
}
/**
* @return iterable<int, array<string, mixed>>
*/
final public static function getFields(): iterable
{
$fieldNames = array_keys($fieldValues = static::getFieldValues());
$cartesian = static function (array $set) use (&$cartesian): array {
if (!$set) {
return [[]];
}
$subset = array_shift($set);
$cartesianSubset = $cartesian($set);
$result = [];
foreach ($subset as $value) {
foreach ($cartesianSubset as $p) {
array_unshift($p, $value);
$result[] = $p;
}
}
return $result;
};
foreach ($cartesian($fieldValues) as $fieldValues) {
yield array_combine($fieldNames, $fieldValues);
}
}
/**
* @return array<int, string>
*/
abstract public static function getIdFields(): array;
/**
* @return array<string, mixed>
*/
abstract public static function getFieldValues(): array;
}