diff --git a/core/AssetManager/UIAsset/OnDiskUIAsset.php b/core/AssetManager/UIAsset/OnDiskUIAsset.php index 1c244207705931ccff16013393a7fcc840a95d7b..e9b19f8f6ae03ee6b881c55e7812325923bc8376 100644 --- a/core/AssetManager/UIAsset/OnDiskUIAsset.php +++ b/core/AssetManager/UIAsset/OnDiskUIAsset.php @@ -10,6 +10,7 @@ namespace Piwik\AssetManager\UIAsset; use Exception; use Piwik\AssetManager\UIAsset; +use Piwik\Filesystem; class OnDiskUIAsset extends UIAsset { @@ -58,12 +59,18 @@ class OnDiskUIAsset extends UIAsset { if ($this->exists()) { - if (!unlink($this->getAbsoluteLocation())) + try { + Filesystem::remove($this->getAbsoluteLocation()); + } catch (Exception $e) { throw new Exception("Unable to delete merged file : " . $this->getAbsoluteLocation() . ". Please delete the file and refresh"); + } // try to remove compressed version of the merged file. - @unlink($this->getAbsoluteLocation() . ".deflate"); - @unlink($this->getAbsoluteLocation() . ".gz"); + try { + Filesystem::remove($this->getAbsoluteLocation() . ".deflate"); + Filesystem::remove($this->getAbsoluteLocation() . ".gz"); + } catch (Exception $e) { + } } } diff --git a/core/Filesystem.php b/core/Filesystem.php index ea138dbfb0dad0b09d313baab8ae9f7e0d930fd1..1d3ae0d8bec9ba7944630441df558a765c3ea68b 100644 --- a/core/Filesystem.php +++ b/core/Filesystem.php @@ -410,6 +410,25 @@ class Filesystem return $converted; } + /** + * Remove a file. + * + * @param string $file + */ + public static function remove($file) + { + if (!file_exists($file)) { + return; + } + + $result = @unlink($file); + + // Testing if the file still exist avoids race conditions + if (!$result && file_exists($file)) { + throw new \RuntimeException('Unable to delete file ' . $file); + } + } + /** * @param $path * @return int diff --git a/tests/PHPUnit/Integration/FilesystemTest.php b/tests/PHPUnit/Integration/FilesystemTest.php index f3879927e562d5c4d601e7b555a1a02cf0fac830..0a17edacb85d4d2e5e0002932278d8c6437fc63b 100644 --- a/tests/PHPUnit/Integration/FilesystemTest.php +++ b/tests/PHPUnit/Integration/FilesystemTest.php @@ -8,6 +8,7 @@ namespace Piwik\Tests\Integration; +use Piwik\Container\StaticContainer; use Piwik\Filesystem; /** @@ -30,4 +31,18 @@ class FilesystemTest extends \PHPUnit_Framework_TestCase $this->assertNull($size); } + public function test_removeFile_shouldRemoveFile() + { + $tmpFile = StaticContainer::get('path.tmp') . '/filesystem-test-file'; + touch($tmpFile); + + Filesystem::remove($tmpFile); + + $this->assertFileNotExists($tmpFile); + } + + public function test_removeNonExistingFile_shouldNotThrowException() + { + Filesystem::remove('foo'); + } } \ No newline at end of file