diff --git a/Imagine/Cache/Resolver/AwsS3Resolver.php b/Imagine/Cache/Resolver/AwsS3Resolver.php index 7da87a89c..772977d1d 100644 --- a/Imagine/Cache/Resolver/AwsS3Resolver.php +++ b/Imagine/Cache/Resolver/AwsS3Resolver.php @@ -46,6 +46,11 @@ class AwsS3Resolver implements ResolverInterface, CacheManagerAwareInterface */ protected $logger; + /** + * @var string + */ + protected $cachePrefix; + /** * Constructs a cache resolver storing images on Amazon S3. * @@ -82,6 +87,14 @@ public function setCacheManager(CacheManager $cacheManager) $this->cacheManager = $cacheManager; } + /** + * @param string $cachePrefix + */ + public function setCachePrefix($cachePrefix) + { + $this->cachePrefix = $cachePrefix; + } + /** * {@inheritDoc} */ @@ -184,7 +197,18 @@ public function setObjectUrlOption($key, $value) */ public function clear($cachePrefix) { - // TODO: implement cache clearing for Amazon S3 service + // Let's just avoid to clear the whole bucket if cache prefix is empty + if ($cachePrefix === '') { + return; + } + + try { + $response = $this->storage->deleteMatchingObjects($this->bucket, ltrim($cachePrefix, '/') . '/'); + + return true; + } catch (\Exception $e) { + return false; + } } /** @@ -197,7 +221,11 @@ public function clear($cachePrefix) */ protected function getObjectPath($path, $filter) { - return str_replace('//', '/', $filter.'/'.$path); + $path = $this->cachePrefix + ? sprintf('%s/%s/%s', $this->cachePrefix, $filter, $path) + : sprintf('%s/%s', $filter, $path); + + return str_replace('//', '/', $path); } /** diff --git a/Tests/Fixtures/S3Client.php b/Tests/Fixtures/S3Client.php index 622f83f0c..819ed04b4 100644 --- a/Tests/Fixtures/S3Client.php +++ b/Tests/Fixtures/S3Client.php @@ -13,4 +13,6 @@ public function putObject($args) { } public function deleteObject($args) { } public function getObjectUrl($bucket, $key, $expires = 0, $args = array()) { } + + public function deleteMatchingObjects($bucket, $prefix = '', $regex = '', array $options = array()) { } } diff --git a/Tests/Imagine/Cache/Resolver/AwsS3ResolverTest.php b/Tests/Imagine/Cache/Resolver/AwsS3ResolverTest.php index 4c70c1db7..b3b31e1c5 100644 --- a/Tests/Imagine/Cache/Resolver/AwsS3ResolverTest.php +++ b/Tests/Imagine/Cache/Resolver/AwsS3ResolverTest.php @@ -229,12 +229,24 @@ public function testRemoveNotExisting() $this->assertTrue($resolver->remove('thumb/some-folder/targetpath.jpg', 'thumb')); } - public function testClearIsDisabled() + public function testClear() + { + $s3 = $this->getMock('Aws\S3\S3Client'); + $s3 + ->expects($this->once()) + ->method('deleteMatchingObjects') + ; + + $resolver = new AwsS3Resolver($s3, 'images.example.com'); + $this->assertTrue($resolver->clear('cache')); + } + + public function testClearWithoutPrefix() { $s3 = $this->getMock('Aws\S3\S3Client'); $s3 ->expects($this->never()) - ->method('deleteObject') + ->method('deleteMatchingObjects') ; $resolver = new AwsS3Resolver($s3, 'images.example.com');