Completed
Pull Request — master (#43)
by
unknown
06:02
created

AwsS3Provider::getUrl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Publiux\laravelcdn\Providers;
4
5
use Aws\S3\BatchDelete;
6
use Aws\S3\Exception\S3Exception;
7
use Aws\S3\S3Client;
8
use Illuminate\Support\Collection;
9
use Publiux\laravelcdn\Contracts\CdnHelperInterface;
10
use Publiux\laravelcdn\Contracts\FileUploadHandlerInterface;
11
use Publiux\laravelcdn\Providers\Contracts\ProviderInterface;
12
use Publiux\laravelcdn\Validators\Contracts\ProviderValidatorInterface;
13
use Symfony\Component\Console\Output\ConsoleOutput;
14
15
/**
16
 * Class AwsS3Provider
17
 * Amazon (AWS) S3.
18
 *
19
 *
20
 * @category Driver
21
 *
22
 * @property string  $provider_url
23
 * @property string  $threshold
24
 * @property string  $version
25
 * @property string  $region
26
 * @property string  $credential_key
27
 * @property string  $credential_secret
28
 * @property string  $buckets
29
 * @property string  $acl
30
 * @property string  $cloudfront
31
 * @property string  $cloudfront_url
32
 * @property string $http
33
 *
34
 * @author   Mahmoud Zalt <[email protected]>
35
 */
36
class AwsS3Provider extends Provider implements ProviderInterface
37
{
38
    /**
39
     * All the configurations needed by this class with the
40
     * optional configurations default values.
41
     *
42
     * @var array
43
     */
44
    protected $default = [
45
        'url' => null,
46
        'threshold' => 10,
47
        'providers' => [
48
            'aws' => [
49
                's3' => [
50
                    'version' => null,
51
                    'region' => null,
52
                    'endpoint' => null,
53
                    'buckets' => null,
54
                    'upload_folder' => '',
55
                    'http' => null,
56
                    'acl' => 'public-read',
57
                    'cloudfront' => [
58
                        'use' => false,
59
                        'cdn_url' => null,
60
                    ],
61
                ],
62
            ],
63
        ],
64
    ];
65
66
    /**
67
     * Required configurations (must exist in the config file).
68
     *
69
     * @var array
70
     */
71
    protected $rules = ['version', 'region', 'key', 'secret', 'buckets', 'url'];
72
73
    /**
74
     * this array holds the parsed configuration to be used across the class.
75
     *
76
     * @var Array
77
     */
78
    protected $supplier;
79
80
    /**
81
     * @var Instance of Aws\S3\S3Client
82
     */
83
    protected $s3_client;
84
85
    /**
86
     * @var Instance of Guzzle\Batch\BatchBuilder
87
     */
88
    protected $batch;
89
90
    /**
91
     * @var \Publiux\laravelcdn\Contracts\CdnHelperInterface
92
     */
93
    protected $cdn_helper;
94
95
    /**
96
     * @var \Publiux\laravelcdn\Validators\Contracts\ConfigurationsInterface
97
     */
98
    protected $configurations;
99
100
    /**
101
     * @var \Publiux\laravelcdn\Validators\Contracts\ProviderValidatorInterface
102
     */
103
    protected $provider_validator;
104
105
    /**
106
     * @param \Symfony\Component\Console\Output\ConsoleOutput $console
107
     * @param \Publiux\laravelcdn\Validators\Contracts\ProviderValidatorInterface $provider_validator
108
     * @param \Publiux\laravelcdn\Contracts\CdnHelperInterface                    $cdn_helper
109
     */
110
    public function __construct(
111
        ConsoleOutput $console,
112
        ProviderValidatorInterface $provider_validator,
113
        CdnHelperInterface $cdn_helper
114
    ) {
115
        $this->console = $console;
0 ignored issues
show
Documentation Bug introduced by
It seems like $console of type object<Symfony\Component...e\Output\ConsoleOutput> is incompatible with the declared type object<Publiux\laravelcdn\Providers\Instance> of property $console.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
116
        $this->provider_validator = $provider_validator;
117
        $this->cdn_helper = $cdn_helper;
118
    }
119
120
    /**
121
     * Read the configuration and prepare an array with the relevant configurations
122
     * for the (AWS S3) provider. and return itself.
123
     *
124
     * @param $configurations
125
     *
126
     * @return $this
127
     */
128
    public function init($configurations)
129
    {
130
        // merge the received config array with the default configurations array to
131
        // fill missed keys with null or default values.
132
        $this->default = array_replace_recursive($this->default, $configurations);
133
134
        $supplier = [
135
            'provider_url' => $this->default['url'],
136
            'threshold' => $this->default['threshold'],
137
            'version' => $this->default['providers']['aws']['s3']['version'],
138
            'region' => $this->default['providers']['aws']['s3']['region'],
139
            'endpoint' => $this->default['providers']['aws']['s3']['endpoint'],
140
            'buckets' => $this->default['providers']['aws']['s3']['buckets'],
141
            'acl' => $this->default['providers']['aws']['s3']['acl'],
142
            'cloudfront' => $this->default['providers']['aws']['s3']['cloudfront']['use'],
143
            'cloudfront_url' => $this->default['providers']['aws']['s3']['cloudfront']['cdn_url'],
144
            'http' => $this->default['providers']['aws']['s3']['http'],
145
            'upload_folder' => $this->default['providers']['aws']['s3']['upload_folder']
146
        ];
147
148
        // check if any required configuration is missed
149
        $this->provider_validator->validate($supplier, $this->rules);
150
151
        $this->supplier = $supplier;
152
153
        return $this;
154
    }
155
156
    /**
157
     * Upload assets.
158
     *
159
     * @param $assets
160
     *
161
     * @return bool
162
     */
163
    public function upload($assets)
164
    {
165
        // connect before uploading
166
        $connected = $this->connect();
167
168
        if (!$connected) {
169
            return false;
170
        }
171
172
        // user terminal message
173
        $this->console->writeln('<fg=yellow>Comparing local files and bucket...</fg=yellow>');
174
175
        $assets = $this->getFilesAlreadyOnBucket($assets);
176
177
        // upload each asset file to the CDN
178
        if (count($assets) > 0) {
179
            $this->console->writeln('<fg=yellow>Upload in progress......</fg=yellow>');
180
            foreach ($assets as $file) {
181
                try {
182
                    $this->console->writeln('<fg=cyan>'.'Uploading file path: '.$file->getRealpath().'</fg=cyan>');
183
                    $command = $this->s3_client->getCommand('putObject', [
184
185
                        // the bucket name
186
                        'Bucket' => $this->getBucket(),
187
                        // the path of the file on the server (CDN)
188
                        'Key' => $this->getUploadFolderForFile($file),
189
                        // the path of the path locally
190
                        'Body' => fopen($file->getRealPath(), 'r'),
191
                        // the permission of the file
192
193
                        'ACL' => $this->acl,
194
                        'CacheControl' => $this->default['providers']['aws']['s3']['cache-control'],
195
                        'Metadata' => $this->default['providers']['aws']['s3']['metadata'],
196
                        'Expires' => $this->default['providers']['aws']['s3']['expires'],
197
                    ]);
198
//                var_dump(get_class($command));exit();
199
200
201
                    $this->s3_client->execute($command);
202
                } catch (S3Exception $e) {
203
                    $this->console->writeln('<fg=red>Upload error: '.$e->getMessage().'</fg=red>');
204
                    return false;
205
                }
206
            }
207
208
            // user terminal message
209
            $this->console->writeln('<fg=green>Upload completed successfully.</fg=green>');
210
        } else {
211
            // user terminal message
212
            $this->console->writeln('<fg=yellow>No new files to upload.</fg=yellow>');
213
        }
214
215
        return true;
216
    }
217
218
    private function getUploadFolderForFile($file){
219
        $uploadFolder = $this->supplier['upload_folder'];
220
        $class = str_replace("/", "", $uploadFolder);
221
222
        if(class_exists($class)){
223
            $instance = new $class;
224
            if($instance instanceof FileUploadHandlerInterface){
225
                $uploadFolder = $instance->getUploadPathForFile($file);
226
            } else {
227
                throw new \Exception("Class \"{$class}\" does not implement " . FileuploadHandlerInterface::class);
228
            }
229
        }
230
231
        return $uploadFolder . str_replace('\\', '/', $file->getPathName());
232
    }
233
234
    /**
235
     * Create an S3 client instance
236
     * (Note: it will read the credentials form the .env file).
237
     *
238
     * @return bool
239
     */
240
    public function connect()
241
    {
242
        try {
243
            // Instantiate an S3 client
244
            $this->setS3Client(new S3Client([
245
                        'version' => $this->supplier['version'],
246
                        'region' => $this->supplier['region'],
247
                        'endpoint' => $this->supplier['endpoint'],
248
                        'http' => $this->supplier['http']
249
                    ]
250
                )
251
            );
252
        } catch (\Exception $e) {
253
            $this->console->writeln('<fg=red>Connection error: '.$e->getMessage().'</fg=red>');
254
            return false;
255
        }
256
257
        return true;
258
    }
259
260
    /**
261
     * @param $s3_client
262
     */
263
    public function setS3Client($s3_client)
264
    {
265
        $this->s3_client = $s3_client;
266
    }
267
268
    /**
269
     * @param $assets
270
     * @return mixed
271
     */
272
    private function getFilesAlreadyOnBucket($assets)
273
    {
274
        $filesOnAWS = new Collection([]);
275
276
        $files = $this->s3_client->listObjects([
277
            'Bucket' => $this->getBucket(),
278
        ]);
279
280
        if (!$files['Contents']) {
281
            //no files on bucket. lets upload everything found.
282
            return $assets;
283
        }
284
285
        foreach ($files['Contents'] as $file) {
286
            $a = [
287
                'Key' => $file['Key'],
288
                "LastModified" => $file['LastModified']->getTimestamp(),
289
                'Size' => $file['Size']
290
            ];
291
            $filesOnAWS->put($file['Key'], $a);
292
        }
293
294
        $assets->transform(function ($item, $key) use (&$filesOnAWS) {
0 ignored issues
show
Unused Code introduced by
The parameter $key is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
295
            $fileOnAWS = $filesOnAWS->get(str_replace('\\', '/', $item->getPathName()));
296
297
            //select to upload files that are different in size AND last modified time.
298
            if (!($item->getMTime() === $fileOnAWS['LastModified']) && !($item->getSize() === $fileOnAWS['Size'])) {
299
                return $item;
300
            }
301
        });
302
303
        $assets = $assets->reject(function ($item) {
304
            return $item === null;
305
        });
306
307
        return $assets;
308
    }
309
310
    /**
311
     * @return array
312
     */
313
    public function getBucket()
314
    {
315
        // this step is very important, "always assign returned array from
316
        // magical function to a local variable if you need to modify it's
317
        // state or apply any php function on it." because the returned is
318
        // a copy of the original variable. this prevent this error:
319
        // Indirect modification of overloaded property
320
        // Vinelab\Cdn\Providers\AwsS3Provider::$buckets has no effect
321
        $bucket = $this->buckets;
322
323
        return rtrim(key($bucket), '/');
324
    }
325
326
    /**
327
     * Empty bucket.
328
     *
329
     * @return bool
330
     */
331
    public function emptyBucket()
332
    {
333
334
        // connect before uploading
335
        $connected = $this->connect();
336
337
        if (!$connected) {
338
            return false;
339
        }
340
341
        // user terminal message
342
        $this->console->writeln('<fg=yellow>Emptying in progress...</fg=yellow>');
343
344
        try {
345
346
            // Get the contents of the bucket for information purposes
347
            $contents = $this->s3_client->listObjects([
348
                'Bucket' => $this->getBucket(),
349
                'Key' => '',
350
            ]);
351
352
            // Check if the bucket is already empty
353
            if (!$contents['Contents']) {
354
                $this->console->writeln('<fg=green>The bucket '.$this->getBucket().' is already empty.</fg=green>');
355
356
                return true;
357
            }
358
359
            // Empty out the bucket
360
            $empty = BatchDelete::fromListObjects($this->s3_client, [
361
                'Bucket' => $this->getBucket(),
362
                'Prefix' => null,
363
            ]);
364
365
            $empty->delete();
366
        } catch (S3Exception $e) {
367
            $this->console->writeln('<fg=red>Deletion error: '.$e->getMessage().'</fg=red>');
368
            return false;
369
        }
370
371
        $this->console->writeln('<fg=green>The bucket '.$this->getBucket().' is now empty.</fg=green>');
372
373
        return true;
374
    }
375
376
    /**
377
     * This function will be called from the CdnFacade class when
378
     * someone use this {{ Cdn::asset('') }} facade helper.
379
     *
380
     * @param $path
381
     *
382
     * @return string
383
     */
384
    public function urlGenerator($path)
385
    {
386
        if ($this->getCloudFront() === true) {
387
            $url = $this->cdn_helper->parseUrl($this->getCloudFrontUrl());
388
389
            return $url['scheme'] . '://' . $url['host'] . '/' . $path;
390
        }
391
392
        $url = $this->cdn_helper->parseUrl($this->getUrl());
393
394
        $bucket = $this->getBucket();
395
        $bucket = (!empty($bucket)) ? $bucket.'.' : '';
396
397
        return $url['scheme'] . '://' . $bucket . $url['host'] . '/' . $path;
398
    }
399
400
    /**
401
     * @return string
402
     */
403
    public function getCloudFront()
404
    {
405
        if (!is_bool($cloudfront = $this->cloudfront)) {
406
            return false;
407
        }
408
409
        return $cloudfront;
410
    }
411
412
    /**
413
     * @return string
414
     */
415
    public function getCloudFrontUrl()
416
    {
417
        return rtrim($this->cloudfront_url, '/').'/';
418
    }
419
420
    /**
421
     * @return string
422
     */
423
    public function getUrl()
424
    {
425
        return rtrim($this->provider_url, '/') . '/';
426
    }
427
428
    /**
429
     * @param $attr
430
     *
431
     * @return Mix | null
432
     */
433
    public function __get($attr)
434
    {
435
        return isset($this->supplier[$attr]) ? $this->supplier[$attr] : null;
436
    }
437
}
438