Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions examples/async-upload/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# Async Upload Example

This example demonstrates how to upload multiple files concurrently using async/await with Guzzle promises.

## Prerequisites

- PHP 8.1 or higher
- Composer
- A Bunny Storage zone with API credentials

## Setup

1. Install dependencies:

```bash
composer install
```

2. Set the required environment variables:

```bash
export BUNNY_STORAGE_API_KEY="your-storage-api-key"
export BUNNY_STORAGE_ZONE="your-storage-zone-name"
export BUNNY_STORAGE_REGION="de" # Optional, defaults to "de" (Falkenstein)
```

3. Create a local `files` directory with files to upload:

```bash
mkdir files
# Add some files to upload
```

## Running the Example

Run directly with PHP:

```bash
BUNNY_STORAGE_API_KEY="your-key" BUNNY_STORAGE_ZONE="your-zone" php index.php
```

Or start a local server:

```bash
BUNNY_STORAGE_API_KEY="your-key" BUNNY_STORAGE_ZONE="your-zone" composer start
```

Then visit http://localhost:8000 in your browser.

## What This Example Does

1. Scans the local `files/` directory for files
2. Creates async upload promises for each file
3. Executes all uploads concurrently
4. Reports progress and results for each file
5. Compares execution time with sequential uploads

## Benefits of Async Uploads

- **Faster**: Multiple files upload simultaneously instead of one at a time
- **Efficient**: Better utilization of network bandwidth
- **Scalable**: Handle large numbers of files more effectively
18 changes: 18 additions & 0 deletions examples/async-upload/composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"name": "bunnycdn/storage-example-async-upload",
"description": "Async upload example for Bunny Storage SDK",
"type": "project",
"require": {
"php": ">=8.1",
"bunnycdn/storage": "*"
},
"repositories": [
{
"type": "path",
"url": "../../"
}
],
"scripts": {
"start": "php -S localhost:8000 index.php"
}
}
142 changes: 142 additions & 0 deletions examples/async-upload/index.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
<?php

require_once __DIR__.'/../../vendor/autoload.php';

use Bunny\Storage\Client;
use Bunny\Storage\Region;
use GuzzleHttp\Promise\Utils;

$apiKey = getenv('BUNNY_STORAGE_API_KEY');
$storageZone = getenv('BUNNY_STORAGE_ZONE');
$region = getenv('BUNNY_STORAGE_REGION') ?: 'de';

if (!$apiKey || !$storageZone) {
header('Content-Type: application/json');
echo json_encode(
[
'error' => 'BUNNY_STORAGE_API_KEY and BUNNY_STORAGE_ZONE environment variables are required.',
],
JSON_PRETTY_PRINT,
);
exit(1);
}

$regionMap = [
'de' => Region::FALKENSTEIN,
'uk' => Region::LONDON,
'se' => Region::STOCKHOLM,
'ny' => Region::NEW_YORK,
'la' => Region::LOS_ANGELES,
'sg' => Region::SINGAPORE,
'syd' => Region::SYDNEY,
'br' => Region::SAO_PAULO,
'jh' => Region::JOHANNESBURG,
];

$regionConstant = $regionMap[$region] ?? Region::FALKENSTEIN;

$localDirectory = __DIR__.'/files';

if (!is_dir($localDirectory)) {
mkdir($localDirectory, 0755, true);

for ($i = 1; $i <= 5; ++$i) {
$content = str_repeat("This is sample file {$i}. ", 100 * $i);
file_put_contents("{$localDirectory}/async-sample{$i}.txt", $content);
}
}

