1
0
mirror of https://github.com/danog/psalm.git synced 2024-11-26 20:34:47 +01:00
psalm/tests/ToStringTest.php

517 lines
17 KiB
PHP
Raw Normal View History

<?php
namespace Psalm\Tests;
2021-12-04 21:55:53 +01:00
use Psalm\Tests\Traits\InvalidCodeAnalysisTestTrait;
use Psalm\Tests\Traits\ValidCodeAnalysisTestTrait;
class ToStringTest extends TestCase
{
2021-12-04 21:55:53 +01:00
use InvalidCodeAnalysisTestTrait;
use ValidCodeAnalysisTestTrait;
2017-01-13 20:07:23 +01:00
/**
Add support for strict arrays, fix type alias intersection, fix array_is_list assertion on non-lists (#8395) * Immutable CodeLocation * Remove excess clones * Remove external clones * Remove leftover clones * Fix final clone issue * Immutable storages * Refactoring * Fixes * Fixes * Fix * Fix * Fixes * Simplify * Fixes * Fix * Fixes * Update * Fix * Cache global types * Fix * Update * Update * Fixes * Fixes * Refactor * Fixes * Fix * Fix * More caching * Fix * Fix * Update * Update * Fix * Fixes * Update * Refactor * Update * Fixes * Break one more test * Fix * FIx * Fix * Fix * Fix * Fix * Improve performance and readability * Equivalent logic * Fixes * Revert * Revert "Revert" This reverts commit f9175100c8452c80559234200663fd4c4f4dd889. * Fix * Fix reference bug * Make default TypeVisitor immutable * Bugfix * Remove clones * Partial refactoring * Refactoring * Fixes * Fix * Fixes * Fixes * cs-fix * Fix final bugs * Add test * Misc fixes * Update * Fixes * Experiment with removing different property * revert "Experiment with removing different property" This reverts commit ac1156e077fc4ea633530d51096d27b6e88bfdf9. * Uniform naming * Uniform naming * Hack hotfix * Clean up $_FILES ref #8621 * Undo hack, try fixing properly * Helper method * Remove redundant call * Partially fix bugs * Cleanup * Change defaults * Fix bug * Fix (?, hope this doesn't break anything else) * cs-fix * Review fixes * Bugfix * Bugfix * Improve logic * Add support for list{} and callable-list{} types, properly implement array_is_list assertions (fixes #8389) * Default to sealed arrays * Fix array_merge bug * Fixes * Fix * Sealed type checks * Properly infer properties-of and get_object_vars on final classes * Fix array_map zipping * Fix tests * Fixes * Fixes * Fix more stuff * Recursively resolve type aliases * Fix typo * Fixes * Fix array_is_list assertion on keyed array * Add BC docs * Fixes * fix * Update * Update * Update * Update * Seal arrays with count assertions * Fix #8528 * Fix * Update * Improve sealed array foreach logic * get_object_vars on template properties * Fix sealed array assertion reconciler logic * Improved reconciler * Add tests * Single source of truth for test types * Fix tests * Fixup tests * Fixup tests * Fixup tests * Update * Fix tests * Fix tests * Final fixes * Fixes * Use list syntax only when needed * Fix tests * Cs-fix * Update docs * Update docs * Update docs * Update docs * Update docs * Document missing types * Update docs * Improve class-string-map docs * Update * Update * I love working on psalm :) * Keep arrays unsealed by default * Fixup tests * Fix syntax mistake * cs-fix * Fix typo * Re-import missing types * Keep strict types only in return types * argc/argv fixes * argc/argv fixes * Fix test * Comment-out valinor code, pinging @romm pls merge https://github.com/CuyZ/Valinor/pull/246 so we can add valinor to the psalm docs :)
2022-11-05 22:34:42 +01:00
*
2017-01-13 20:07:23 +01:00
*/
public function providerValidCodeParse(): iterable
{
return [
'validToString' => [
'code' => '<?php
class A {
function __toString() {
return "hello";
}
}
2017-05-27 02:05:57 +02:00
echo (new A);',
],
'inheritedToString' => [
'code' => '<?php
class A {
function __toString() {
return "hello";
}
}
class B {
function __toString() {
return "goodbye";
}
}
class C extends B {}
$c = new C();
2018-09-17 18:15:45 +02:00
echo (string) $c;',
],
'goodCast' => [
'code' => '<?php
class A {
2018-01-11 21:50:45 +01:00
public function __toString(): string
{
return "hello";
}
}
2017-06-12 01:20:07 +02:00
/** @param string|A $b */
2018-01-11 21:50:45 +01:00
function fooFoo($b): void {}
2017-06-12 01:20:07 +02:00
/** @param A|string $b */
2018-01-11 21:50:45 +01:00
function barBar($b): void {}
2017-06-12 01:20:07 +02:00
fooFoo(new A());
2017-05-27 02:05:57 +02:00
barBar(new A());',
],
2018-04-30 06:19:35 +02:00
'resourceToString' => [
'code' => '<?php
2018-04-30 06:19:35 +02:00
$a = fopen("php://memory", "r");
if ($a === false) exit;
$b = (string) $a;',
],
'canBeObject' => [
'code' => '<?php
class A {
public function __toString() {
return "A";
}
}
/** @param string|object $s */
function foo($s) : void {}
foo(new A);',
],
'castArrayKey' => [
'code' => '<?php
/**
* @param string[] $arr
*/
function foo(array $arr) : void {
if (!$arr) {
return;
}
foreach ($arr as $i => $_) {}
echo (string) $i;
}',
],
'allowToStringAfterMethodExistsCheck' => [
'code' => '<?php
function getString(object $value) : ?string {
if (method_exists($value, "__toString")) {
return (string) $value;
}
return null;
}'
],
'refineToStringType' => [
'code' => '<?php
/** @psalm-return non-empty-string */
function doesCast() : string {
return (string) (new A());
}
/** @psalm-return non-empty-string */
function callsToString() : string {
return (new A())->__toString();
}
class A {
/** @psalm-return non-empty-string */
function __toString(): string {
return "ha";
}
}'
],
'intersectionCanBeString' => [
'code' => '<?php
interface EmptyInterface {}
class StringCastable implements EmptyInterface
{
public function __toString()
{
return \'I am castable\';
}
}
function factory(): EmptyInterface
{
return new StringCastable();
}
$object = factory();
if (method_exists($object, \'__toString\')) {
$a = (string) $object;
echo $a;
}
if (is_callable([$object, \'__toString\'])) {
$a = (string) $object;
echo $a;
2020-10-04 06:17:16 +02:00
}'
],
'PHP80-stringableInterface' => [
'code' => '<?php
2020-10-04 06:17:16 +02:00
interface Foo extends Stringable {}
function takesString(string $s) : void {}
function takesFoo(Foo $foo) : void {
/** @psalm-suppress ImplicitToStringCast */
takesString($foo);
}
2020-10-04 06:17:16 +02:00
class FooImplementer implements Foo {
public function __toString() : string {
return "hello";
}
}
takesFoo(new FooImplementer());',
'assertions' => [],
'ignored_issues' => [],
'php_version' => '8.0'
],
'implicitStringable' => [
'code' => '<?php
function foo(Stringable $s): void {}
class Bar {
public function __toString() {
return "foo";
}
}
foo(new Bar());',
'assertions' => [],
'ignored_issues' => [],
'php_version' => '8.0',
],
'toStringNever' => [
'code' => '<?php
class B{
public function __toString() {
throw new BadMethodCallException("bad");
}
}
'
],
'toStringToImplode' => [
'code' => '<?php
class Bar {
public function __toString() {
return "foo";
}
}
echo implode(":", [new Bar()]);',
],
];
}
2017-01-13 20:07:23 +01:00
/**
Add support for strict arrays, fix type alias intersection, fix array_is_list assertion on non-lists (#8395) * Immutable CodeLocation * Remove excess clones * Remove external clones * Remove leftover clones * Fix final clone issue * Immutable storages * Refactoring * Fixes * Fixes * Fix * Fix * Fixes * Simplify * Fixes * Fix * Fixes * Update * Fix * Cache global types * Fix * Update * Update * Fixes * Fixes * Refactor * Fixes * Fix * Fix * More caching * Fix * Fix * Update * Update * Fix * Fixes * Update * Refactor * Update * Fixes * Break one more test * Fix * FIx * Fix * Fix * Fix * Fix * Improve performance and readability * Equivalent logic * Fixes * Revert * Revert "Revert" This reverts commit f9175100c8452c80559234200663fd4c4f4dd889. * Fix * Fix reference bug * Make default TypeVisitor immutable * Bugfix * Remove clones * Partial refactoring * Refactoring * Fixes * Fix * Fixes * Fixes * cs-fix * Fix final bugs * Add test * Misc fixes * Update * Fixes * Experiment with removing different property * revert "Experiment with removing different property" This reverts commit ac1156e077fc4ea633530d51096d27b6e88bfdf9. * Uniform naming * Uniform naming * Hack hotfix * Clean up $_FILES ref #8621 * Undo hack, try fixing properly * Helper method * Remove redundant call * Partially fix bugs * Cleanup * Change defaults * Fix bug * Fix (?, hope this doesn't break anything else) * cs-fix * Review fixes * Bugfix * Bugfix * Improve logic * Add support for list{} and callable-list{} types, properly implement array_is_list assertions (fixes #8389) * Default to sealed arrays * Fix array_merge bug * Fixes * Fix * Sealed type checks * Properly infer properties-of and get_object_vars on final classes * Fix array_map zipping * Fix tests * Fixes * Fixes * Fix more stuff * Recursively resolve type aliases * Fix typo * Fixes * Fix array_is_list assertion on keyed array * Add BC docs * Fixes * fix * Update * Update * Update * Update * Seal arrays with count assertions * Fix #8528 * Fix * Update * Improve sealed array foreach logic * get_object_vars on template properties * Fix sealed array assertion reconciler logic * Improved reconciler * Add tests * Single source of truth for test types * Fix tests * Fixup tests * Fixup tests * Fixup tests * Update * Fix tests * Fix tests * Final fixes * Fixes * Use list syntax only when needed * Fix tests * Cs-fix * Update docs * Update docs * Update docs * Update docs * Update docs * Document missing types * Update docs * Improve class-string-map docs * Update * Update * I love working on psalm :) * Keep arrays unsealed by default * Fixup tests * Fix syntax mistake * cs-fix * Fix typo * Re-import missing types * Keep strict types only in return types * argc/argv fixes * argc/argv fixes * Fix test * Comment-out valinor code, pinging @romm pls merge https://github.com/CuyZ/Valinor/pull/246 so we can add valinor to the psalm docs :)
2022-11-05 22:34:42 +01:00
*
2017-01-13 20:07:23 +01:00
*/
public function providerInvalidCodeParse(): iterable
{
return [
'echoClass' => [
'code' => '<?php
class A {}
echo (new A);',
2020-06-29 21:06:11 +02:00
'error_message' => 'InvalidArgument',
],
'echoCastClass' => [
'code' => '<?php
class A {}
echo (string)(new A);',
'error_message' => 'InvalidCast',
],
'invalidToStringReturnType' => [
'code' => '<?php
class A {
2018-01-11 21:50:45 +01:00
function __toString(): void { }
}',
2017-05-27 02:05:57 +02:00
'error_message' => 'InvalidToString',
],
'invalidInferredToStringReturnType' => [
'code' => '<?php
class A {
function __toString() { }
}',
2017-05-27 02:05:57 +02:00
'error_message' => 'InvalidToString',
],
2020-10-28 03:29:49 +01:00
'invalidInferredToStringReturnTypeWithTruePhp8' => [
'code' => '<?php
2020-10-28 03:29:49 +01:00
class A {
function __toString() {
/** @psalm-suppress InvalidReturnStatement */
return true;
}
}',
'error_message' => 'InvalidToString',
'ignored_issues' => [],
'php_version' => '8.0'
2020-10-28 03:29:49 +01:00
],
'implicitCastWithStrictTypes' => [
'code' => '<?php declare(strict_types=1);
class A {
public function __toString(): string
{
return "hello";
}
}
function fooFoo(string $b): void {}
fooFoo(new A());',
'error_message' => 'InvalidArgument',
],
'implicitCastWithStrictTypesToEchoOrSprintf' => [
'code' => '<?php declare(strict_types=1);
class A {
public function __toString(): string
{
return "hello";
}
}
echo(new A());
sprintf("hello *", new A());',
'error_message' => 'ImplicitToStringCast',
],
'implicitCast' => [
'code' => '<?php
class A {
2018-01-11 21:50:45 +01:00
public function __toString(): string
{
return "hello";
}
}
2017-06-12 01:20:07 +02:00
2018-01-11 21:50:45 +01:00
function fooFoo(string $b): void {}
fooFoo(new A());',
2017-05-27 02:05:57 +02:00
'error_message' => 'ImplicitToStringCast',
],
'implicitCastToUnion' => [
'code' => '<?php
class A {
public function __toString(): string
{
return "hello";
}
}
/** @param string|int $b */
function fooFoo($b): void {}
fooFoo(new A());',
'error_message' => 'ImplicitToStringCast',
2017-05-27 02:05:57 +02:00
],
2017-06-12 01:20:07 +02:00
'implicitCastFromInterface' => [
'code' => '<?php
2017-06-12 01:20:07 +02:00
interface I {
public function __toString();
}
2018-01-11 21:50:45 +01:00
function takesString(string $str): void { }
2017-06-12 01:20:07 +02:00
2018-01-11 21:50:45 +01:00
function takesI(I $i): void
2017-06-12 01:20:07 +02:00
{
takesString($i);
}',
'error_message' => 'ImplicitToStringCast',
],
2018-04-30 06:19:35 +02:00
'resourceCannotBeCoercedToString' => [
'code' => '<?php
2018-04-30 06:19:35 +02:00
function takesString(string $s) : void {}
$a = fopen("php://memory", "r");
takesString($a);',
'error_message' => 'InvalidArgument',
],
'resourceOrFalseToString' => [
'code' => '<?php
$a = fopen("php://memory", "r");
if (rand(0, 1)) {
$a = [];
}
$b = (string) $a;',
'error_message' => 'PossiblyInvalidCast',
],
'cannotCastInsideString' => [
'code' => '<?php
class NotStringCastable {}
$object = new NotStringCastable();
echo "$object";',
'error_message' => 'InvalidCast',
],
2019-03-17 21:41:34 +01:00
'warnAboutNullableCast' => [
'code' => '<?php
2019-03-17 21:41:34 +01:00
class ClassWithToString {
public function __toString(): string {
return "";
}
}
function maybeShow(?string $message): void {
if ($message !== null) {
echo $message;
}
}
maybeShow(new ClassWithToString());',
'error_message' => 'ImplicitToStringCast',
],
'possiblyInvalidCastOnIsSubclassOf' => [
'code' => '<?php
class Foo {}
/**
* @param mixed $a
*/
function bar($a) : ?string {
/**
* @psalm-suppress MixedArgument
*/
if (is_subclass_of($a, Foo::class)) {
return "hello" . $a;
}
return null;
}',
'error_message' => 'PossiblyInvalidOperand',
],
'allowToStringAfterMethodExistsCheckWithTypo' => [
'code' => '<?php
function getString(object $value) : ?string {
if (method_exists($value, "__toStrong")) {
return (string) $value;
}
return null;
}',
'error_message' => 'InvalidCast',
],
'alwaysEvaluateToStringVar' => [
'code' => '<?php
/** @psalm-suppress UndefinedFunction */
fora((string) $address);',
'error_message' => 'UndefinedGlobalVariable',
],
'implicitStringableDisallowed' => [
'code' => '<?php
interface Stringable {
function __toString() {}
}
function foo(Stringable $s): void {}
class Bar {
public function __toString() {
return "foo";
}
}
foo(new Bar());',
'error_message' => 'InvalidArgument',
'ignored_issues' => [],
'php_version' => '7.4',
],
'implicitCastInArray' => [
'code' => '<?php
interface S {
public function __toString(): string;
}
/** @return array<array-key, string> */
function f(S $s): array {
return [$s];
}
',
'error_message' => 'ImplicitToStringCast'
],
'implicitCastInList' => [
'code' => '<?php
interface S {
public function __toString(): string;
}
/** @return list<string> */
function f(S $s): array {
return [$s];
}
',
'error_message' => 'ImplicitToStringCast'
],
'implicitCastInTuple' => [
'code' => '<?php
interface S {
public function __toString(): string;
}
Add support for strict arrays, fix type alias intersection, fix array_is_list assertion on non-lists (#8395) * Immutable CodeLocation * Remove excess clones * Remove external clones * Remove leftover clones * Fix final clone issue * Immutable storages * Refactoring * Fixes * Fixes * Fix * Fix * Fixes * Simplify * Fixes * Fix * Fixes * Update * Fix * Cache global types * Fix * Update * Update * Fixes * Fixes * Refactor * Fixes * Fix * Fix * More caching * Fix * Fix * Update * Update * Fix * Fixes * Update * Refactor * Update * Fixes * Break one more test * Fix * FIx * Fix * Fix * Fix * Fix * Improve performance and readability * Equivalent logic * Fixes * Revert * Revert "Revert" This reverts commit f9175100c8452c80559234200663fd4c4f4dd889. * Fix * Fix reference bug * Make default TypeVisitor immutable * Bugfix * Remove clones * Partial refactoring * Refactoring * Fixes * Fix * Fixes * Fixes * cs-fix * Fix final bugs * Add test * Misc fixes * Update * Fixes * Experiment with removing different property * revert "Experiment with removing different property" This reverts commit ac1156e077fc4ea633530d51096d27b6e88bfdf9. * Uniform naming * Uniform naming * Hack hotfix * Clean up $_FILES ref #8621 * Undo hack, try fixing properly * Helper method * Remove redundant call * Partially fix bugs * Cleanup * Change defaults * Fix bug * Fix (?, hope this doesn't break anything else) * cs-fix * Review fixes * Bugfix * Bugfix * Improve logic * Add support for list{} and callable-list{} types, properly implement array_is_list assertions (fixes #8389) * Default to sealed arrays * Fix array_merge bug * Fixes * Fix * Sealed type checks * Properly infer properties-of and get_object_vars on final classes * Fix array_map zipping * Fix tests * Fixes * Fixes * Fix more stuff * Recursively resolve type aliases * Fix typo * Fixes * Fix array_is_list assertion on keyed array * Add BC docs * Fixes * fix * Update * Update * Update * Update * Seal arrays with count assertions * Fix #8528 * Fix * Update * Improve sealed array foreach logic * get_object_vars on template properties * Fix sealed array assertion reconciler logic * Improved reconciler * Add tests * Single source of truth for test types * Fix tests * Fixup tests * Fixup tests * Fixup tests * Update * Fix tests * Fix tests * Final fixes * Fixes * Use list syntax only when needed * Fix tests * Cs-fix * Update docs * Update docs * Update docs * Update docs * Update docs * Document missing types * Update docs * Improve class-string-map docs * Update * Update * I love working on psalm :) * Keep arrays unsealed by default * Fixup tests * Fix syntax mistake * cs-fix * Fix typo * Re-import missing types * Keep strict types only in return types * argc/argv fixes * argc/argv fixes * Fix test * Comment-out valinor code, pinging @romm pls merge https://github.com/CuyZ/Valinor/pull/246 so we can add valinor to the psalm docs :)
2022-11-05 22:34:42 +01:00
/** @return strict-array{string} */
function f(S $s): array {
return [$s];
}
',
'error_message' => 'ImplicitToStringCast'
],
'implicitCastInShape' => [
'code' => '<?php
interface S {
public function __toString(): string;
}
Add support for strict arrays, fix type alias intersection, fix array_is_list assertion on non-lists (#8395) * Immutable CodeLocation * Remove excess clones * Remove external clones * Remove leftover clones * Fix final clone issue * Immutable storages * Refactoring * Fixes * Fixes * Fix * Fix * Fixes * Simplify * Fixes * Fix * Fixes * Update * Fix * Cache global types * Fix * Update * Update * Fixes * Fixes * Refactor * Fixes * Fix * Fix * More caching * Fix * Fix * Update * Update * Fix * Fixes * Update * Refactor * Update * Fixes * Break one more test * Fix * FIx * Fix * Fix * Fix * Fix * Improve performance and readability * Equivalent logic * Fixes * Revert * Revert "Revert" This reverts commit f9175100c8452c80559234200663fd4c4f4dd889. * Fix * Fix reference bug * Make default TypeVisitor immutable * Bugfix * Remove clones * Partial refactoring * Refactoring * Fixes * Fix * Fixes * Fixes * cs-fix * Fix final bugs * Add test * Misc fixes * Update * Fixes * Experiment with removing different property * revert "Experiment with removing different property" This reverts commit ac1156e077fc4ea633530d51096d27b6e88bfdf9. * Uniform naming * Uniform naming * Hack hotfix * Clean up $_FILES ref #8621 * Undo hack, try fixing properly * Helper method * Remove redundant call * Partially fix bugs * Cleanup * Change defaults * Fix bug * Fix (?, hope this doesn't break anything else) * cs-fix * Review fixes * Bugfix * Bugfix * Improve logic * Add support for list{} and callable-list{} types, properly implement array_is_list assertions (fixes #8389) * Default to sealed arrays * Fix array_merge bug * Fixes * Fix * Sealed type checks * Properly infer properties-of and get_object_vars on final classes * Fix array_map zipping * Fix tests * Fixes * Fixes * Fix more stuff * Recursively resolve type aliases * Fix typo * Fixes * Fix array_is_list assertion on keyed array * Add BC docs * Fixes * fix * Update * Update * Update * Update * Seal arrays with count assertions * Fix #8528 * Fix * Update * Improve sealed array foreach logic * get_object_vars on template properties * Fix sealed array assertion reconciler logic * Improved reconciler * Add tests * Single source of truth for test types * Fix tests * Fixup tests * Fixup tests * Fixup tests * Update * Fix tests * Fix tests * Final fixes * Fixes * Use list syntax only when needed * Fix tests * Cs-fix * Update docs * Update docs * Update docs * Update docs * Update docs * Document missing types * Update docs * Improve class-string-map docs * Update * Update * I love working on psalm :) * Keep arrays unsealed by default * Fixup tests * Fix syntax mistake * cs-fix * Fix typo * Re-import missing types * Keep strict types only in return types * argc/argv fixes * argc/argv fixes * Fix test * Comment-out valinor code, pinging @romm pls merge https://github.com/CuyZ/Valinor/pull/246 so we can add valinor to the psalm docs :)
2022-11-05 22:34:42 +01:00
/** @return strict-array{0:string} */
function f(S $s): array {
return [$s];
}
',
'error_message' => 'ImplicitToStringCast'
],
'implicitCastInIterable' => [
'code' => '<?php
interface S {
public function __toString(): string;
}
/** @return iterable<int, string> */
function f(S $s) {
return [$s];
}
',
'error_message' => 'ImplicitToStringCast'
],
2021-10-20 19:54:32 +02:00
'implicitCastInToString' => [
'code' => '<?php
2021-10-20 19:54:32 +02:00
declare(strict_types=1);
final class A
{
public function __toString(): string
{
return new SplFileInfo("a");
}
}
',
'error_message' => 'ImplicitToStringCast'
],
'toStringTypecastNonString' => [
2022-10-16 13:59:15 +02:00
'code' => '<?php
class A {
function __toString(): string {
return "ha";
}
}
$foo = new A();
echo (int) $foo;',
'error_message' => 'InvalidCast',
],
2022-09-20 10:59:46 +02:00
'riskyArrayToIntCast' => [
2022-10-16 13:59:15 +02:00
'code' => '<?php
2022-09-20 10:59:46 +02:00
echo (int) array();',
'error_message' => 'RiskyCast',
],
'riskyArrayToFloatCast' => [
2022-10-16 13:59:15 +02:00
'code' => '<?php
2022-09-20 10:59:46 +02:00
echo (float) array(\'hello\');',
'error_message' => 'RiskyCast',
],
];
}
}