Manipulate a S3 bucket

4.1.4 2024-11-11 16:45 UTC

This package is auto-updated.

Last update: 2024-12-11 16:59:35 UTC


README

codecov Build Status Type Coverage

Minimalist abstraction to work with any S3 bucket.

Installation

composer require innmind/s3

Usage

use Innmind\S3\{
    Factory,
    Region,
};
use Innmind\OperatingSystem\Factory as OSFactory;
use Innmind\Filesystem\File\Content;
use Innmind\Url\{
    Url,
    Path,
};

$os = OSFactory::build();

$bucket = Factory::of($os)->build(
    Url::of('https://acces_key:acces_secret@bucket-name.s3.region-name.scw.cloud/'),
    Region::of('region-name'),
);

$file = $bucket->get(Path::of('some-file.txt'))->match(
    static fn(Content $file) => $file,
    static fn() => throw new \RuntimeException('File does not exist'),
);
$bucket->upload(Path::of('some-other-name.txt'), $file)->match( // essentially this will copy the file
    static fn() => null, // everything ok
    static fn() => throw new \RuntimeException('Failed to upload file'),
);

To simplify some usage you can use the filesystem adapter on top of the bucket interface. Here's an example to upload a directory to a bucket:

use Innmind\S3\Filesystem;
use Innmind\Filesystem\Name;

$data = $os->filsystem()->mount(Path::of('/var/data'));
$s3 = Filesystem\Adapter::of($bucket);
$data
    ->get(Name::of('images'))
    ->match(
        $s3->add(...),
        static fn() => null, // do something if there is no images
    );

Warning

A bucket can contain a file and a directory with the same name. This is not supported by innmind/filesystem adapters. This means that if you use Innmind\S3\Filesystem\Adapter on a bucket where there is a file and a directory with the same name it will result in unexpected behaviour or an exception.