Pergunta

Estou tendo problemas com a aprovação do módulo.e o relatório de validação do magento connect gera a seguinte mensagem

Uso direto de $_SERVER Superglobal detectado

como posso usar alternativa para

$_SERVER['REMOTE_ADDR']

no Magento 2.

Foi útil?

Solução

Usando uma classe auxiliar estendendo o /Magento/Framework/App/Helper/AbstractHelper classe você pode usar o seguinte:

$this->_remoteAddress

Está definido no AbstractHelper construtor de classe:

public function __construct(Context $context)
{
    $this->_moduleManager = $context->getModuleManager();
    $this->_logger = $context->getLogger();
    $this->_request = $context->getRequest();
    $this->_urlBuilder = $context->getUrlBuilder();
    $this->_httpHeader = $context->getHttpHeader();
    $this->_eventManager = $context->getEventManager();
    $this->_remoteAddress = $context->getRemoteAddress();
    $this->_cacheConfig = $context->getCacheConfig();
    $this->urlEncoder = $context->getUrlEncoder();
    $this->urlDecoder = $context->getUrlDecoder();
    $this->scopeConfig = $context->getScopeConfig();
}

Vem do /Magento/Framework/App/Helper/Context.php aula:

/**
 * @return \Magento\Framework\HTTP\PhpEnvironment\RemoteAddress
 */
public function getRemoteAddress()
{
    return $this->_remoteAddress;
}

E é um exemplo de \Magento\Framework\HTTP\PhpEnvironment\RemoteAddress :

/**
 * Retrieve Client Remote Address
 *
 * @param bool $ipToLong converting IP to long format
 * @return string IPv4|long
 */
public function getRemoteAddress($ipToLong = false)
{
    if ($this->remoteAddress === null) {
        foreach ($this->alternativeHeaders as $var) {
            if ($this->request->getServer($var, false)) {
                $this->remoteAddress = $this->request->getServer($var);
                break;
            }
        }

        if (!$this->remoteAddress) {
            $this->remoteAddress = $this->request->getServer('REMOTE_ADDR');
        }
    }

    if (!$this->remoteAddress) {
        return false;
    }

    return $ipToLong ? ip2long($this->remoteAddress) : $this->remoteAddress;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a magento.stackexchange
scroll top