66
77use Closure ;
88use Patchlevel \EventSourcing \Aggregate \AggregateRoot ;
9+ use Patchlevel \EventSourcing \CommandBus \HandlerFinder ;
910use PHPUnit \Framework \Attributes \After ;
1011use PHPUnit \Framework \Attributes \Before ;
1112use PHPUnit \Framework \Constraint \Exception as ExceptionConstraint ;
1213use PHPUnit \Framework \Constraint \ExceptionMessageIsOrContains ;
1314use PHPUnit \Framework \TestCase ;
15+ use ReflectionClass ;
1416use Throwable ;
1517
1618abstract class AggregateRootTestCase extends TestCase
1719{
1820 /** @var array<object> */
1921 private array $ givenEvents = [];
20- private Closure |null $ when = null ;
22+ private object |null $ when = null ;
23+
24+ /** @var array<mixed> */
25+ private array $ parameters = [];
2126
2227 /** @var array<object> */
2328 private array $ expectedEvents = [];
@@ -35,9 +40,11 @@ final public function given(object ...$events): self
3540 return $ this ;
3641 }
3742
38- final public function when (Closure $ callable ): self
43+ /** @param object|Closure $callable */
44+ final public function when (object $ callable , mixed ...$ parameters ): self
3945 {
4046 $ this ->when = $ callable ;
47+ $ this ->parameters = $ parameters ;
4148
4249 return $ this ;
4350 }
@@ -78,7 +85,29 @@ final public function assert(): self
7885 }
7986
8087 try {
81- $ return = ($ this ->when )($ aggregate );
88+ $ callableOrCommand = $ this ->when ;
89+ $ return = null ;
90+
91+ if ($ callableOrCommand instanceof Closure) {
92+ $ return = $ callableOrCommand ($ aggregate );
93+ } else {
94+ foreach (HandlerFinder::findInClass ($ this ->aggregateClass ()) as $ handler ) {
95+ if (!$ callableOrCommand instanceof $ handler ->commandClass ) {
96+ continue ;
97+ }
98+
99+ $ reflection = new ReflectionClass ($ this ->aggregateClass ());
100+ $ reflectionMethod = $ reflection ->getMethod ($ handler ->method );
101+
102+ $ return = $ reflectionMethod ->invokeArgs (
103+ $ handler ->static ? null : $ aggregate ,
104+ [
105+ $ callableOrCommand ,
106+ ...$ this ->parameters ,
107+ ],
108+ );
109+ }
110+ }
82111
83112 if ($ aggregate !== null && $ return instanceof AggregateRoot) {
84113 throw new AggregateAlreadySet ();
@@ -107,6 +136,7 @@ final public function reset(): void
107136 {
108137 $ this ->givenEvents = [];
109138 $ this ->when = null ;
139+ $ this ->parameters = [];
110140 $ this ->expectedEvents = [];
111141 $ this ->expectedException = null ;
112142 $ this ->expectedExceptionMessage = null ;
0 commit comments