44
55namespace Rector \PHPUnit \CodeQuality \NodeAnalyser ;
66
7+ use PhpParser \Node \Expr \Assign ;
8+ use PhpParser \Node \Expr \MethodCall ;
9+ use PhpParser \Node \Expr \PropertyFetch ;
710use PhpParser \Node \Name \FullyQualified ;
11+ use PhpParser \Node \Stmt \ClassMethod ;
12+ use PhpParser \Node \Stmt \Expression ;
813use PhpParser \Node \Stmt \Property ;
14+ use Rector \NodeNameResolver \NodeNameResolver ;
915use Rector \PHPUnit \Enum \PHPUnitClassName ;
1016
11- final class MockObjectPropertyDetector
17+ final readonly class MockObjectPropertyDetector
1218{
19+ public function __construct (
20+ private NodeNameResolver $ nodeNameResolver
21+ ) {
22+ }
23+
1324 public function detect (Property $ property ): bool
1425 {
1526 if (! $ property ->type instanceof FullyQualified) {
@@ -18,4 +29,48 @@ public function detect(Property $property): bool
1829
1930 return $ property ->type ->toString () === PHPUnitClassName::MOCK_OBJECT ;
2031 }
32+
33+ /**
34+ * @return array<string, MethodCall>
35+ */
36+ public function collectFromClassMethod (ClassMethod $ classMethod ): array
37+ {
38+ $ propertyNamesToCreateMockMethodCalls = [];
39+
40+ foreach ((array ) $ classMethod ->stmts as $ stmt ) {
41+ if (! $ stmt instanceof Expression) {
42+ continue ;
43+ }
44+
45+ if (! $ stmt ->expr instanceof Assign) {
46+ continue ;
47+ }
48+
49+ $ assign = $ stmt ->expr ;
50+
51+ if (! $ assign ->var instanceof PropertyFetch) {
52+ continue ;
53+ }
54+
55+ if (! $ assign ->expr instanceof MethodCall) {
56+ continue ;
57+ }
58+
59+ $ methodCall = $ assign ->expr ;
60+ if (! $ this ->nodeNameResolver ->isName ($ methodCall ->name , 'createMock ' )) {
61+ continue ;
62+ }
63+
64+ $ propertyFetch = $ assign ->var ;
65+ $ propertyName = $ this ->nodeNameResolver ->getName ($ propertyFetch ->name );
66+
67+ if (! is_string ($ propertyName )) {
68+ continue ;
69+ }
70+
71+ $ propertyNamesToCreateMockMethodCalls [$ propertyName ] = $ methodCall ;
72+ }
73+
74+ return $ propertyNamesToCreateMockMethodCalls ;
75+ }
2176}
0 commit comments