Completed
Pull Request — master (#61)
by Saurabh
12:42
created

SetCORSHeaders::handle()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 20

Duplication

Lines 20
Ratio 100 %

Importance

Changes 0
Metric Value
dl 20
loc 20
rs 9.2888
c 0
b 0
f 0
cc 5
nc 8
nop 0
1
<?php
2
3
namespace Sausin\LaravelOvh\Commands;
4
5
use Exception;
6
use Illuminate\Console\Command;
7
use Illuminate\Support\Facades\Storage;
8
use InvalidArgumentException;
9
use League\Flysystem\Cached\CachedAdapter;
10
use OpenStack\ObjectStore\v1\Models\Container;
11
12
class SetCORSHeaders extends Command
13
{
14
    /**
15
     * The name and signature of the console command.
16
     *
17
     * @var string
18
     */
19
    protected $signature = 'ovh:set-cors-headers
20
                            {--disk=ovh : The disk using your OVH container}
21
                            {--origins=* : The origins to be allowed on the containers (multiple allowed)}
22
                            {--max-age=3600 : The maximum cache validity of pre-flight requests}
23
                            {--force : Forcibly set the new keys}';
24
25
    /**
26
     * The console command description.
27
     *
28
     * @var string
29
     */
30
    protected $description = 'Set CORS headers on the container to make Form POST signaure work flawlessly';
31
32
    /**
33
     * The Object Storage Container.
34
     *
35
     * @var Container
36
     */
37
    protected $container;
38
39
    /** array */
40
    protected $tempUrlKeyMeta = [];
41
42
    /**
43
     * Execute the console command.
44
     *
45
     * If the '--force' flag is provided, the specified keys will be set on the container.
46
     * This excludes any 'Temp-Url-Key' already present on the container.
47
     *
48
     * @return void
49
     */
50 View Code Duplication
    public function handle(): void
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
51
    {
52
        try {
53
            $adapter = Storage::disk($this->option('disk'))->getAdapter();
0 ignored issues
show
Bug introduced by
The method getAdapter() does not seem to exist on object<Illuminate\Contra...\Filesystem\Filesystem>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
54
55
            if ($adapter instanceof CachedAdapter) {
56
                $adapter = $adapter->getAdapter();
57
            }
58
59
            $this->container = $adapter->getContainer();
60
        } catch (InvalidArgumentException $e) {
61
            $this->error($e->getMessage());
62
63
            return;
64
        }
65
66
        if ($this->hasOption('force') || $this->askIfShouldOverrideExistingParams()) {
67
            $this->setHeaders();
68
        }
69
    }
70
71
    /**
72
     * If there's no existing Temp URL Key present in the Container, continue.
73
     *
74
     * Otherwise, if there's already an existing Temp URL Key present in the
75
     * Container, the User will be prompted to choose if we should override it
76
     * or not.
77
     *
78
     * @return bool
79
     */
80
    protected function askIfShouldOverrideExistingParams(): bool
81
    {
82
        $metaKeys = ['Access-Control-Allow-Origin', 'Access-Control-Max-Age'];
83
        $containerMeta = $this->container->getMetadata();
84
85
        if (array_key_exists('Temp-Url-Key', $containerMeta)) {
86
            $this->tempUrlKeyMeta = ['Temp-Url-Key' => $containerMeta['Temp-Url-Key']];
87
        }
88
89
        if (count(array_intersect($metaKeys, array_keys($containerMeta))) === 0) {
90
            return true;
91
        }
92
93
        return $this->confirm(
94
            'Some CORS Meta keys are already set on the container. Do you want to override them?',
95
            false
96
        );
97
    }
98
99
    /**
100
     * Updates the Temp URL Key for the Container.
101
     *
102
     * @return void
103
     */
104
    protected function setHeaders(): void
105
    {
106
        $origins = implode(' ', $this->hasOption('origins') ? $this->option('origins') : ['*']);
107
        $maxAge = $this->option('max-age');
108
        $meta = ['Access-Control-Allow-Origin' => $origins, 'Access-Control-Max-Age' => $maxAge];
109
110
        if ($this->tempUrlKeyMeta) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->tempUrlKeyMeta of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
111
            $meta += $this->tempUrlKeyMeta;
112
        }
113
114
        try {
115
            $this->container->resetMetadata($meta);
116
117
            $this->info('CORS meta keys successfully set on the container');
118
        } catch (Exception $e) {
119
            $this->error($e->getMessage());
120
        }
121
    }
122
}
123