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

OVHSwiftAdapter::getTemporaryUrl()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

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