Example #1
0
 /**
  * Deletes objects from Amazon S3 that match the result of a ListObjects operation. For example, this allows you
  * to do things like delete all objects that match a specific key prefix.
  *
  * @param string $bucket  Bucket that contains the object keys
  * @param string $prefix  Optionally delete only objects under this key prefix
  * @param string $regex   Delete only objects that match this regex
  * @param array  $options Options used when deleting the object:
  *     - before_delete: Callback to invoke before each delete. The callback will receive a
  *       Guzzle\Common\Event object with context.
  *
  * @see Mss\S3\S3Client::listObjects
  * @see Mss\S3\Model\ClearBucket For more options or customization
  * @return int Returns the number of deleted keys
  * @throws RuntimeException if no prefix and no regex is given
  */
 public function deleteMatchingObjects($bucket, $prefix = '', $regex = '', array $options = array())
 {
     if (!$prefix && !$regex) {
         throw new RuntimeException('A prefix or regex is required, or use S3Client::clearBucket().');
     }
     $clear = new ClearBucket($this, $bucket);
     $iterator = $this->getIterator('ListObjects', array('Bucket' => $bucket, 'Prefix' => $prefix));
     if ($regex) {
         $iterator = new FilterIterator($iterator, function ($current) use($regex) {
             return preg_match($regex, $current['Key']);
         });
     }
     $clear->setIterator($iterator);
     if (isset($options['before_delete'])) {
         $clear->getEventDispatcher()->addListener(ClearBucket::BEFORE_CLEAR, $options['before_delete']);
     }
     return $clear->clear();
 }