Skip to content

Instantly share code, notes, and snippets.

@jwage
Created November 7, 2022 23:29
Show Gist options
  • Save jwage/3e097860745ac4ab232868cc544b1ee9 to your computer and use it in GitHub Desktop.
Save jwage/3e097860745ac4ab232868cc544b1ee9 to your computer and use it in GitHub Desktop.
Add PHPUnit MockObject type hints to satisfy static analysis
<?php
$file = $argv[1];
$code = file_get_contents($file);
preg_match_all('/\$this->(.*)\s+=\s+\$this->createMock\((.*)::class\);/', $code, $matches);
foreach ($matches[2] as $key => $className) {
$propertyName = trim($matches[1][$key]);
$propertyCodeFind = sprintf(' private %s $%s;', $className, $propertyName);
$propertyCodeDocBlock = sprintf('/** @var %s&MockObject */', $className);
$propertyCodeReplace = sprintf(" %s\n%s", $propertyCodeDocBlock, $propertyCodeFind);
$code = str_replace($propertyCodeFind, $propertyCodeReplace, $code);
}
preg_match_all('/namespace (.*)\;/', $code, $matches2);
$code = str_replace($matches2[0][0], $matches2[0][0]."\nuse PHPUnit\Framework\MockObject\MockObject;", $code);
file_put_contents($file, $code);
echo passthru(sprintf('phpcbf %s', $file));
echo passthru(sprintf('psalm %s', $file));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment