1
0
mirror of https://github.com/danog/psalm.git synced 2024-11-27 04:45:20 +01:00
psalm/tests/ClosureTest.php

125 lines
3.0 KiB
PHP
Raw Normal View History

<?php
namespace Psalm\Tests;
use PhpParser\ParserFactory;
use PHPUnit_Framework_TestCase;
2016-11-02 07:29:00 +01:00
use Psalm\Checker\FileChecker;
use Psalm\Config;
use Psalm\Context;
class ClosureTest extends PHPUnit_Framework_TestCase
{
/** @var \PhpParser\Parser */
2016-11-02 07:29:00 +01:00
protected static $parser;
public static function setUpBeforeClass()
{
2016-11-02 07:29:00 +01:00
self::$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
2016-12-14 18:28:38 +01:00
$config = new TestConfig();
}
public function setUp()
{
2016-11-02 07:29:00 +01:00
FileChecker::clearCache();
}
public function testByRefUseVar()
{
2016-11-02 07:29:00 +01:00
$stmts = self::$parser->parse('<?php
2016-11-11 23:13:24 +01:00
/** @return void */
function run_function(\Closure $fnc) {
$fnc();
}
// here we have to make sure $data exists as a side-effect of calling `run_function`
// because it could exist depending on how run_function is implemented
/**
* @return void
* @psalm-suppress MixedArgument
*/
function fn() {
run_function(
2016-12-07 20:13:39 +01:00
/**
* @return void
*/
function() use(&$data) {
$data = 1;
}
);
echo $data;
}
fn();
');
2016-11-02 07:29:00 +01:00
$file_checker = new FileChecker('somefile.php', $stmts);
$context = new Context('somefile.php');
$file_checker->check(true, true, $context);
}
/**
2016-11-02 07:29:00 +01:00
* @expectedException \Psalm\Exception\CodeException
* @expectedExceptionMessage InvalidScalarArgument
*/
public function testWrongArg()
{
2016-11-02 07:29:00 +01:00
$stmts = self::$parser->parse('<?php
$bar = ["foo", "bar"];
$bam = array_map(
2016-12-07 20:13:39 +01:00
function(int $a) : int {
return $a + 1;
},
$bar
);
');
2016-11-02 07:29:00 +01:00
$file_checker = new FileChecker('somefile.php', $stmts);
$context = new Context('somefile.php');
$file_checker->check(true, true, $context);
}
2016-12-07 20:13:39 +01:00
/**
* @expectedException \Psalm\Exception\CodeException
* @expectedExceptionMessage InvalidReturnType
*/
public function testNoReturn()
{
$stmts = self::$parser->parse('<?php
$bar = ["foo", "bar"];
$bam = array_map(
function(string $a) : string {
},
$bar
);
');
$file_checker = new FileChecker('somefile.php', $stmts);
$context = new Context('somefile.php');
$file_checker->check(true, true, $context);
}
public function testInferredArg()
{
$stmts = self::$parser->parse('<?php
$bar = ["foo", "bar"];
$bam = array_map(
/**
* @psalm-suppress MissingReturnType
*/
function(string $a) {
return $a . "blah";
},
$bar
);
');
$file_checker = new FileChecker('somefile.php', $stmts);
$context = new Context('somefile.php');
$file_checker->check(true, true, $context);
}
}