cómo solucionar el "Uso directo de $_SERVER Superglobal detectado" en Magento 2
-
29-09-2020 - |
Pregunta
Tengo problemas con la aprobación del módulo.y el informe de validación de magento connect genera el siguiente mensaje
Detectado uso directo de $_SERVER Superglobal
¿Cómo puedo usar alternativa para?
$_SERVER['REMOTE_ADDR']
en Magento 2.
Solución
Usando una clase auxiliar que extiende el /Magento/Framework/App/Helper/AbstractHelper
clase puedes utilizar lo siguiente:
$this->_remoteAddress
Está ambientado en el AbstractHelper
constructor de clase:
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();
}
Viene de la /Magento/Framework/App/Helper/Context.php
clase:
/**
* @return \Magento\Framework\HTTP\PhpEnvironment\RemoteAddress
*/
public function getRemoteAddress()
{
return $this->_remoteAddress;
}
Y es un ejemplo 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 bajo: CC-BY-SA con atribución
No afiliado a magento.stackexchange