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,18 @@
<?php

namespace Rector\Tests\TypeDeclarationDocblocks\Rector\Class_\AddVarArrayDocblockFromDimFetchAssignRector\Fixture;

final class SkipKeyedAssign
{
private array $response = [];

public function run(): void
{
$this->response[] = [
'name' => 'John',
];

$this->response['error'] = 'some error';
$this->response['done'] = true;
}
}
39 changes: 39 additions & 0 deletions rules/TypeDeclarationDocblocks/NodeFinder/ArrayDimFetchFinder.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,36 @@ public function findDimFetchAssignToPropertyName(Class_ $class, string $variable
return $exprs;
}

/**
* Any write to the property other than a bare append $this->someProperty[] = ...,
* i.e. a keyed dim assign $this->someProperty['key'] = ... or a direct $this->someProperty = ...
*/
public function hasNonAppendAssignToPropertyName(Class_ $class, string $variableName): bool
{
$assigns = $this->betterNodeFinder->findInstancesOfScoped($class->getMethods(), Assign::class);

foreach ($assigns as $assign) {
if ($assign->var instanceof PropertyFetch && $this->isThisPropertyNamed($assign->var, $variableName)) {
return true;
}

if (! $assign->var instanceof ArrayDimFetch) {
continue;
}

// bare append, already covered by findDimFetchAssignToPropertyName()
if (! $assign->var->dim instanceof Expr) {
continue;
}

if ($assign->var->var instanceof PropertyFetch && $this->isThisPropertyNamed($assign->var->var, $variableName)) {
return true;
}
}

return false;
}

/**
* @return ArrayDimFetch[]
*/
Expand All @@ -106,6 +136,15 @@ public function findByVariableName(Node $node, string $variableName): array
});
}

private function isThisPropertyNamed(PropertyFetch $propertyFetch, string $propertyName): bool
{
if (! $this->nodeNameResolver->isName($propertyFetch->var, 'this')) {
return false;
}

return $this->nodeNameResolver->isName($propertyFetch->name, $propertyName);
}

/**
* @return ArrayDimFetch[]
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,11 @@ public function refactor(Node $node): ?Node

$propertyName = $this->getName($property);

// a keyed dim assign ($this->prop['x'] = ...) or a direct assign carries a value type this rule does not read from bare appends; skip to avoid a too-narrow @var
if ($this->arrayDimFetchFinder->hasNonAppendAssignToPropertyName($node, $propertyName)) {
continue;
}

$assignedExprs = $this->arrayDimFetchFinder->findDimFetchAssignToPropertyName($node, $propertyName);

$assignedExprTypes = [];
Expand Down
Loading