From 0cfb3953027faace2f736ab069c09cd1c542a72a Mon Sep 17 00:00:00 2001 From: muruganstr Date: Wed, 16 Nov 2016 19:08:19 +0530 Subject: [PATCH] Add support to upload directly to s3 --- README.md | 13 ++++++-- src/Services/TinifyService.php | 55 +++++++++++++++++++++++++++++++++- 2 files changed, 65 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index f12fe26..9cc894c 100644 --- a/README.md +++ b/README.md @@ -15,11 +15,20 @@ under "providers": ```php yasmuru\LaravelTinify\LaravelTinifyServiceProvider::class, ``` -uder "aliases": +under "aliases": ```php 'Tinify' => yasmuru\LaravelTinify\Facades\Tinify::class ``` -And set a env variable `TINIFY_APIKEY` \ No newline at end of file +And set a env variable `TINIFY_APIKEY` with your tinypng api key. + +If you want to directly upload the image to `aws s3`, you need set the env variables of following with your aws s3 credentials. + +```php + S3_KEY= + S3_SECRET= + S3_REGION= + S3_BUCKET= +``` diff --git a/src/Services/TinifyService.php b/src/Services/TinifyService.php index 506c1eb..1158957 100644 --- a/src/Services/TinifyService.php +++ b/src/Services/TinifyService.php @@ -1,9 +1,11 @@ client = new Tinify(); $this->client->setKey($this->apikey); + + $this->s3_key = env('S3_KEY'); + $this->s3_secret = env('S3_SECRET'); + $this->s3_region = env('S3_REGION'); } public function setKey($key) { return $this->client->setKey($key); @@ -46,6 +52,53 @@ public function fromUrl($string) { return Source::fromUrl($string); } + function isS3Set() { + if($this->s3_key && $this->s3_secret && $this->s3_region ) { + return true; + } + + throw new \InvalidArgumentException('Please set S3 environment variables.'); + } + + public function fileToS3($source_path, $bucket, $destination_path) { + if($this->isS3Set()) { + return Source::fromFile($source_path) + ->store(array( + "service" => "s3", + "aws_access_key_id" => $this->s3_key, + "aws_secret_access_key" => $this->s3_secret, + "region" => $this->s3_region, + "path" => $bucket . $destination_path, + )); + } + } + + public function bufferToS3($string, $bucket, $path) { + if($this->isS3Set()) { + return Source::fromBuffer($string) + ->store(array( + "service" => "s3", + "aws_access_key_id" => $this->s3_key, + "aws_secret_access_key" => $this->s3_secret, + "region" => $this->s3_region, + "path" => $bucket . $path, + )); + } + } + + public function urlToS3($url, $bucket, $path) { + if($this->isS3Set()) { + return Source::fromUrl($url) + ->store(array( + "service" => "s3", + "aws_access_key_id" => $this->s3_key, + "aws_secret_access_key" => $this->s3_secret, + "region" => $this->s3_region, + "path" => $bucket . $path, + )); + } + } + public function validate() { try { $this->client->getClient()->request("post", "/shrink");