PHP code example of struggle-for-php / sfp-psalm-typed-local-variable-plugin

1. Go to this page and download the library: Download struggle-for-php/sfp-psalm-typed-local-variable-plugin library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

struggle-for-php / sfp-psalm-typed-local-variable-plugin example snippets



class Entity{}
interface Repository
{
    public function findOneById(int $id): ?Entity;
}
interface Mock{}
/** @return \DateTimeInterface&Mock */
function date_mock() {
    return new class('now') extends \DateTime implements Mock{};
}

class Demo
{
    /** @var Repository */
    private $repository;

    function typed_by_phpdoc() : void
    {
        /** @var string|null $nullable_string */
        $nullable_string = null;
        $nullable_string = "a";
        $nullable_string = true; // ERROR
    }

    function typed_by_assignement() : void
    {
        $date = new \DateTimeImmutable('now');
        if (\rand() % 2 === 0) {
            $date = new \DateTime('tomorrow'); // ERROR
        }

        $bool = true; //direct typed without doc-block
        $bool = false; // ok (currently, this plugin treats true|false as bool)
        $bool = 1; // ERROR
    }

    function mismatch_by_return() : void
    {
        /** @var Entity $entity */
        $entity = $this->repository->findOneById(1); // ERROR
    }

    function works_with_intersection() : void
    {
        /** @var \DateTimeInterface&Mock $date */
        $date = new \DateTime('now'); // ERROR
        $date = date_mock(); // success
    }
}

function foo(array $a) : void {
    /** @var string[] $x */
    $x = $a;
}

class A {}
class B extends A {}

function takesA(A $a) : void {
    /** @var B $b */
    $b = $a;
}

/** @var string $var1 */
/** @var bool $var2 */
$var1 = 'string'; // cannot determine type for $var1

// should fix like below
/** @var string $var1 */
$var1 = 'string';
/** @var bool $var2 */
$var2 = true;
xml
<issueHandlers>
  <PluginIssue name="MixedTypeCoercionTypedLocalVariableIssue">
      <errorLevel type="suppress">
          <file name="src/Foo.php"/>
      </errorLevel>
  </PluginIssue>
</issueHandlers>