-
Notifications
You must be signed in to change notification settings - Fork 27
Add Interceptor Autoloader #345
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
d97f0a6
2d776a1
214a677
362e508
c12221e
b6f2c46
70c62b1
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,336 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the phpstan-magento package. | ||
* | ||
* (c) bitExpert AG | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
* | ||
* This file uses modified excerpts from the Magento Framework. That code | ||
* is Copyright Magento, Inc. which is licensed under OSL 3.0. You can | ||
* contact [email protected] for a copy. | ||
*/ | ||
declare(strict_types=1); | ||
|
||
namespace bitExpert\PHPStan\Magento\Autoload; | ||
|
||
use bitExpert\PHPStan\Magento\Autoload\DataProvider\ClassLoaderProvider; | ||
use Laminas\Code\Generator\ValueGenerator; | ||
use Magento\Framework\Code\Generator\ClassGenerator; | ||
use Magento\Framework\GetParameterClassTrait; | ||
use PHPStan\Cache\Cache; | ||
use ReflectionClass; | ||
use ReflectionIntersectionType; | ||
use ReflectionNamedType; | ||
use ReflectionUnionType; | ||
|
||
/** | ||
* @phpstan-type MethodDef array{name:non-empty-string, body:string, parameters: ParameterInfo[], returnType?:string|null, docblock?:array<string,string>} | ||
* @phpstan-type ParameterInfo array{name:non-empty-string, passedByReference:bool, variadic?:true, type?:string, defaultValue?:mixed} | ||
*/ | ||
class InterceptorAutoloader implements Autoloader | ||
{ | ||
use GetParameterClassTrait; | ||
|
||
public function __construct(private Cache $cache, private ClassLoaderProvider $classLoaderProvider) | ||
{ | ||
} | ||
|
||
/** | ||
* @param string $class | ||
* @throws \ReflectionException | ||
*/ | ||
public function autoload(string $class): void | ||
{ | ||
if (preg_match('#\\\Interceptor#', $class) !== 1) { | ||
return; | ||
} | ||
|
||
// fix for PHPStan 1.7.5 and later: Classes generated by autoloaders are supposed to "win" against | ||
// local classes in your project. We need to check first if classes exists locally before generating them! | ||
$pathToLocalClass = $this->classLoaderProvider->findFile($class); | ||
if ($pathToLocalClass === false) { | ||
$pathToLocalClass = $this->cache->load($class, ''); | ||
if ($pathToLocalClass === null) { | ||
$this->cache->save($class, '', $this->getFileContents($class)); | ||
$pathToLocalClass = $this->cache->load($class, ''); | ||
} | ||
} | ||
|
||
require_once($pathToLocalClass); | ||
} | ||
|
||
/** | ||
* Generate the proxy file content as Magento would. | ||
* | ||
* @param string $class | ||
* @return string | ||
* @throws \ReflectionException | ||
*/ | ||
protected function getFileContents(string $class): string | ||
{ | ||
$namespace = explode('\\', ltrim($class, '\\')); | ||
array_pop($namespace); // Remove "Interceptor" from the class name | ||
$originalClassname = implode('\\', $namespace); | ||
|
||
if (!class_exists($originalClassname)) { | ||
throw new \RuntimeException("Class ${originalClassname} for Interceptor does not exist"); | ||
} | ||
$reflectionClass = new ReflectionClass($originalClassname); | ||
|
||
$methods = [$this->_getDefaultConstructorDefinition($reflectionClass)]; | ||
$publicMethods = $reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC); | ||
foreach ($publicMethods as $method) { | ||
if (!$method->isInternal() && $this->isInterceptedMethod($method)) { | ||
$methods[] = $this->_getMethodInfo($method); | ||
} | ||
} | ||
|
||
$generator = new ClassGenerator(); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It's not ideal that we rely here on code from Magento itself, as this can confuse PHPStan during the code analysis. PHPStan extension should ideally never load and execute code from the code base they analyse. That's the 2nd reason I had to implement a custom logic for the code generation. |
||
$generator->setName($class) | ||
->addMethods($methods); | ||
|
||
$interfaces = []; | ||
if ($reflectionClass->isInterface()) { | ||
$interfaces[] = $originalClassname; | ||
} else { | ||
$generator->setExtendedClass($originalClassname); | ||
} | ||
$generator->addTrait('\\' . \Magento\Framework\Interception\Interceptor::class); | ||
$interfaces[] = '\\' . \Magento\Framework\Interception\InterceptorInterface::class; | ||
$generator->setImplementedInterfaces($interfaces); | ||
|
||
$code = $generator->generate(); | ||
return '<?php'.PHP_EOL.PHP_EOL.$this->_fixCodeStyle($code); | ||
} | ||
|
||
protected function _fixCodeStyle(string $sourceCode): string | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We are not in Magento, we don't need underscores to identify non-public methods :) There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This was lifted directly out of Magento, but I'm happy to adjust it if desired :) There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I am fine with the function names, just the underscores have to go to make the CI pipeline happy :) There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I can take care of that next week! |
||
{ | ||
$sourceCode = str_replace(' array (', ' array(', $sourceCode); | ||
$sourceCode = preg_replace("/{\n{2,}/m", "{\n", $sourceCode) ?? ''; | ||
return preg_replace("/\n{2,}}/m", "\n}", $sourceCode) ?? ''; | ||
} | ||
|
||
/** | ||
* @return MethodDef | ||
*/ | ||
protected function _getMethodInfo(\ReflectionMethod $method): array | ||
{ | ||
$parameters = array_map([$this, '_getMethodParameterInfo'], $method->getParameters()); | ||
|
||
$returnTypeValue = $this->getReturnTypeValue($method); | ||
$methodInfo = [ | ||
'name' => ($method->returnsReference() ? '& ' : '') . $method->getName(), | ||
'parameters' => $parameters, | ||
'body' => str_replace( | ||
[ | ||
'%method%', | ||
'%return%', | ||
'%parameters%' | ||
], | ||
[ | ||
$method->getName(), | ||
$returnTypeValue === 'void' ? '' : 'return ', | ||
$this->_getParameterList($parameters) | ||
], | ||
<<<'METHOD_BODY' | ||
$pluginInfo = $this->pluginList->getNext($this->subjectType, '%method%'); | ||
%return%$pluginInfo ? $this->___callPlugins('%method%', func_get_args(), $pluginInfo) : parent::%method%(%parameters%); | ||
METHOD_BODY | ||
), | ||
'returnType' => $returnTypeValue, | ||
'docblock' => ['shortDescription' => '{@inheritdoc}'], | ||
]; | ||
|
||
return $methodInfo; | ||
} | ||
|
||
/** | ||
* @param ReflectionClass<object> $reflectionClass | ||
* @return MethodDef | ||
*/ | ||
private function _getDefaultConstructorDefinition(ReflectionClass $reflectionClass) | ||
{ | ||
$constructor = $reflectionClass->getConstructor(); | ||
$parameters = []; | ||
$body = "\$this->___init();\n"; | ||
if ($constructor !== null) { | ||
$parameters = array_map($this->_getMethodParameterInfo(...), $constructor->getParameters()); | ||
|
||
$body .= count($parameters) > 0 | ||
? "parent::__construct({$this->_getParameterList($parameters)});" | ||
: "parent::__construct();"; | ||
} | ||
|
||
return [ | ||
'name' => '__construct', | ||
'parameters' => $parameters, | ||
'body' => $body | ||
]; | ||
} | ||
|
||
/** | ||
* @param \ReflectionParameter $parameter | ||
* @return ParameterInfo | ||
*/ | ||
protected function _getMethodParameterInfo(\ReflectionParameter $parameter) | ||
{ | ||
$parameterInfo = [ | ||
'name' => $parameter->getName(), | ||
'passedByReference' => $parameter->isPassedByReference() | ||
]; | ||
if ($parameter->isVariadic()) { | ||
$parameterInfo['variadic'] = $parameter->isVariadic(); | ||
} | ||
|
||
if (($type = $this->extractParameterType($parameter)) !== null) { | ||
$parameterInfo['type'] = $type; | ||
} | ||
if (($default = $this->extractParameterDefaultValue($parameter)) !== null) { | ||
$parameterInfo['defaultValue'] = $default; | ||
} | ||
|
||
return $parameterInfo; | ||
} | ||
|
||
private function extractParameterDefaultValue( | ||
\ReflectionParameter $parameter | ||
): ?ValueGenerator { | ||
$value = null; | ||
if ($parameter->isOptional() && $parameter->isDefaultValueAvailable()) { | ||
$valueType = ValueGenerator::TYPE_AUTO; | ||
$defaultValue = $parameter->getDefaultValue(); | ||
if ($defaultValue === null) { | ||
$valueType = ValueGenerator::TYPE_NULL; | ||
} | ||
$value = new ValueGenerator($defaultValue, $valueType); | ||
} | ||
|
||
return $value; | ||
} | ||
|
||
/** | ||
* @param ParameterInfo[] $parameters | ||
* @return string | ||
*/ | ||
protected function _getParameterList(array $parameters) | ||
{ | ||
return implode( | ||
', ', | ||
array_map( | ||
function ($item) { | ||
$output = ''; | ||
if (isset($item['variadic']) && $item['variadic']) { | ||
$output .= '... '; | ||
} | ||
|
||
$output .= "\${$item['name']}"; | ||
return $output; | ||
}, | ||
$parameters | ||
) | ||
); | ||
} | ||
|
||
private function extractParameterType( | ||
\ReflectionParameter $parameter | ||
): ?string { | ||
if (!$parameter->hasType()) { | ||
return null; | ||
} | ||
|
||
$parameterType = $parameter->getType(); | ||
|
||
if ($parameterType === null) { | ||
return null; | ||
} elseif ($parameterType instanceof ReflectionUnionType) { | ||
$parameterType = $parameterType->getTypes(); | ||
$parameterType = implode('|', $parameterType); | ||
} elseif ($parameterType instanceof ReflectionIntersectionType) { | ||
$parameterType = $parameterType->getTypes(); | ||
$parameterType = implode('&', $parameterType); | ||
} elseif ($parameterType instanceof ReflectionNamedType) { | ||
$parameterType = $parameterType->getName(); | ||
} | ||
|
||
$typeName = null; | ||
if ($parameterType === 'array') { | ||
$typeName = 'array'; | ||
} elseif (($parameterClass = $this->getParameterClass($parameter)) !== null) { | ||
$typeName = $this->_getFullyQualifiedClassName($parameterClass->getName()); | ||
} elseif ($parameterType === 'callable') { | ||
$typeName = 'callable'; | ||
} elseif (is_string($parameterType)) { | ||
$typeName = $parameterType; | ||
} | ||
|
||
// Type "?array|string|null" is a union type, and therefore cannot be also marked nullable with the "?" prefix | ||
if ($parameter->allowsNull() && $typeName !== 'mixed') { | ||
$typeName = $typeName === null || str_contains($typeName, "null") ? $typeName : '?' . $typeName; | ||
} | ||
|
||
return $typeName; | ||
} | ||
|
||
protected function isInterceptedMethod(\ReflectionMethod $method): bool | ||
{ | ||
return !($method->isConstructor() || $method->isFinal() || $method->isStatic() || $method->isDestructor()) && | ||
!in_array($method->getName(), ['__sleep', '__wakeup', '__clone', '_resetState'], true); | ||
} | ||
|
||
protected function _getFullyQualifiedClassName(string $className): string | ||
{ | ||
return $className !== '' ? '\\' . ltrim($className, '\\') : ''; | ||
} | ||
|
||
private function getReturnTypeValue(\ReflectionMethod $method): ?string | ||
{ | ||
$returnTypeValue = null; | ||
$returnType = $method->getReturnType(); | ||
if ($returnType !== null) { | ||
if ($returnType instanceof ReflectionUnionType || $returnType instanceof ReflectionIntersectionType) { | ||
return $this->getReturnTypeValues($returnType); | ||
} | ||
if (!$returnType instanceof \ReflectionNamedType) { | ||
return null; | ||
} | ||
|
||
$className = $method->getDeclaringClass()->getName(); | ||
$returnTypeValue = ($returnType->allowsNull() && $returnType->getName() !== 'mixed' ? '?' : ''); | ||
$returnTypeValue .= ($returnType->getName() === 'self') | ||
? ltrim($className, '\\') | ||
: $returnType->getName(); | ||
} | ||
|
||
return $returnTypeValue; | ||
} | ||
|
||
private function getReturnTypeValues( | ||
ReflectionIntersectionType|ReflectionUnionType $returnType, | ||
): string { | ||
$returnTypeValue = []; | ||
|
||
foreach ($returnType->getTypes() as $type) { | ||
if ($type instanceof ReflectionNamedType) { | ||
$returnTypeValue[] = $type->getName(); | ||
} | ||
} | ||
|
||
return implode( | ||
$returnType instanceof ReflectionUnionType ? '|' : '&', | ||
$returnTypeValue | ||
); | ||
} | ||
|
||
public function register(): void | ||
{ | ||
\spl_autoload_register($this->autoload(...), true, false); | ||
} | ||
|
||
public function unregister(): void | ||
{ | ||
\spl_autoload_unregister($this->autoload(...)); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the phpstan-magento package. | ||
* | ||
* (c) bitExpert AG | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
declare(strict_types=1); | ||
|
||
namespace bitExpert\PHPStan\Magento\Autoload; | ||
|
||
/** | ||
* Dummy class that can be loaded via the Autoloader in the test cases. | ||
*/ | ||
class Helper | ||
{ | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Did you change this because of your project requirements?
While I think the extension is technically compatible with PHP 7.x, I'd rather not like to soften it here as our CI pipeline currently only checks for PHP 8.x as it turned out way too complex to support PHP 7.x & 8.x plus all the various Magento versions.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think you perhaps misread this change, as it removed PHP 7.2 support from the library (due to some PHP 8 only code in this PR)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks like I need better glasses. My bad!