Skip to content

Commit

Permalink
test: add test for offset access legal
Browse files Browse the repository at this point in the history
  • Loading branch information
rajyan committed May 5, 2024
1 parent 461cb89 commit ed98710
Show file tree
Hide file tree
Showing 2 changed files with 122 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -776,6 +776,29 @@ public function testMixed(): void
]);
}

public function testOffsetAccessLegal(): void
{
$this->checkExplicitMixed = true;
$this->analyse([__DIR__ . '/data/offset-access-legal.php'], [
[
'Cannot access offset 0 on Closure(): void.',
7,
],
[
'Cannot access offset 0 on stdClass.',
12,
],
[
'Cannot access offset 0 on array{\'test\'}|stdClass.',
96,
],
[
'Cannot access offset 0 on array{\'test\'}|(Closure(): void).',
98,
],
]);
}

public function dataReportPossiblyNonexistentArrayOffset(): iterable
{
yield [false, false, []];
Expand Down
99 changes: 99 additions & 0 deletions tests/PHPStan/Rules/Arrays/data/offset-access-legal.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
<?php declare(strict_types=1); // lint >= 8.0

namespace OffsetAccessLegal;

function closure(): void
{
(function(){})[0] ?? "error";
}

function nonArrayAccessibleObject()
{
(new \stdClass())[0] ?? "error";
}

function arrayAccessibleObject()
{
(new class implements \ArrayAccess {
public function offsetExists($offset) {
return true;
}

public function offsetGet($offset) {
return $offset;
}

public function offsetSet($offset, $value) {
}

public function offsetUnset($offset) {
}
})[0] ?? "error";
}

function array_(): void
{
[0][0] ?? "error";
}

function integer(): void
{
(0)[0] ?? 'ok';
}

function float(): void
{
(0.0)[0] ?? 'ok';
}

function null(): void
{
(null)[0] ?? 'ok';
}

function bool(): void
{
(true)[0] ?? 'ok';
}

function void(): void
{
((function (){})())[0] ?? 'ok';
}

function resource(): void
{
(tmpfile())[0] ?? 'ok';
}

function offsetAccessibleMaybeAndLegal(): void
{
$arrayAccessible = rand() ? (new class implements \ArrayAccess {
public function offsetExists($offset) {
return true;
}

public function offsetGet($offset) {
return $offset;
}

public function offsetSet($offset, $value) {
}

public function offsetUnset($offset) {
}
}) : false;

($arrayAccessible)[0] ?? "error";

(rand() ? "string" : true)[0] ?? "error";
}

function offsetAccessibleMaybeAndIllegal(): void
{
$arrayAccessible = rand() ? new \stdClass() : ['test'];

($arrayAccessible)[0] ?? "error";

(rand() ? function(){} : ['test'])[0] ?? "error";
}

0 comments on commit ed98710

Please sign in to comment.