codeigniter4 / CodeIgniter4

Open Source PHP Framework (originally from EllisLab)
https://codeigniter.com/
MIT License
5.4k stars 1.9k forks source link

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

Open TalhaAshar01 opened 3 months ago

TalhaAshar01 commented 3 months ago

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
kenjis commented 3 months ago

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 commented 3 months ago

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);
    }