try {
$client = new Client($apiKey, $storageZone, $regionConstant);

$files = glob("{$localDirectory}/*");
$files = array_filter($files, 'is_file');

if (empty($files)) {
header('Content-Type: application/json');
echo json_encode(
[
'error' => "No files found in '{$localDirectory}'. Add some files to the 'files/' directory and run again.",
],
JSON_PRETTY_PRINT,
);
exit(0);
}

$uploadMap = [];
foreach ($files as $file) {
$fileName = basename($file);
$remotePath = "async/{$fileName}";
$uploadMap[$file] = $remotePath;
}

$asyncStart = microtime(true);

$promises = [];
foreach ($uploadMap as $localPath => $remotePath) {
$promises[$remotePath] = $client->uploadAsync($localPath, $remotePath);
}

$promiseResults = Utils::settle($promises)->wait();

$asyncEnd = microtime(true);
$asyncDuration = round($asyncEnd - $asyncStart, 3);

$results = [];
$successful = 0;
$failed = 0;

foreach ($promiseResults as $remotePath => $result) {
$fileName = basename($remotePath);
$localPath = array_search($remotePath, $uploadMap);

if ('fulfilled' === $result['state']) {
$results[] = [
'file' => $fileName,
'size' => filesize($localPath),
'status' => 'success',
];
++$successful;
} else {
$results[] = [
'file' => $fileName,
'size' => filesize($localPath),
'status' => 'failed',
'error' => $result['reason']->getMessage(),
];
++$failed;
}
}

$uploadedFiles = $client->listFiles('async/');
$uploadedList = array_map(
fn ($file) => [
'name' => $file->getName(),
'size' => $file->getSize(),
'isDirectory' => $file->isDirectory(),
'dateModified' => $file->getDateModified()->format('c'),
],
array_filter($uploadedFiles, fn ($file) => !$file->isDirectory()),
);

header('Content-Type: application/json');
echo json_encode(
[
'storageZone' => $storageZone,
'region' => $region,
'summary' => [
'successful' => $successful,
'failed' => $failed,
'total' => count($files),
'durationSeconds' => $asyncDuration,
],
'results' => $results,
'uploadedFiles' => array_values($uploadedList),
],
JSON_PRETTY_PRINT,
);
} catch (Exception $e) {
header('Content-Type: application/json');
echo json_encode(['error' => $e->getMessage()], JSON_PRETTY_PRINT);
exit(1);
}
57 changes: 57 additions & 0 deletions examples/batch-upload/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Batch Upload Example

This example demonstrates how to upload multiple files from a local directory to Bunny Storage.

## Prerequisites

- PHP 8.1 or higher
- Composer
- A Bunny Storage zone with API credentials

## Setup

1. Install dependencies:

```bash
composer install
```

2. Set the required environment variables:

```bash
export BUNNY_STORAGE_API_KEY="your-storage-api-key"
export BUNNY_STORAGE_ZONE="your-storage-zone-name"
export BUNNY_STORAGE_REGION="de" # Optional, defaults to "de" (Falkenstein)
```

3. Create a local `files` directory with files to upload:

```bash
mkdir files
echo "File 1 content" > files/file1.txt
echo "File 2 content" > files/file2.txt
echo "File 3 content" > files/file3.txt
```

## Running the Example

Run directly with PHP:

```bash
BUNNY_STORAGE_API_KEY="your-key" BUNNY_STORAGE_ZONE="your-zone" php index.php
```

Or start a local server:

```bash
BUNNY_STORAGE_API_KEY="your-key" BUNNY_STORAGE_ZONE="your-zone" composer start
```

Then visit http://localhost:8000 in your browser.

## What This Example Does

1. Scans the local `files/` directory for files
2. Uploads each file to Bunny Storage in a `batch/` directory
3. Reports progress and results for each file
4. Shows a summary of successful and failed uploads
18 changes: 18 additions & 0 deletions examples/batch-upload/composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"name": "bunnycdn/storage-example-batch-upload",
"description": "Batch upload example for Bunny Storage SDK",
"type": "project",
"require": {
"php": ">=8.1",
"bunnycdn/storage": "*"
},
"repositories": [
{
"type": "path",
"url": "../../"
}
],
"scripts": {
"start": "php -S localhost:8000 index.php"
}
}
Loading