1

When running PHP Code sniffer with the Magento 2 standard included in the dev tools on my code I receive the Ambiguous type array is NOT recommended warning quite frequently, is there a way to solve the warning?

php vendor/bin/phpcs --warning-severity=1 \ --standard=dev/tests/static/testsuite/Magento/Test/Php/_files/phpcs/ruleset.xml \ -d memory_limit=1024M --encoding=utf-8 --extensions=php,phtml \ vendor/vendorName/moduleName/

FOUND 0 ERROR(S) AND 3 WARNING(S) AFFECTING 3 LINE(S)

  • 24 | WARNING | Ambiguous type "array" for @var is NOT recommended
  • 42 | WARNING | Ambiguous type "array" for @return is NOT recommended
  • 63 | WARNING | Ambiguous type "array" for @return is NOT recommended
1

Entirely depends on context. The preferred solution would be one of two things (or possibly a combination of both):

  1. If your array is a set of values all having consistent type, specify that sub-type explicitly. For instance, if you have a $param array of \My\Class\Model\Something instances, rather than array $param, your type definition should be \My\Class\Model\Something[] $param.
  2. If your array is not a set of consistent type, but always follows the same pattern (it should!), convert it into an object with a defined interface.

For #2: Say you have an array to hold multiple values for the response:

$response = [
    'message' => 'Success',
    'error' => false,
];
return $response;

Rather than returning this array (type array), you should turn that into an object:

class Response extends \Magento\Framework\DataObject implements ResponseInterface
{
    public function setMessage(string $message)
    {
        return $this->setData('message', $message);
    }

    public function getMessage()
    {
        return $this->getData('message');
    }

    public function setError(bool $error)
    {
        return $this->setData('error', $error);
    }

    public function getError()
    {
        return $this->getData('error');
    }
}

And then use dependency injection to inject a ResponseFactory (as $this->responseFactory), then:

$response = $this->responseFactory->create();
$response->setMessage('Success');
$response->setError(false);
return $response;

And suddenly you have a defined interface, and every bit of code knows that response is going to be an instance of Response, with a message and an error flag, as well as the types of each, and how to get to them.

By defining types, you remove ambiguity and the possibility of anomalous behavior.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.