-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathStaticAddToTrait.php
79 lines (66 loc) · 2.44 KB
/
StaticAddToTrait.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 Atk4\Core;
trait StaticAddToTrait
{
use DiContainerTrait;
/**
* @param array<mixed> $addArgs
*/
private static function _addToAdd(object $parent, object $object, array $addArgs, bool $skipAdd = false): void
{
if (!$skipAdd) {
$parent->add($object, ...$addArgs);
}
}
/**
* Initialize and add new object into parent. The new object is asserted to be an instance of current class.
*
* The best, typehinting-friendly, way to create an object if it should be immediately
* added to a parent (otherwise use fromSeed() method).
*
* $crud = Crud::addTo($app, ['displayFields' => ['name']]);
* is equivalent to
* $crud = $app->add(['Crud', 'displayFields' => ['name']]);
* but the first one design pattern is strongly recommended as it supports refactoring.
*
* @param array<mixed> $defaults
* @param array<mixed> $addArgs
*
* @return static
*/
public static function addTo(object $parent, array $defaults = [], array $addArgs = [], bool $skipAdd = false)// :static supported by PHP8+
{
$object = static::fromSeed([static::class], $defaults);
self::_addToAdd($parent, $object, $addArgs, $skipAdd);
return $object;
}
/**
* Same as addTo(), but the first element of seed specifies a class name instead of static::class.
*
* @param array<mixed>|object $seed the first element specifies a class name, other elements are seed
* @param array<mixed> $addArgs
*
* @return static
*/
public static function addToWithCl(object $parent, $seed = [], array $addArgs = [], bool $skipAdd = false)// :static supported by PHP8+
{
$object = static::fromSeed($seed);
self::_addToAdd($parent, $object, $addArgs, $skipAdd);
return $object;
}
/**
* Same as addToWithCl(), but the new object is not asserted to be an instance of this class.
*
* @param array<mixed>|object $seed the first element specifies a class name, other elements are seed
* @param array<mixed> $addArgs
*
* @return static
*/
public static function addToWithClUnsafe(object $parent, $seed = [], array $addArgs = [], bool $skipAdd = false)
{
$object = static::fromSeedUnsafe($seed);
self::_addToAdd($parent, $object, $addArgs, $skipAdd);
return $object;
}
}