|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Rector\PHPUnit\CodeQuality\NodeFactory; |
| 6 | + |
| 7 | +use PhpParser\Node\Expr; |
| 8 | +use PhpParser\Node\Expr\BinaryOp\Identical; |
| 9 | +use PhpParser\Node\Expr\ClassConstFetch; |
| 10 | +use PhpParser\Node\Expr\FuncCall; |
| 11 | +use PhpParser\Node\Expr\Instanceof_; |
| 12 | +use PhpParser\Node\Name; |
| 13 | +use PhpParser\Node\Name\FullyQualified; |
| 14 | +use PhpParser\Node\Scalar\Int_; |
| 15 | +use PhpParser\Node\Stmt; |
| 16 | +use PhpParser\Node\Stmt\Expression; |
| 17 | +use Rector\NodeNameResolver\NodeNameResolver; |
| 18 | +use Rector\PhpParser\Node\NodeFactory; |
| 19 | + |
| 20 | +final readonly class FromBinaryAndAssertExpressionsFactory |
| 21 | +{ |
| 22 | + public function __construct( |
| 23 | + private NodeFactory $nodeFactory, |
| 24 | + private NodeNameResolver $nodeNameResolver, |
| 25 | + ) { |
| 26 | + } |
| 27 | + |
| 28 | + /** |
| 29 | + * @param Expr[] $exprs |
| 30 | + * @return Stmt[]|null |
| 31 | + */ |
| 32 | + public function create(array $exprs): ?array |
| 33 | + { |
| 34 | + $assertMethodCalls = []; |
| 35 | + |
| 36 | + foreach ($exprs as $expr) { |
| 37 | + if ($expr instanceof Instanceof_) { |
| 38 | + if (! $expr->class instanceof Name) { |
| 39 | + return null; |
| 40 | + } |
| 41 | + |
| 42 | + $className = $expr->class->name; |
| 43 | + $assertMethodCalls[] = $this->nodeFactory->createMethodCall( |
| 44 | + 'this', |
| 45 | + 'assertInstanceOf', |
| 46 | + [new ClassConstFetch(new FullyQualified($className), 'class'), $expr->expr] |
| 47 | + ); |
| 48 | + |
| 49 | + continue; |
| 50 | + } |
| 51 | + |
| 52 | + if ($expr instanceof Identical) { |
| 53 | + if ($expr->left instanceof FuncCall && $this->nodeNameResolver->isName($expr->left, 'count')) { |
| 54 | + if ($expr->right instanceof Int_) { |
| 55 | + $countedExpr = $expr->left->getArgs()[0] |
| 56 | + ->value; |
| 57 | + |
| 58 | + // create assertCount() |
| 59 | + $assertMethodCalls[] = $this->nodeFactory->createMethodCall( |
| 60 | + 'this', |
| 61 | + 'assertCount', |
| 62 | + [$expr->right, $countedExpr] |
| 63 | + ); |
| 64 | + |
| 65 | + continue; |
| 66 | + } |
| 67 | + |
| 68 | + // unclear, fallback to no change |
| 69 | + return null; |
| 70 | + } |
| 71 | + |
| 72 | + // create assertSame() |
| 73 | + $assertMethodCalls[] = $this->nodeFactory->createMethodCall( |
| 74 | + 'this', |
| 75 | + 'assertSame', |
| 76 | + [$expr->right, $expr->left] |
| 77 | + ); |
| 78 | + } else { |
| 79 | + // not supported expr |
| 80 | + return null; |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + if ($assertMethodCalls === []) { |
| 85 | + return null; |
| 86 | + } |
| 87 | + |
| 88 | + $stmts = []; |
| 89 | + foreach ($assertMethodCalls as $assertMethodCall) { |
| 90 | + $stmts[] = new Expression($assertMethodCall); |
| 91 | + } |
| 92 | + |
| 93 | + return $stmts; |
| 94 | + } |
| 95 | +} |
0 commit comments