Search code examples
phplaravelinterfacephpstorm

Weird issue with parameter validation on usage of interface implementation


So basically I'm not sure if this is a PhpStorm issue parsing my code or if its a weird quirk of PHP and interfaces but basically I have the following interface

<?php

namespace App\Contracts;

/**
 * Interface IFileSource
 * @package App\Contracts
 */
interface IFileSource
{
    public function getFilesByPattern(string $filePattern) : array;
}

with the following implementation

<?php

namespace App\Sources;

use App\Contracts\IFileService;
use App\Services\File\FileService;

/**
 * Class FileSource
 * @package App\Sources
 */
class FileSource implements IFileSource
{
    /**
     * @var FileService
     */
    private $fileService;

    public function __construct (IFileService $fileService)
    {
        $this->fileService = $fileService;
    }


    /**
     * @param string $filePattern
     * @return File[]
     * NOTE THIS ASSUMES FILESYSTEM
     */
    public function getFilesByPattern (string $filePattern) : array
    {
        $filesDetails = $this->fileService->getFilesByPattern($filePattern);
        return [];
    }
}

and the usage

<?php

namespace App\Console\Commands;

use App\Contracts\IFileSource;
use App\Sources\FileSource;

class ImportXML extends Command
{

    /**
     * @var FileSource
     */
    protected $fileSource;

    public function __construct (IFileSource $fileSource)
    {
        parent::__construct();
        $this->fileSource = $fileSource;
    }

    public function handle () : void
    {     
            $filePattern = 'APATTERN';
            $files = $this->fileSource->getFilesByPattern($filePattern)
    }
}

My question relates to the usage of this implementation.

So the following is a valid usage:

$filePattern = 'APATTERN';
$this->fileSource->getFilesByPattern(filePattern)

But for some reason the following is also seen as a valid usage?

$filePattern = 'APATTERN';
$this->fileSource->getFilesByPattern(filePattern,filePattern,filePattern,filePattern,filePattern,filePattern,filePattern)

Why does it not care that i am not conforming to my implementation?


Solution

  • So incase someone else stumbles across this,

    thanks to LazyOne for the help explaining what i was doing wrong

    it was due to the fact i am enforcing the implementation in the PHPdoc rather than relying on the interface to enforce the type hinting (or adding the interface as the type hint instead of the implementation), once i changed this it began complaining as expected.

    Why enforce an implementation when the point of the interface is the enforce such things.

    Doh