Completed
Pull Request — master (#14)
by Saurabh
01:06
created

OVHSwiftAdapter::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 3
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Sausin\LaravelOvh;
4
5
use BadMethodCallException;
6
use Carbon\Carbon;
7
use League\Flysystem\Config;
8
use Nimbusoft\Flysystem\OpenStack\SwiftAdapter;
9
use OpenStack\Common\Error\BadResponseError;
10
use OpenStack\ObjectStore\v1\Models\Container;
11
use OpenStack\ObjectStore\v1\Service;
12
13
class OVHSwiftAdapter extends SwiftAdapter
14
{
15
    /**
16
     * URL base path variables for OVH service
17
     * the HTTPS url is typically of the format
18
     * https://storage.[REGION].cloud.ovh.net/v1/AUTH_[PROJECT_ID]/[CONTAINER_NAME].
19
     * @var array
20
     */
21
    protected $urlVars;
22
23
    /**
24
     * Constructor.
25
     *
26
     * @param Container $container
27
     * @param array     $urlVars
28
     * @param string    $prefix
29
     */
30
    public function __construct(Container $container, $urlVars = [], $prefix = null)
31
    {
32
        parent::__construct($container, $prefix);
33
34
        $this->urlVars = $urlVars;
35
    }
36
37
    /**
38
     * Custom function to comply with the Storage::url() function in laravel
39
     * without checking the existence of a file (faster).
40
     *
41
     * @param  string $path
42
     * @return string
43
     */
44
    public function getUrl($path)
45
    {
46
        $this->checkParams();
47
48
        return $this->getEndpoint().$path;
49
    }
50
51
    /**
52
     * Custom function to get a url with confirmed file existence.
53
     *
54
     * @param  string $path
55
     * @return string
56
     */
57
    public function getUrlConfirm($path)
58
    {
59
        // check if object exists
60
        try {
61
            $this->getTimestamp($path);
62
        } catch (BadResponseError $e) {
63
            throw $e;
64
        }
65
66
        $this->checkParams();
67
68
        return $this->getEndpoint().$path;
69
    }
70
71
    /**
72
     * Generate a temporary URL for private containers.
73
     *
74
     * @param  string   $path
75
     * @param  Carbon   $expiration
76
     * @param  array    $options
77
     * @return string
78
     */
79
    public function getTemporaryUrl($path, $expiration, $options = [])
80
    {
81
        $this->checkParams();
82
83
        // expiry is relative to current time
84
        $expiresAt = $expiration instanceof Carbon ? $expiration->timestamp : (int) (time() + 60 * 60);
85
86
        // get the method
87
        $method = isset($options['method']) ? $options['method'] : 'GET';
88
89
        // the url on the OVH host
90
        $codePath = sprintf(
91
            '/v1/AUTH_%s/%s/%s',
92
            $this->urlVars['projectId'],
93
            $this->urlVars['container'],
94
            $path
95
        );
96
97
        // body for the HMAC hash
98
        $body = sprintf("%s\n%s\n%s", $method, $expiresAt, $codePath);
99
100
        // the actual hash signature
101
        $signature = hash_hmac('sha1', $body, $this->urlVars['urlKey']);
102
103
        // return the url
104
        return sprintf(
105
            '%s?temp_url_sig=%s&temp_url_expires=%s',
106
            $this->getEndpoint().$path,
107
            $signature,
108
            $expiresAt
109
        );
110
    }
111
112
    /**
113
     * Gets the endpoint url of the bucket.
114
     *
115
     * @return string
116
     */
117
    protected function getEndpoint()
118
    {
119
        $this->checkParams();
120
121
        return isset($this->urlVars['endpoint'])
122
            // allows assigning custom endpoint url
123
            ? rtrim($this->urlVars['endpoint'], '/').'/'
124
            // if no custom endpoint assigned, use traditional swift v1 endpoint
125
            : sprintf(
126
                'https://storage.%s.cloud.ovh.net/v1/AUTH_%s/%s/',
127
                $this->urlVars['region'],
128
                $this->urlVars['projectId'],
129
                $this->urlVars['container']
130
            );
131
    }
132
133
    /**
134
     * Check if the url support variables have
135
     * been correctly defined.
136
     *
137
     * @return void|BadMethodCallException
138
     */
139
    protected function checkParams()
140
    {
141
        $needKeys = ['region', 'projectId', 'container', 'urlKey', 'endpoint'];
142
143
        if (! is_array($this->urlVars) || count(array_intersect($needKeys, array_keys($this->urlVars))) !== count($needKeys)) {
144
            throw new BadMethodCallException('Insufficient Url Params', 1);
145
        }
146
    }
147
    
148
    /**
149
     * {@inheritdoc}
150
     */
151
    public function write($path, $contents, Config $config, $size = 0)
152
    {
153
        $this->config = $config;
0 ignored issues
show
Bug introduced by
The property config does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
154
        
155
        parent::write();
0 ignored issues
show
Bug introduced by
The call to write() misses some required arguments starting with $path.
Loading history...
156
    }
157
158
    /**
159
     * Include support for object deletion.
160
     *
161
     * @param string $path
162
     * @see Nimbusoft\Flysystem\OpenStack
163
     *
164
     * @return array
165
     */
166
    protected function getData($path)
167
    {
168
        $data = ['name' => $path];
169
        
170
        if (array_key_exists('deleteAfter', $this->config) ) {
171
            $data += ['deleteAfter' => $this->config['deleteAfter']];
172
        } elseif (array_key_exists('deleteAt', $this->config) ) {
173
            $data += ['deleteAt' => $this->config['deleteAt']];
174
        }
175
176
        return $data;
177
    }
178
}
179