-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathModelFactoryWithDefaultsManagement.php
More file actions
70 lines (57 loc) · 2.45 KB
/
ModelFactoryWithDefaultsManagement.php
File metadata and controls
70 lines (57 loc) · 2.45 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
<?php
declare(strict_types=1);
namespace Prosopo\Views\PrivateClasses\Model;
use Closure;
use Prosopo\Views\Interfaces\Model\ModelFactoryInterface;
use Prosopo\Views\Interfaces\Model\TemplateModelWithDefaultsInterface;
use Prosopo\Views\Interfaces\Object\ObjectPropertyWriterInterface;
use Prosopo\Views\Interfaces\Object\ObjectReaderInterface;
/**
* This class is marked as a final and placed under the 'Private' namespace to prevent anyone from using it directly.
* We reserve the right to change its name and implementation.
*/
final class ModelFactoryWithDefaultsManagement implements ModelFactoryInterface
{
private ModelFactoryInterface $modelFactory;
private ObjectReaderInterface $objectPropertyReader;
private ObjectPropertyWriterInterface $objectPropertyWriter;
public function __construct(
ModelFactoryInterface $modelFactory,
ObjectReaderInterface $objectReader,
ObjectPropertyWriterInterface $objectPropertyWriter
) {
$this->modelFactory = $modelFactory;
$this->objectPropertyReader = $objectReader;
$this->objectPropertyWriter = $objectPropertyWriter;
}
public function createModel(string $modelClass, ?Closure $setupModelCallback = null)
{
$model = $this->modelFactory->createModel($modelClass);
if ($model instanceof TemplateModelWithDefaultsInterface) {
$this->setDefaultValuesRecursively($model);
}
return $model;
}
protected function setDefaultValuesRecursively(TemplateModelWithDefaultsInterface $modelWithDefaults): void
{
$defaultsPropertyValueProvider = $modelWithDefaults->getDefaultPropertyValueProvider();
$this->objectPropertyWriter->assignPropertyValues($modelWithDefaults, $defaultsPropertyValueProvider);
$innerModelsWithDefaults = $this->getInnerModels(
$this->objectPropertyReader->extractObjectVariables($modelWithDefaults)
);
array_map(function (TemplateModelWithDefaultsInterface $innerModelWithDefaults) {
$this->setDefaultValuesRecursively($innerModelWithDefaults);
}, $innerModelsWithDefaults);
}
/**
* @param array<string,mixed> $variables
*
* @return TemplateModelWithDefaultsInterface[]
*/
protected function getInnerModels(array $variables): array
{
return array_filter($variables, function ($item) {
return $item instanceof TemplateModelWithDefaultsInterface ;
});
}
}