Thursday 31 January 2019

Rename all existing files on AWS S3 Bucket using Laravel Storage library

Follow below steps to rename existing files on a selected directory on S3 Bucket.

1. Lets say your config/filesystems.php looks like this:
'disks' => [
  's3_test_bucket' => [
        'driver' => 's3',
        'key'    => env('AWS_KEY', 'your_aws_key_here'),
        'secret' => env('AWS_SECRET','your_aws_secret_here'),
        'region' =>  env('AWS_REGION', 'your_aws_region_here'),
        'version' => 'latest',
        'bucket'  => 'my-test-bucket',
  ],
];

2. Let's say, you have my-test-bucket on your AWS S3.

3. Lets say you have following files inside the my-test-bucket/test-directory directory.
i.e.
- test-files-1.csv
- test-files-2.csv
- test-files-3.csv

3. Call below function to rename existing files on a selected directory on S3 Bucket.
$directoryPath = 'test-directory';
$storage = new MyStorageRepository();
$storage->renameAnyExistingFilesOnImportDirectory('my-test-bucket', 'test-directory');

4. Output: files should be rename as below on my-test-bucket/test-directory directory:
- test-files-1--1548870936.csv
- test-files-2--1548870936.csv
- test-files-3--1548870936.csv

5. Include the below library class or methods on your class and you should be good.

use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Storage;

class MyStorageRepository
{
    public function renameAnyExistingFilesOnImportDirectory($bucket, $directoryPath)
    {
        $directoryPath = App::environment() . '/' . $directoryPath;
        $storage = Storage::disk('s3_test_bucket');

        $suffix = '--' . time(); // File suffix to rename.

        if ($storage->exists($directoryPath)) {
            $this->renameStorageDirectoryFiles($directoryPath, $storage, $suffix);
        }
    }

    private function getNewFilename($filename, $suffix = null)
    {
        $file = (object) pathinfo($filename);

        if (!$suffix) {
            $suffix = '--' . time();
        }

        return $file->dirname . '/' . $file->filename . $suffix . '.' . $file->extension;
    }

    private function renameStorageDirectoryFiles($directoryPath, $storage = null, $suffix = null, $filesystemDriver = null)
    {
        if (!$storage) {
            $storage = Storage::disk($filesystemDriver);
        }

        // List all the existing files from the directory
        $files = $storage->files($directoryPath);

        if (count($files) < 1 ) return false;

        foreach($files as $file) {
            // Get new filename
            $newFilename = Helpers::getNewFilename($file, $suffix);

            // Renamed the files
            $storage->move($file, $newFilename);
        }
    }
}
  
Also, copy of ref here

No comments:

Post a Comment

Please post any queries and comments here.