Skip to content

Commit 733ee8f

Browse files
committed
Add Docs ModelTrait + Update ModelTrait
1 parent 8564cc0 commit 733ee8f

File tree

2 files changed

+166
-6
lines changed

2 files changed

+166
-6
lines changed

README.md

Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,14 @@ Amazon S3 or Amazon Simple Storage Service component for Yii2.
2323
- [Basic Usage](#basic-usage)
2424
- [Advanced Usage](#advanced-usage)
2525
- [Custom Commands](#custom-commands)
26+
- [Using Traits](#using-traits)
27+
- [Model Trait](#model-trait)
28+
- [Using Trait Methods](#using-trait-methods)
29+
- [Overriding Trait Methods](#overriding-trait-methods)
30+
- [getS3Component](#gets3component)
31+
- [attributePaths](#attributepaths)
32+
- [getPresignedUrlDuration](#getpresignedurlduration)
33+
- [isSuccessResponseStatus](#issuccessresponsestatus)
2634
- [License](#license)
2735

2836
## Instalation
@@ -318,6 +326,155 @@ class MyPlainCommand implements PlainCommand, HasBucket
318326
Any command can extend the `ExecutableCommand` class or implement the `Executable` interface that will
319327
allow to execute this command immediately: `$command->withSomething('some value')->execute();`.
320328

329+
## Using Traits
330+
331+
### Model Trait
332+
333+
Attach the Trait to the Model/ActiveRecord with some media attribute that will be saved in S3:
334+
335+
```php
336+
/**
337+
* @property string|null $file
338+
*/
339+
class Model extends \yii\db\ActiveRecord
340+
{
341+
use \diecoding\aws\s3\traits\ModelTrait;
342+
343+
// ...
344+
345+
public function rules()
346+
{
347+
return [
348+
['image', 'string'], // Stores the filename
349+
];
350+
}
351+
352+
/**
353+
* @inheritdoc
354+
* @see https://github.com/sugeng-sulistiyawan/yii2-aws-s3/blob/main/src/traits/ModelTrait.php#L162
355+
*/
356+
protected function attributePaths()
357+
{
358+
return [
359+
'image' => 'images/'
360+
];
361+
}
362+
363+
// ...
364+
}
365+
```
366+
367+
Override the `attributePaths()` method to change the base path where the files will be saved on AWS S3.
368+
369+
* You can map a different path to each file attribute of your Model/ActiveRecord.
370+
371+
#### Using Trait Methods
372+
373+
```php
374+
$image = \yii\web\UploadedFile::getInstance($model, 'image');
375+
376+
// Save image as image_thumb.png on S3 at //my_bucket/images/ path
377+
// $model->image will hold "image_thumb.png" after this call finish with success
378+
$model->saveUploadedFile($image, 'image', 'image_thumb.png');
379+
380+
// Save image_thumb.* to S3 on //my_bucket/images/ path
381+
// The extension of the file will be determined by the submitted file type
382+
// This allows multiple file types upload (png,jpg,gif,...)
383+
$model->saveUploadedFile($image, 'image', 'image_thumb', true);
384+
385+
// Get the URL to the image on S3
386+
$model->getFileUrl('image');
387+
388+
// Get the presigned URL to the image on S3
389+
// The default duration is "+30 minutes"
390+
$model->getFilePresignedUrl('image');
391+
392+
// Remove the file with named saved on the image attribute
393+
// Continuing the example, here "//my_bucket/images/my_image.png" will be deleted from S3
394+
$model->removeFile('image');
395+
```
396+
397+
#### Overriding Trait Methods
398+
399+
##### getS3Component
400+
401+
The S3MediaTrait depends on this component to be configured. The default configuration is to use this component on index `'s3'`, but you may use another value. For this cases, override the `getS3Component()` method:
402+
403+
```php
404+
public function getS3Component()
405+
{
406+
return Yii::$app->get('my_s3_component');
407+
}
408+
```
409+
410+
##### attributePaths
411+
412+
The main method to override is `attributePaths()`, which defines a path in S3 for each attribute of yout model. Allowing you to save each attribute in a different S3 folder.
413+
414+
Here an example:
415+
416+
```php
417+
protected function attributePaths()
418+
{
419+
return [
420+
'logo' => 'logos/',
421+
'badge' => 'images/badges/'
422+
];
423+
}
424+
425+
// or use another attribute, example: id
426+
// ! Note: id must contain a value first if you don't want it to be empty
427+
428+
protected function attributePaths()
429+
{
430+
return [
431+
'logo' => 'thumbnail/' . $this->id . '/logos/',
432+
'badge' => 'thumbnail/' . $this->id . '/images/badges/'
433+
];
434+
}
435+
```
436+
437+
##### getPresignedUrlDuration
438+
439+
The default pressigned URL duration is set to "+1day", override this method and use your own expiration.
440+
441+
```php
442+
protected function getPresignedUrlDuration($attribute)
443+
{
444+
return '+2 hours';
445+
}
446+
447+
// or if you want to set the attribute differently
448+
449+
protected function getPresignedUrlDuration($attribute)
450+
{
451+
switch ($attribute) {
452+
case 'badge':
453+
return '+2 hours';
454+
break;
455+
456+
default:
457+
return '+1 days';
458+
break;
459+
}
460+
}
461+
462+
```
463+
464+
The value should be a valid PHP datetime operation. Read [PHP documentation](https://www.php.net/manual/en/datetime.formats.php) for details
465+
466+
##### isSuccessResponseStatus
467+
468+
The `isSuccessResponseStatus()` method validate the AWS response for status codes is 2**. If needed, you can override this validation:
469+
470+
```php
471+
protected function isSuccessResponseStatus($response)
472+
{
473+
// Response is always valid
474+
return true;
475+
}
476+
```
477+
321478
## License
322479

323480
Yii2 AWS S3 is licensed under the MIT License.

src/traits/ModelTrait.php

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,11 @@ public function getS3Component()
2727
* @param UploadedFile $file Uploaded file to save
2828
* @param string $attribute Attribute name where the uploaded filename name will be saved
2929
* @param string $fileName Name which file will be saved. If empty will use the name from $file
30-
* @param bool $updateExtension `true` to automatically append the extension to the file name. Default is `true`
30+
* @param bool $autoExtension `true` to automatically append or replace the extension to the file name. Default is `true`
3131
*
3232
* @return string|false Uploaded full path of filename on success or `false` in failure.
3333
*/
34-
public function saveUploadedFile(UploadedFile $file, $attribute, $fileName = '', $updateExtension = true)
34+
public function saveUploadedFile(UploadedFile $file, $attribute, $fileName = '', $autoExtension = true)
3535
{
3636
if ($this->hasError && !$file instanceof UploadedFile) {
3737
return false;
@@ -40,8 +40,9 @@ public function saveUploadedFile(UploadedFile $file, $attribute, $fileName = '',
4040
if (empty($fileName)) {
4141
$fileName = $file->name;
4242
}
43-
if ($updateExtension) {
44-
$fileName .= '.' . $file->extension;
43+
if ($autoExtension) {
44+
$_file = pathinfo($fileName, PATHINFO_FILENAME);
45+
$fileName = $_file . '.' . $file->extension;
4546
}
4647

4748
$filePath = $this->getAttributePath($attribute) . $fileName;
@@ -127,16 +128,18 @@ public function getFilePresignedUrl($attribute)
127128

128129
return $this->getS3Component()->getPresignedUrl(
129130
$this->getAttributePath($attribute) . $this->{$attribute},
130-
$this->getPresignedUrlDuration()
131+
$this->getPresignedUrlDuration($attribute)
131132
);
132133
}
133134

134135
/**
135136
* Retrieves the URL signature expiration.
136137
*
138+
* @param string $attribute Attribute name which holds the duration
139+
*
137140
* @return mixed URL expiration
138141
*/
139-
protected function getPresignedUrlDuration()
142+
protected function getPresignedUrlDuration($attribute)
140143
{
141144
return '+30 minutes';
142145
}

0 commit comments

Comments
 (0)