neilime / zf2-assets-bundle

AssetsBundle is a module for Zend Framework 2 allowing asset managment (bundling & caching)
https://neilime.github.io/zf2-assets-bundle/
MIT License
33 stars 20 forks source link

Avoid 404 error on empty CSS generated #56

Closed wambaloo closed 5 years ago

wambaloo commented 7 years ago

Hi !!!

I was looking for optimize my application on page loading, and I notice that an empty CSS file is already generated by assets-bundle plugin. This file (named like dev_0fead24561256adfebb64c5614a.css) is already empty and made page loading in Chrome and Firefox very long (because these browser send a 404 error when trying to load an empty CSS file). So I look into the source code to see how I can speed up my app by avoid this empty loading. I modify the following lines to optimize that, I let you see if it's the right way to do that or if I missed something. I think it could be a plus to integrate this case in your library to not generate an empty file and not include it in page loading.

In file AssetsBundle/AssetFile/AssetFilesCacheManager.php, line 184 to the end of the method, I replaced that:

else {
    \Zend\Stdlib\ErrorHandler::start();
    $sAssetFilePath = $oAssetFile->getAssetFilePath();
    if (!is_file($sAssetFilePath)) {
        throw new \LogicException('Asset file "' . $sAssetFilePath . '" does not exits');
    }
    copy($sAssetFilePath, $sCacheFilePath);
    \Zend\Stdlib\ErrorHandler::stop(true);
}
return $oAssetFile->setAssetFilePath($sCacheFilePath);

by:

else {
    \Zend\Stdlib\ErrorHandler::start();
    $sAssetFilePath = $oAssetFile->getAssetFilePath();
    if (!is_file($sAssetFilePath)) {
        throw new \LogicException('Asset file "' . $sAssetFilePath . '" does not exits');
    }
    /* ADD TO AVOID 404 LOADING DUE TO EMPTY CSS FILE */
    $size = filesize($sAssetFilePath);
    if ($size > 0) {
        copy($sAssetFilePath, $sCacheFilePath);
    } else {
        $oAssetFile = null;
    }
    \Zend\Stdlib\ErrorHandler::stop(true);
}
return (null !== $oAssetFile ? $oAssetFile->setAssetFilePath($sCacheFilePath) : null);

And in file AssetBundle/AssetFile/AssetFilesManager.php, line 212, I replaced:

return array($this->getAssetFilesCacheManager()->cacheAssetFile($oTmpAssetFile)->setAssetFileType(\AssetsBundle\AssetFile\AssetFile::ASSET_CSS));

by:

$cache = $this->getAssetFilesCacheManager()->cacheAssetFile($oTmpAssetFile);
$result = (null !== $cache) ? [$cache->setAssetFileType(\AssetsBundle\AssetFile\AssetFile::ASSET_CSS)] : [];
return $result;

I hope it will help !

neilime commented 7 years ago

Can you create a pull request please ?

wambaloo commented 7 years ago

Hi !

I could do it when my internet access will be open for windows command line in my job... proxy bloqued it so I can't clone the git repository and I can't commit... I hope I could do it soon !

chielsen commented 7 years ago

Would be great if this was fixed.