PHPackages                             matecat/simple-s3 - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [File &amp; Storage](/categories/file-storage)
4. /
5. matecat/simple-s3

ActiveLibrary[File &amp; Storage](/categories/file-storage)

matecat/simple-s3
=================

Simple S3 Client

v2.0.1(1mo ago)1319.4k↑502.4%4MITPHPPHP &gt;=8.3CI passing

Since May 16Pushed 1mo ago9 watchersCompare

[ Source](https://github.com/matecat/simple-s3)[ Packagist](https://packagist.org/packages/matecat/simple-s3)[ Docs](https://github.com/matecat/simple-s3)[ RSS](/packages/matecat-simple-s3/feed)WikiDiscussions master Synced today

READMEChangelog (3)Dependencies (14)Versions (72)Used By (0)

Simple S3 Client
================

[](#simple-s3-client)

[![Tests](https://github.com/matecat/simple-s3/actions/workflows/tests.yml/badge.svg)](https://github.com/matecat/simple-s3/actions/workflows/tests.yml)![license](https://camo.githubusercontent.com/9226d41b1241084cff0aa9023c6bf4b0b203d0e974faaaf8f1f6ff18d087331c/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f6d6174656361742f73696d706c652d73332e737667)![Packagist](https://camo.githubusercontent.com/b8d5bacb3aa19f10ae0fd4c71b925d34939857e4ded7f11f4b3b231440c41b9d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d6174656361742f73696d706c652d73332e737667)[![Quality Gate Status](https://camo.githubusercontent.com/184ef8295ad3dfc29b1d0eedda11927de15cd88db409443b7a50e9d761878b27/68747470733a2f2f736f6e6172636c6f75642e696f2f6170692f70726f6a6563745f6261646765732f6d6561737572653f70726f6a6563743d6d6174656361745f73696d706c652d7333266d65747269633d616c6572745f737461747573)](https://sonarcloud.io/summary/new_code?id=matecat_simple-s3)[![Coverage](https://camo.githubusercontent.com/a4055a11c1b1047d354c1c7bf060c44c77b027c538e87017639bd18b6885677d/68747470733a2f2f736f6e6172636c6f75642e696f2f6170692f70726f6a6563745f6261646765732f6d6561737572653f70726f6a6563743d6d6174656361745f73696d706c652d7333266d65747269633d636f766572616765)](https://sonarcloud.io/summary/new_code?id=matecat_simple-s3)[![Reliability Rating](https://camo.githubusercontent.com/3e6e67dd57e164a29563d92e8c0140f0b1eb5dee9d003c78a269ab53988455c2/68747470733a2f2f736f6e6172636c6f75642e696f2f6170692f70726f6a6563745f6261646765732f6d6561737572653f70726f6a6563743d6d6174656361745f73696d706c652d7333266d65747269633d72656c696162696c6974795f726174696e67)](https://sonarcloud.io/summary/new_code?id=matecat_simple-s3)[![Maintainability Rating](https://camo.githubusercontent.com/b73a61b805abf4acf5b6f8ec7bf2bf9ac0f847535ca720d72ba8bd590dea67b4/68747470733a2f2f736f6e6172636c6f75642e696f2f6170692f70726f6a6563745f6261646765732f6d6561737572653f70726f6a6563743d6d6174656361745f73696d706c652d7333266d65747269633d7371616c655f726174696e67)](https://sonarcloud.io/summary/new_code?id=matecat_simple-s3)

**Simple S3 Client** is a simple wrapper of the official SDK PHP Client.

Basic Usage
-----------

[](#basic-usage)

To instantiate the Client do the following:

```
use Matecat\SimpleS3\Client;

$s3Client = new Client([
    'version' => 'latest',   // REQUIRED
    'region' => 'us-west-2', // REQUIRED
    'credentials' => [       // OPTIONAL
        'key' => 'YOUR-ACCESS-KEY',
        'secret' => 'YOUR-SECRET-KEY',
        'token' => 'SESSION-TOKEN',
    ]
];
```

Please note that if you don't provide the credentials array, the Client will try to [get values from the following environments variables on your system as the original S3Client](https://docs.aws.amazon.com/en_us/sdk-for-php/v3/developer-guide/guide_credentials_environment.html):

- `AWS_ACCESS_KEY_ID`
- `AWS_SECRET_ACCESS_KEY`
- `AWS_SESSION_TOKEN`

If you instead want to authenticate assuming an IAM Role in another AWS Account do the following:

```
use Matecat\SimpleS3\Client;

$s3Client = new Client([
    'version' => 'latest',
    'region' => 'us-west-2',
    'iam' => [
        'arn' => 'arn:aws:iam::123456789012:role/xaccounts3acces',
        'session' => 's3-access-example',
    ]
];
```

For further config details please refer to the official documentation:

[Configuration for the AWS SDK for PHP Version 3](https://docs.aws.amazon.com/en_us/sdk-for-php/v3/developer-guide/guide_configuration.html#credentials)

Methods
-------

[](#methods)

Here is the list of Client's public methods:

- `clearBucket` - clear a bucket from all files
- `copyFolder` - copy the items from a folder to another one
- `copyItem` - copy an item from a bucket to another one
- `copyInBatch` - copy in batch items from a bucket to another one
- `createBucketIfItDoesNotExist` . create a bucket if it does not exists
- `createFolder` . create an empty folder in a bucket if it does not exists
- `deleteBucket` - delete a bucket
- `deleteBucketPolicy` - delete the bucket policy
- `deleteFolder` - delete a folder
- `deleteItem` - delete an item
- `downloadItem` - download an item
- `enableAcceleration` - enable the acceleration mode for a bucket
- `getBucketLifeCycle` get the bucket lifecycle configuration
- `getBucketPolicy` get the bucket policy
- `getBucketSize` get the size (in Bytes) of files in a bucket
- `getItem` - get all informations for an item
- `getItemsInABucket` get an array of items in a bucket
- `getItemsInAVersionedBucket` get an array of items in a versioned bucket
- `getCurrentItemVersion` - get the latest version of an item
- `getPublicItemLink` - get the public link to download the item
- `hasBucket` - check if a bucket exists
- `hasFolder` - check if a folder exists
- `hasItem` - check if an item exists
- `isBucketVersioned` - check if bucket has versioned enabled
- `openItem` - get the content of an item
- `restoreItem` - try to restore an item from archive
- `setBucketLifecycleConfiguration` - set bucket lifecycle configuration
- `setBucketPolicy` - set the bucket policy
- `setBucketVersioning` - set the bucket versioning
- `transfer` - transfer content from/to buckets
- `uploadItem` - upload an item to a bucket from a file
- `uploadItemFromBody` - upload an item to a bucket from the body content

Naming validation for buckets and objects
-----------------------------------------

[](#naming-validation-for-buckets-and-objects)

Please refer to the official AWS policy:

- [Bucket naming restrictions and limitations](https://docs.aws.amazon.com/en_us/AmazonS3/latest/dev/BucketRestrictions.html)
- [Object safe naming rules](https://docs.aws.amazon.com/en_us/AmazonS3/latest/dev/UsingMetadata.html)

The Client comes with two validators:

- `S3BucketNameValidator`
- `S3ObjectSafeNameValidator`

These two classes throws you an `InvalidS3NameException` if the name provided is not compliant with the AWS rule conventions.

Validators are invoked in Client's `createBucketIfItDoesNotExist`, `uploadFileFromBody` and `uploadFile` methods.

Objects name escaping
---------------------

[](#objects-name-escaping)

Please read carefully the [object safe naming rules](https://docs.aws.amazon.com/en_us/AmazonS3/latest/dev/UsingMetadata.html).

Escaping object names is entirely up to you.

You can use the provided `Matecat\SimpleS3\Components\Encoders\UrlEncoder` class, or inject in Client your own encoder if you prefer, but please note that it MUST implement `Matecat\SimpleS3\Components\Encoders\SafeNameEncoderInterface`interface:

```
...

use Matecat\SimpleS3\Components\Encoders\UrlEncoder;

$encoder = new UrlEncoder();
$s3Client->addEncoder($encoder);
```

Filename trimming
-----------------

[](#filename-trimming)

As the [Amazon official documentation](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html) reports, the filename max size on S3 is **1024 characters**.

**But you MUST be aware of filename max size of your operating system.**

For example, if you run the application on a Linux system, this limit is **255 bytes**, so you cannot download a file with a name which exceeds this value.

S3Client comes with a `FilenameTrimmer` helper class, which automatically trims the filenames. Default limit value is 255.

To override this limit, use `setFilenameMaxSize` method:

```
...

$client->setFilenameMaxSize(512);
```

Bucket lifecycle
----------------

[](#bucket-lifecycle)

You can set the basic lifecycle for your bucket with `setBucketLifecycleConfiguration` method.

```
...

$s3Client->setBucketLifecycleConfiguration(['bucket' => $this->bucket, 'rules' => [...]]);
```

For further details please refer to the [bucket lifecycle configuration official API documentation](https://docs.aws.amazon.com/cli/latest/reference/s3api/put-bucket-lifecycle-configuration.html).

Bucket policy
-------------

[](#bucket-policy)

You can set the bucket policy using `setBucketPolicy` method. Consider the following example:

```
...

$s3Client->setBucketPolicy([
    'bucket' => 'mauretto78-bucket-test-policy',
    'policy' => '{
        "Version": "2012-10-17",
        "Id": "Versioning",
        "Statement": [
            {
                "Effect": "Deny",
                "Principal": "*",
                "Action": "s3:GetBucketVersioning",
                "Resource": "arn:aws:s3:::mauretto78-bucket-test-policy"
            }
        ]
    }'
]);
```

You can grab bucket policy and delete it by using respectively `getBucketPolicy` and `deleteBucketPolicy` methods.

For further details please refer to the [bucket policy official API documentation](https://docs.aws.amazon.com/cli/latest/reference/s3api/put-bucket-policy.html).

Bucket versioning
-----------------

[](#bucket-versioning)

You can enable bucket versioning:

```
...

$s3Client->setBucketVersioning(['bucket' => $this->bucket]);
```

And now, when you use `getItemsInABucket` method, a &lt;VERSION\_ID&gt; tag will be added to keys:

```
...

// getItemsInABucket() will return something like this:
$notHydrated = [
    'key',
    'key',
    'key',
];

$hydrated = [
    'key' => 'content',
    'key' => 'content',
    'key' => 'content',
];
```

For further details please refer to the [bucket versioning official API documentation](https://docs.aws.amazon.com/en_us/AmazonS3/latest/API/RESTBucketPUTVersioningStatus.html).

Restoring an item
-----------------

[](#restoring-an-item)

You can use `restoreItem` to send a restore an archived object. You can choose between three retrieval options:

- `Bulk` (lasts 5-12 hours)
- `Expedited` (default, lasts 1-5 minutes)
- `Standard` (lasts 3-5 hours)

For further details please refer to the official documentation:

[Restore an archived object](https://docs.aws.amazon.com/cli/latest/reference/s3api/restore-object.html)

Caching
-------

[](#caching)

In order speed up data retrieval, you can inject a cache handler. Please note that the cache MUST implement `Matecat\SimpleS3\Components\Cache\CacheInterface`. The client comes with a Redis implementation:

```
...

use Matecat\SimpleS3\Components\Cache\RedisCache;

$redis = new Predis\Client();
$cacheAdapter = new RedisCache($redis);
$s3Client->addCache($cacheAdapter);
```

Now `getItemsInABucket` method will get the elements directly from cache. Please note that caching works ONLY if you provide a prefix to the method:

```
...

// this will get keys from cache
$s3Client->getItemsInABucket([
    'bucket' => 'your-bucket',
    'prefix' => 'prefix/',
    'hydrate' => true // false by default. If true is set the method returns an array of Aws\ResultInterface
]);

// this will EVER get keys from S3
$s3Client->getItemsInABucket('your-bucket');
```

If you need to skip the cache you can add an extra parameter called `exclude-cache`:

```
...

// this will get keys from S3
$s3Client->getItemsInABucket([
    'bucket' => 'your-bucket',
    'prefix' => 'prefix/',
    'exclude-cache' => true
]);
```

Commands
--------

[](#commands)

If you have an application which uses [Symfony Console](https://github.com/symfony/console), you have some commands available:

- `ss3:batch:transfer` Transfer files from/to a bucket.
- `ss3:bucket:clear` Clears a bucket.
- `ss3:bucket:create` Creates a bucket.
- `ss3:bucket:delete` Deletes a bucket.
- `ss3:cache:flush` Flush all data stored in cache.
- `ss3:cache:stats` Get the cache statistics.
- `ss3:folder:copy` Copy the items from a folder to another one.
- `ss3:item:copy` Copy an object from a bucket to another one.
- `ss3:item:delete` Deletes an object from a bucket.
- `ss3:item:download` Download an object from a bucket.
- `ss3:item:upload` Upload an object into a bucket.

You can register the commands in your app, consider this example:

```
#!/usr/bin/env php
