1
0
mirror of https://github.com/danog/psalm.git synced 2024-12-11 16:59:45 +01:00
psalm/tests/ForeachTest.php

141 lines
4.1 KiB
PHP
Raw Normal View History

2016-12-12 05:41:11 +01:00
<?php
namespace Psalm\Tests;
class ForeachTest extends TestCase
2016-12-12 05:41:11 +01:00
{
use Traits\FileCheckerInvalidCodeParseTestTrait;
use Traits\FileCheckerValidCodeParseTestTrait;
/**
* @return array
*/
public function providerFileCheckerValidCodeParse()
{
return [
'iteratorAggregateIteration' => [
'<?php
class C implements IteratorAggregate
{
public function getIterator(): Iterator
{
return new ArrayIterator([]);
}
}
function loopT(Traversable $coll): void
{
foreach ($coll as $item) {}
}
function loopI(IteratorAggregate $coll): void
{
foreach ($coll as $item) {}
}
loopT(new C);
loopI(new C);',
'assignments' => [],
'error_levels' => [
'MixedAssignment', 'UndefinedThisPropertyAssignment',
],
],
2018-03-21 17:21:46 +01:00
'intersectionIterator' => [
'<?php
/**
* @param \Traversable<int>&\Countable $object
*/
function doSomethingUseful($object) : void {
echo count($object);
foreach ($object as $foo) {}
}'
],
'arrayIteratorIteration' => [
'<?php
class Item {
/**
* @var string
*/
public $prop = "var";
}
class Collection implements IteratorAggregate {
/**
* @var Item[]
*/
private $items = [];
public function add(Item $item): void
{
$this->items[] = $item;
}
/**
* @return \ArrayIterator<mixed, Item>
*/
public function getIterator(): \ArrayIterator
{
return new \ArrayIterator($this->items);
}
}
$collection = new Collection();
$collection->add(new Item());
foreach ($collection as $item) {
echo $item->prop;
}'
],
'foreachIntersectionTraversable' => [
'<?php
/** @var Countable&Traversable<int> */
$c = null;
foreach ($c as $i) {}',
],
];
}
2017-01-13 20:07:23 +01:00
/**
* @return array
2017-01-13 20:07:23 +01:00
*/
public function providerFileCheckerInvalidCodeParse()
2016-12-12 05:41:11 +01:00
{
return [
'continueOutsideLoop' => [
'<?php
continue;',
2017-05-27 02:05:57 +02:00
'error_message' => 'ContinueOutsideLoop',
],
'invalidIterator' => [
'<?php
foreach (5 as $a) {
}',
2017-05-27 02:05:57 +02:00
'error_message' => 'InvalidIterator',
],
'rawObjectIteration' => [
'<?php
class A {
/** @var ?string */
public $foo;
}
class B extends A {}
2018-01-11 21:50:45 +01:00
function bar(A $a): void {}
$arr = [];
if (rand(0, 10) > 5) {
$arr[] = new A;
} else {
$arr = new B;
}
foreach ($arr as $a) {
bar($a);
}',
'error_message' => 'RawObjectIteration',
],
];
2016-12-12 05:41:11 +01:00
}
}