Skip to content
Merged
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

namespace Rector\Tests\Php81\Rector\FuncCall\NullToStrictStringFuncCallArgRector\Fixture;

class EntityWithMagicGet
{
protected array $_fields = [];

public function __get(string $field)
{
$value = null;
if (isset($this->_fields[$field])) {
$value = &$this->_fields[$field];
}

return $value;
}
}

$entity = new EntityWithMagicGet();
if ($entity->someProp) {
preg_replace('/\r\n|\n|\r/', '', $entity->someProp);
}
26 changes: 26 additions & 0 deletions rules/Php81/NodeManipulator/NullToStrictStringIntConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use PhpParser\Node\Expr\Cast\String_ as CastString_;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\PropertyFetch;
use PhpParser\Node\Expr\Ternary;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Scalar\Int_;
Expand All @@ -19,9 +20,11 @@
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\Native\ExtendedNativeParameterReflection;
use PHPStan\Reflection\ParametersAcceptor;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Type\ErrorType;
use PHPStan\Type\MixedType;
use PHPStan\Type\NullType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\Type;
use PHPStan\Type\UnionType;
use Rector\NodeAnalyzer\PropertyFetchAnalyzer;
Expand All @@ -35,6 +38,7 @@ public function __construct(
private ValueResolver $valueResolver,
private NodeTypeResolver $nodeTypeResolver,
private PropertyFetchAnalyzer $propertyFetchAnalyzer,
private ReflectionProvider $reflectionProvider,
) {
}

Expand Down Expand Up @@ -116,6 +120,10 @@ public function convertIfNull(

private function shouldSkipValue(Expr $expr, Scope $scope, bool $isTrait, string $targetType): bool
{
if ($this->isPropertyFetchOnClassWithMagicGet($expr)) {
return true;
}

$type = $this->nodeTypeResolver->getType($expr);
if ($type->isString()->yes() && $targetType === 'string') {
return true;
Expand Down Expand Up @@ -153,6 +161,24 @@ private function shouldSkipValue(Expr $expr, Scope $scope, bool $isTrait, string
return $this->shouldSkipTrait($expr, $type, $isTrait);
}

private function isPropertyFetchOnClassWithMagicGet(Expr $expr): bool
{
if (! $expr instanceof PropertyFetch) {
return false;
}

$varType = $this->nodeTypeResolver->getType($expr->var);
if (! $varType instanceof ObjectType) {
return false;
}

if (! $this->reflectionProvider->hasClass($varType->getClassName())) {
return false;
}

return $this->reflectionProvider->getClass($varType->getClassName())->hasMethod('__get');
}

private function isValidUnionType(Type $type): bool
{
if (! $type instanceof UnionType) {
Expand Down
Loading