1: <?php declare(strict_types=1);
2:
3: namespace Salient\Core\Concern;
4:
5: use Salient\Container\RequiresContainer;
6: use Salient\Contract\Container\ContainerInterface;
7: use Salient\Contract\Core\Entity\Constructible;
8: use Salient\Contract\Core\Entity\Treeable;
9: use Salient\Contract\Core\ListConformity;
10: use Salient\Core\Introspector;
11: use Salient\Utility\Exception\InvalidArgumentTypeException;
12: use Generator;
13:
14: /**
15: * Implements Constructible
16: *
17: * @see Constructible
18: *
19: * @api
20: *
21: * @phpstan-require-implements Constructible
22: */
23: trait ConstructibleTrait
24: {
25: use RequiresContainer;
26:
27: /**
28: * @inheritDoc
29: */
30: final public static function construct(
31: array $data,
32: ?object $parent = null,
33: ?ContainerInterface $container = null
34: ) {
35: if ($parent && !$parent instanceof Treeable) {
36: throw new InvalidArgumentTypeException(2, 'parent', Treeable::class, $parent);
37: }
38:
39: $container = self::requireContainer($container);
40:
41: return Introspector::getService($container, static::class)
42: ->getCreateFromClosure(true)($data, $container, null, $parent);
43: }
44:
45: /**
46: * @inheritDoc
47: */
48: final public static function constructMultiple(
49: iterable $data,
50: int $conformity = ListConformity::NONE,
51: ?object $parent = null,
52: ?ContainerInterface $container = null
53: ): Generator {
54: if ($parent && !$parent instanceof Treeable) {
55: throw new InvalidArgumentTypeException(3, 'parent', Treeable::class, $parent);
56: }
57:
58: $container = self::requireContainer($container);
59:
60: $closure = null;
61: foreach ($data as $key => $array) {
62: if (!$closure) {
63: $builder = Introspector::getService($container, static::class);
64: $closure =
65: in_array($conformity, [ListConformity::PARTIAL, ListConformity::COMPLETE])
66: ? $builder->getCreateFromSignatureClosure(array_keys($array), true)
67: : $builder->getCreateFromClosure(true);
68: }
69:
70: yield $key => $closure($array, $container, null, $parent);
71: }
72: }
73: }
74: