1: <?php
2:
3: declare(strict_types=1);
4:
5: namespace Atk4\Core;
6:
7: trait StaticAddToTrait
8: {
9: use DiContainerTrait;
10:
11: /**
12: * @param array<mixed> $addArgs
13: */
14: private static function _addToAdd(object $parent, object $object, array $addArgs, bool $skipAdd = false): void
15: {
16: if (!$skipAdd) {
17: $parent->add($object, ...$addArgs);
18: }
19: }
20:
21: /**
22: * Initialize and add new object into parent. The new object is asserted to be an instance of current class.
23: *
24: * The best, typehinting-friendly, way to create an object if it should be immediately
25: * added to a parent (otherwise use fromSeed() method).
26: *
27: * $crud = Crud::addTo($app, ['displayFields' => ['name']]);
28: * is equivalent to
29: * $crud = $app->add(['Crud', 'displayFields' => ['name']]);
30: * but the first one design pattern is strongly recommended as it supports refactoring.
31: *
32: * @param array<mixed> $defaults
33: * @param array<mixed> $addArgs
34: *
35: * @return static
36: */
37: public static function addTo(object $parent, array $defaults = [], array $addArgs = [], bool $skipAdd = false)// :static supported by PHP8+
38: {
39: $object = static::fromSeed([static::class], $defaults);
40:
41: self::_addToAdd($parent, $object, $addArgs, $skipAdd);
42:
43: return $object;
44: }
45:
46: /**
47: * Same as addTo(), but the first element of seed specifies a class name instead of static::class.
48: *
49: * @param array<mixed>|object $seed the first element specifies a class name, other elements are seed
50: * @param array<mixed> $addArgs
51: *
52: * @return static
53: */
54: public static function addToWithCl(object $parent, $seed = [], array $addArgs = [], bool $skipAdd = false)// :static supported by PHP8+
55: {
56: $object = static::fromSeed($seed);
57:
58: self::_addToAdd($parent, $object, $addArgs, $skipAdd);
59:
60: return $object;
61: }
62:
63: /**
64: * Same as addToWithCl(), but the new object is not asserted to be an instance of this class.
65: *
66: * @param array<mixed>|object $seed the first element specifies a class name, other elements are seed
67: * @param array<mixed> $addArgs
68: *
69: * @return static
70: */
71: public static function addToWithClUnsafe(object $parent, $seed = [], array $addArgs = [], bool $skipAdd = false)// :self is too strict with unsafe behaviour
72: {
73: $object = static::fromSeedUnsafe($seed);
74:
75: self::_addToAdd($parent, $object, $addArgs, $skipAdd);
76:
77: return $object;
78: }
79: }
80: