CodeIgniter4 icon indicating copy to clipboard operation
CodeIgniter4 copied to clipboard

Bug: IDE warnings on static::getSharedInstance() return type mismatch

Open TalhaAshar01 opened this issue 1 year ago • 2 comments

PHP Version

8.1

CodeIgniter4 Version

4.5.4

CodeIgniter4 Installation Method

Composer (using codeigniter4/appstarter)

Which operating systems have you tested for this bug?

macOS

Which server did you use?

apache

Database

No response

What happened?

I recently upgraded my CI4 to version 4.5.4 from 4.2.5 and noticed that that static::static::getSharedInstance() function had its doc comment updated to return 'object' instead of 'mixed'.

Places where this function is used in my codebase now show a warning on the getSharedInstance line in the IDE as follows. This is also the case for CI4's code using this function under the 'System' directory.

public static function example($getShared = true): MyClass
 {
        if ($getShared) {
             return static::getSharedInstance('MyClass');
       }
     
       return new MyClass();
}

Warning: Return value is expected to be 'MyClass', 'object' returned.

Any plans to make adjustments for this?

Steps to Reproduce

1- Use the static::getSharedInstance() function to return in a class that has a class as the defined return type

Expected Output

Removal of type mismatch warnings

Anything else?

Screenshot 2024-08-22 at 2 51 35 PM

TalhaAshar01 avatar Aug 22 '24 09:08 TalhaAshar01

Thank you for reporting.

If you have an idea to fix the issue, feel free to send a PR. https://github.com/codeigniter4/CodeIgniter4/blob/develop/contributing/pull_request.md

kenjis avatar Aug 22 '24 10:08 kenjis

An easy fix would be like this.

    /**
     * The Router class uses a RouteCollection's array of routes, and determines
     * the correct Controller and Method to execute.
     *
     * @return Router
     */
    public static function router(?RouteCollectionInterface $routes = null, ?Request $request = null, bool $getShared = true)
    {
        if ($getShared) {
            /** @var Router $instance */
            $instance = static::getSharedInstance('router', $routes, $request);

            return $instance;
        }

        $routes ??= AppServices::get('routes');
        $request ??= AppServices::get('request');

        return new Router($routes, $request);
    }

kenjis avatar Aug 22 '24 10:08 kenjis

Please use phpstan along with our own phpstan-codeigniter. If I recall right, phpstorm uses phpstan's return type analysis to detect issues. With https://github.com/CodeIgniter/phpstan-codeigniter/commit/89fe4612f4795ed0d2542ab5f188da4fa0523379, getSharedInstance() no longer returns the generic object type.

paulbalandan avatar Apr 20 '25 12:04 paulbalandan