Skip to content

Commit

Permalink
Merge pull request #2 from konnco/feature/path-variable-support
Browse files Browse the repository at this point in the history
Feature/path variable support
  • Loading branch information
frankyso authored Oct 29, 2021
2 parents 8d37901 + c54778e commit 60e8669
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 3 deletions.
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,13 @@ protected $casts = [
'banner' => Image::class.":80,images/account/avatar,png",
];
```
with parameters `:quality,savePath,extension`.
with parameters `:quality,savePath,extension`. For the `savePath` variable you may want to insert random variable like date as the folder name, you can follow the example

```php
protected $casts = [
'avatar' => Image::class.":80,images/account/{date:Y-m-d}/avatar,jpg",
];
```

After defining all of those configuration you can start uploading the image, example :

Expand Down
21 changes: 20 additions & 1 deletion src/Casts/Image.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ class Image implements CastsAttributes
public function __construct($quality = 80, $path = null, $extension = null)
{
$this->quality = $quality;
$this->path = $path ?? config('imagecast.path');
$this->path = $this->_prepareSavePath($path) ?? config('imagecast.path');
$this->extension = $extension;
$this->disk = config('imagecast.disk');
$this->storage = Storage::disk($this->disk);
Expand Down Expand Up @@ -308,4 +308,23 @@ protected function _prepareSaveData($value)
'path' => $path,
];
}

protected function _prepareSavePath($path)
{
$match = [];
preg_match_all('#\{(.*?)\}#', $path, $match);

foreach ($match[1] as $key => $string) {
$startWithDate = Str::of($string)->startsWith('date:');
if (! $startWithDate) {
continue;
}

$dateFormat = explode(":", $string)[1];
$date = date($dateFormat);
$path = str_replace($match[0][$key], $date, $path);
}

return $path;
}
}
2 changes: 1 addition & 1 deletion tests/src/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@ class User extends Model
* @var array
*/
protected $casts = [
'avatar' => Image::class.":80,images/account/avatar",
'avatar' => Image::class.":80,images/account/avatar/{date:Y}/{date:m}",
];
}

0 comments on commit 60e8669

Please sign in to comment.