-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUseCase.php
More file actions
96 lines (79 loc) · 2.42 KB
/
Copy pathUseCase.php
File metadata and controls
96 lines (79 loc) · 2.42 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
<?php
namespace Gcd\UseCases;
use Psr\Container\ContainerInterface;
abstract class UseCase
{
public function __construct()
{
}
/**
* @var ContainerInterface
*/
private static $container;
/**
* Set the DI Container to allow `create` to use DI
*
* @see create()
* @param ContainerInterface $container
*/
public static function setContainer(ContainerInterface $container)
{
self::$container = $container;
}
private static $mocks = [];
/**
* Receives a Stub class to return when a use case needs to be created.
*
* Note this should be the result of a Codeception Stub::make() call.
*
* @param $useCase
*/
final public static function setMockUseCase($useCase)
{
self::$mocks[$useCase->__mocked] = $useCase;
}
/**
* Remove any attached mocks
*/
final public static function clearMockUseCases()
{
self::$mocks = [];
}
/**
* @param array $arguments
* @return static|UseCase
* @throws \ReflectionException
*/
final public static function create(...$arguments)
{
// If we have an attached mock use case - return it instead of making a new use case.
if (isset(self::$mocks[static::class])) {
return self::$mocks[static::class];
}
$reflection = new \ReflectionMethod(static::class, '__construct');
$params = $reflection->getParameters();
$paramArgs = [];
foreach ($params as $param) {
$dependencyClass = $param->getClass();
if ($dependencyClass == null) {
// End of the type hinted arguments
break;
}
$dependencyClassName = $dependencyClass->getName();
if (count($arguments) > 0 && is_object($arguments[0]) && $arguments[0] instanceof $dependencyClassName) {
$dependency = $arguments[0];
array_splice($arguments, 0, 1);
} else {
if (self::$container){
$container = self::$container;
$dependency = $container->get($dependencyClassName);
} else {
$dependency = new $dependencyClassName();
}
}
$paramArgs[] = $dependency;
}
$paramArgs = array_merge($paramArgs, $arguments);
return new static(...$paramArgs);
}
}