Skip to content

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

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
}
],
"require": {
"php": "^7.2.0 || ^8.1.0",
"php": "^8.1.0",
"ext-dom": "*",
"laminas/laminas-code": "~3.3.0 || ~3.4.1 || ~3.5.1 || ^4.5 || ^4.10",
"phpstan/phpstan": "^2.0",
Expand Down
7 changes: 7 additions & 0 deletions extension.neon
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,13 @@ services:
classLoaderProvider: @classLoaderProvider
tags:
- phpstan.magento.autoloader
interceptorAutoloader:
class: bitExpert\PHPStan\Magento\Autoload\InterceptorAutoloader
arguments:
cache: @autoloaderCache
classLoaderProvider: @classLoaderProvider
tags:
- phpstan.magento.autoloader
extensionInterfaceAutoloader:
class: bitExpert\PHPStan\Magento\Autoload\ExtensionInterfaceAutoloader
arguments:
Expand Down
5 changes: 4 additions & 1 deletion phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ parameters:
-
message: '~is not covered by backward compatibility promise.~'
path: src/bitExpert/PHPStan/Magento/Autoload/ExtensionInterfaceAutoloader.php
-
message: '~is not covered by backward compatibility promise.~'
path: src/bitExpert/PHPStan/Magento/Autoload/InterceptorAutoloader.php
-
message: '~is not covered by backward compatibility promise.~'
path: src/bitExpert/PHPStan/Magento/Reflection/Framework/Session/SessionManagerMagicMethodReflectionExtension.php
Expand Down Expand Up @@ -69,4 +72,4 @@ parameters:
path: tests/bitExpert/PHPStan/Magento/Type/TestFrameworkObjectManagerDynamicReturnTypeExtensionUnitTest.php
-
message: '~PHPDoc tag @var assumes the expression with type~'
path: tests/bitExpert/PHPStan/Magento/Type/TestFrameworkObjectManagerDynamicReturnTypeExtensionUnitTest.php
path: tests/bitExpert/PHPStan/Magento/Type/TestFrameworkObjectManagerDynamicReturnTypeExtensionUnitTest.php
336 changes: 336 additions & 0 deletions src/bitExpert/PHPStan/Magento/Autoload/InterceptorAutoloader.php
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();
$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
{
$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(...));
}
}
20 changes: 20 additions & 0 deletions tests/bitExpert/PHPStan/Magento/Autoload/Helper.php
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
{
}
Loading