-1

I am having issue getting the return type for this function as I have mixed types in the switch. I have used mixed, it blew up. I have used string|bool and several type for union type.

* @param  $value 
* @param  string $type

public function __construct(string $type,  $value)
    {  
        $this->type    = $type;
        $this->value   = $value;
    }

I have tried everything but it didn't pass the CI/CD pipeline (AWS)

public function getValue(bool $typed = false)
    {
        if (false === $typed) {
            return $this->value;
        }

        switch ($this->type) {
            case 'boolean':
                return (bool) $this->value;
            case 'datetime':
                if (empty($this->value)) {
                    return null;
                }

                return new \DateTime($this->value);
            case 'option_tags':
                return json_decode($this->value);
            default:
                return $this->value;
        }
    }

ERROR The following are the error

  Method App\Model\Resources::getValue() has no return typehint specified.  
  Parameter #1 $time of class DateTime constructor expects string, string|true given.                                 
  Parameter #1 $json of function json_decode expects string, bool|string given.
Curtis Lanz
  • 405
  • 2
  • 16

3 Answers3

1

In modern PHP you can either provide a list of all possible types:

// Tweak type list your exact needs
public function getValue(bool $typed = false): bool|DateTime|null

... or use mixed if the method can indeed return anything:

public function getValue(bool $typed = false): mixed

In older versions, you can only use the @return tag in the docblock:

/**
 * @param bool $typed
 * @return mixed
 * @throws Exception
 */

I understand PHPStan will be happy with all options.

Álvaro González
  • 142,137
  • 41
  • 261
  • 360
0

This ERROR is because you didn't declare the type that you want to return from getValue()

This is how you declare the return type

public function getValue(bool $typed = false): date
joeb
  • 777
  • 8
  • 28
0

You need to declare the return type to the function.

Simply to declare a return type, you need to put a : after the params, like this

public function store(Request $request): JsonResponse
runtimeTerror
  • 398
  • 3
  • 14