Magento – Magento 2 MEQP2 WARNING | The use of function file_get_contents() is discouraged

extensionsmagento-2.1magento2meqp2

I am getting WARNING | The use of function file_get_contents() is discouraged. but its working fine but not for MEQP2 its giving WARNING so how use alternate of function file_get_contents() in the code.

public function importFromTranslationFile($filePath)
{
    $fileContent = file_get_contents($filePath);
    if ($fileContent !== false) {
        $fileContent = trim($fileContent, '`');

        return json_decode($fileContent, true);
    } else {
        return false;
    }
}

Best Answer

Have a look at the Interfaces available inside Magento\Framework.

There are classes to help you, for example Magento\Framework\Filesystem\DriverInterface gives you access to a fileGetContents function:

/**
 * Retrieve file contents from given path
 *
 * @param string $path
 * @param string|null $flag
 * @param resource|null $context
 * @return string
 * @throws FileSystemException
 */
public function fileGetContents($path, $flag = null, $context = null);

Which is implemented inside Magento\Framework\Filesystem\Driver

/**
 * Retrieve file contents from given path
 *
 * @param string $path
 * @param string|null $flag
 * @param resource|null $context
 * @return string
 * @throws FileSystemException
 */
public function fileGetContents($path, $flag = null, $context = null)
{
    clearstatcache();
    $result = @file_get_contents($this->getScheme() . $path, $flag, $context);
    if (false === $result) {
        throw new FileSystemException(
            new \Magento\Framework\Phrase(
                'Cannot read contents from file "%1" %2',
                [$path, $this->getWarningMessage()]
            )
        );
    }
    return $result;
}

This is going to be your best option.

Related Topic