elFinderVolumeFlysystemGoogleDriveNetmount   C
last analyzed

Complexity

Total Complexity 57

Size/Duplication

Total Lines 314
Duplicated Lines 24.52 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 0
Metric Value
dl 77
loc 314
rs 5.1724
c 0
b 0
f 0
wmc 57
lcom 0
cbo 2

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 14 1
F netmountPrepare() 77 163 31
B netunmount() 0 14 5
F mount() 0 63 15
A init() 0 13 4
A tmbname() 0 4 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like elFinderVolumeFlysystemGoogleDriveNetmount often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use elFinderVolumeFlysystemGoogleDriveNetmount, and based on these observations, apply Extract Interface, too.

1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 14 and the first side effect is on line 11.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
3
use League\Flysystem\Filesystem;
4
use League\Flysystem\Adapter\Local;
5
use Hypweb\Flysystem\Cached\Extra\Hasdir;
6
use League\Flysystem\Cached\CachedAdapter;
7
use Hypweb\Flysystem\GoogleDrive\GoogleDriveAdapter;
8
use League\Flysystem\Cached\Storage\Adapter as ACache;
9
use Hypweb\Flysystem\Cached\Extra\DisableEnsureParentDirectories;
10
11
elFinder::$netDrivers['googledrive'] = 'FlysystemGoogleDriveNetmount';
12
13
if (! class_exists('elFinderVolumeFlysystemGoogleDriveCache', false)) {
14
    class elFinderVolumeFlysystemGoogleDriveCache extends ACache
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
15
    {
16
        use Hasdir;
17
        use DisableEnsureParentDirectories;
18
    }
19
}
20
21
class elFinderVolumeFlysystemGoogleDriveNetmount extends \Hypweb\elFinderFlysystemDriverExt\Driver
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
22
{
23
    public function __construct()
24
    {
25
        parent::__construct();
26
27
        $opts = [
28
            'rootCssClass' => 'elfinder-navbar-root-googledrive',
29
            'gdAlias' => '%s@GDrive',
30
            'gdCacheDir' => __DIR__.'/.tmp',
31
            'gdCachePrefix' => 'gd-',
32
            'gdCacheExpire' => 600,
33
        ];
34
35
        $this->options = array_merge($this->options, $opts);
36
    }
37
38
    /**
39
     * Prepare
40
     * Call from elFinder::netmout() before volume->mount().
41
     *
42
     * @param $options
43
     * @return array
44
     * @author Naoki Sawada
45
     */
46
    public function netmountPrepare($options)
0 ignored issues
show
Coding Style introduced by
netmountPrepare uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
47
    {
48
        if (empty($options['client_id']) && defined('ELFINDER_GOOGLEDRIVE_CLIENTID')) {
49
            $options['client_id'] = ELFINDER_GOOGLEDRIVE_CLIENTID;
50
        }
51
        if (empty($options['client_secret']) && defined('ELFINDER_GOOGLEDRIVE_CLIENTSECRET')) {
52
            $options['client_secret'] = ELFINDER_GOOGLEDRIVE_CLIENTSECRET;
53
        }
54
55
        if (! isset($options['pass'])) {
56
            $options['pass'] = '';
57
        }
58
59
        try {
60
            $client = new \Google_Client();
61
            $client->setClientId($options['client_id']);
62
            $client->setClientSecret($options['client_secret']);
63
64 View Code Duplication
            if ($options['pass'] === 'reauth') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
65
                $options['pass'] = '';
66
                $this->session->set('GoogleDriveAuthParams', [])->set('GoogleDriveTokens', []);
67
            } elseif ($options['pass'] === 'googledrive') {
68
                $options['pass'] = '';
69
            }
70
71
            $options = array_merge($this->session->get('GoogleDriveAuthParams', []), $options);
72
73 View Code Duplication
            if (! isset($options['access_token'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
74
                $options['access_token'] = $this->session->get('GoogleDriveTokens', []);
75
                $this->session->remove('GoogleDriveTokens');
76
            }
77
            $aToken = $options['access_token'];
78
79
            $rootObj = $service = null;
80 View Code Duplication
            if ($aToken) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
81
                try {
82
                    $client->setAccessToken($aToken);
83
                    if ($client->isAccessTokenExpired()) {
84
                        $aToken = array_merge($aToken, $client->fetchAccessTokenWithRefreshToken());
85
                        $client->setAccessToken($aToken);
86
                    }
87
                    $service = new \Google_Service_Drive($client);
88
                    $rootObj = $service->files->get('root');
89
90
                    $options['access_token'] = $aToken;
91
                    $this->session->set('GoogleDriveAuthParams', $options);
92
                } catch (Exception $e) {
93
                    $aToken = [];
94
                    $options['access_token'] = [];
95
                    if ($options['user'] !== 'init') {
96
                        $this->session->set('GoogleDriveAuthParams', $options);
97
98
                        return ['exit' => true, 'error' => elFinder::ERROR_REAUTH_REQUIRE];
99
                    }
100
                }
101
            }
102
103
            if ($options['user'] === 'init') {
104
                if (empty($options['url'])) {
105
                    $options['url'] = elFinder::getConnectorUrl();
106
                }
107
108
                $callback = $options['url']
109
                           .'?cmd=netmount&protocol=googledrive&host=1';
110
                $client->setRedirectUri($callback);
111
112
                if (! $aToken && empty($_GET['code'])) {
113
                    $client->setScopes([Google_Service_Drive::DRIVE]);
114
                    if (! empty($options['offline'])) {
115
                        $client->setApprovalPrompt('force');
116
                        $client->setAccessType('offline');
117
                    }
118
                    $url = $client->createAuthUrl();
119
120
                    $html = '<input id="elf-volumedriver-googledrive-host-btn" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" value="{msg:btnApprove}" type="button" onclick="window.open(\''.$url.'\')">';
121
                    $html .= '<script>
122
                        $("#'.$options['id'].'").elfinder("instance").trigger("netmount", {protocol: "googledrive", mode: "makebtn"});
123
                    </script>';
124 View Code Duplication
                    if (empty($options['pass']) && $options['host'] !== '1') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
125
                        $options['pass'] = 'return';
126
                        $this->session->set('GoogleDriveAuthParams', $options);
127
128
                        return ['exit' => true, 'body' => $html];
129
                    } else {
130
                        $out = [
131
                            'node' => $options['id'],
132
                            'json' => '{"protocol": "googledrive", "mode": "makebtn", "body" : "'.str_replace($html, '"', '\\"').'", "error" : "'.elFinder::ERROR_ACCESS_DENIED.'"}',
133
                            'bind' => 'netmount',
134
                        ];
135
136
                        return ['exit' => 'callback', 'out' => $out];
137
                    }
138
                } else {
139 View Code Duplication
                    if (! empty($_GET['code'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
140
                        $aToken = $client->fetchAccessTokenWithAuthCode($_GET['code']);
141
                        $options['access_token'] = $aToken;
142
                        $this->session->set('GoogleDriveTokens', $aToken)->set('GoogleDriveAuthParams', $options);
143
                        $out = [
144
                            'node' => $options['id'],
145
                            'json' => '{"protocol": "googledrive", "mode": "done", "reset": 1}',
146
                            'bind' => 'netmount',
147
                        ];
148
149
                        return ['exit' => 'callback', 'out' => $out];
150
                    }
151
                    $folders = [];
152 View Code Duplication
                    foreach ($service->files->listFiles([
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
153
                        'pageSize' => 1000,
154
                        'q' => 'trashed = false and mimeType = "application/vnd.google-apps.folder"',
155
                    ]) as $f) {
156
                        $folders[$f->getId()] = $f->getName();
157
                    }
158
                    natcasesort($folders);
159
                    $folders = ['root' => $rootObj->getName()] + $folders;
160
                    $folders = json_encode($folders);
161
                    $json = '{"protocol": "googledrive", "mode": "done", "folders": '.$folders.'}';
162
                    $options['pass'] = 'return';
163
                    $html = 'Google.com';
164
                    $html .= '<script>
165
                        $("#'.$options['id'].'").elfinder("instance").trigger("netmount", '.$json.');
166
                    </script>';
167
                    $this->session->set('GoogleDriveAuthParams', $options);
168
169
                    return ['exit' => true, 'body' => $html];
170
                }
171
            }
172
        } catch (Exception $e) {
173
            $this->session->remove('GoogleDriveAuthParams')->remove('GoogleDriveTokens');
174 View Code Duplication
            if (empty($options['pass'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
175
                return ['exit' => true, 'body' => '{msg:'.elFinder::ERROR_ACCESS_DENIED.'}'.' '.$e->getMessage()];
176
            } else {
177
                return ['exit' => true, 'error' => [elFinder::ERROR_ACCESS_DENIED, $e->getMessage()]];
178
            }
179
        }
180
181
        if (! $aToken) {
182
            return ['exit' => true, 'error' => elFinder::ERROR_REAUTH_REQUIRE];
183
        }
184
185
        if ($options['path'] === '/') {
186
            $options['path'] = 'root';
187
        }
188
189
        try {
190
            $file = $service->files->get($options['path']);
191
            $options['alias'] = sprintf($this->options['gdAlias'], $file->getName());
192
        } catch (Google_Service_Exception $e) {
0 ignored issues
show
Bug introduced by
The class Google_Service_Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
193
            $err = json_decode($e->getMessage(), true);
194 View Code Duplication
            if (isset($err['error']) && $err['error']['code'] == 404) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
195
                return ['exit' => true, 'error' => [elFinder::ERROR_TRGDIR_NOT_FOUND, $options['path']]];
196
            } else {
197
                return ['exit' => true, 'error' => $e->getMessage()];
198
            }
199
        } catch (Exception $e) {
200
            return ['exit' => true, 'error' => $e->getMessage()];
201
        }
202
203 View Code Duplication
        foreach (['host', 'user', 'pass', 'id', 'offline'] as $key) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
204
            unset($options[$key]);
205
        }
206
207
        return $options;
208
    }
209
210
    /**
211
     * process of on netunmount
212
     * Drop table `dropbox` & rm thumbs.
213
     *
214
     * @param $netVolumes
215
     * @param $key
216
     * @return bool
217
     * @internal param array $options
218
     */
219
    public function netunmount($netVolumes, $key)
220
    {
221
        $cache = $this->options['gdCacheDir'].DIRECTORY_SEPARATOR.$this->options['gdCachePrefix'].$this->netMountKey;
222
        if (file_exists($cache) && is_writable($cache)) {
223
            unlink($cache);
224
        }
225
        if ($tmbs = glob($this->tmbPath.DIRECTORY_SEPARATOR.$this->netMountKey.'*')) {
226
            foreach ($tmbs as $file) {
227
                unlink($file);
228
            }
229
        }
230
231
        return true;
232
    }
233
234
    /**
235
     * "Mount" volume.
236
     * Return true if volume available for read or write,
237
     * false - otherwise.
238
     *
239
     * @param array $opts
240
     * @return bool
241
     * @author Naoki Sawada
242
     */
243
    public function mount(array $opts)
244
    {
245
        $creds = null;
246
        if (isset($opts['access_token'])) {
247
            $this->netMountKey = md5(implode('-', ['googledrive', $opts['path'], (isset($opts['access_token']['refresh_token']) ? $opts['access_token']['refresh_token'] : $opts['access_token']['access_token'])]));
248
        }
249
250
        $client = new \Google_Client();
251
        $client->setClientId($opts['client_id']);
252
        $client->setClientSecret($opts['client_secret']);
253
254
        if (! empty($opts['access_token'])) {
255
            $client->setAccessToken($opts['access_token']);
256
        }
257
        if ($client->isAccessTokenExpired()) {
258
            try {
259
                $creds = $client->fetchAccessTokenWithRefreshToken();
260
            } catch (LogicException $e) {
261
                $this->session->remove('GoogleDriveAuthParams');
262
                throw $e;
263
            }
264
        }
265
266
        $service = new \Google_Service_Drive($client);
267
268
        // If path is not set, use the root
269
        if (! isset($opts['path']) || $opts['path'] === '') {
270
            $opts['path'] = 'root';
271
        }
272
273
        $googleDrive = new GoogleDriveAdapter($service, $opts['path'], ['useHasDir' => true]);
274
275
        $opts['fscache'] = null;
276
        if ($this->options['gdCacheDir'] && is_writable($this->options['gdCacheDir'])) {
277
            if ($this->options['gdCacheExpire']) {
278
                $opts['fscache'] = new elFinderVolumeFlysystemGoogleDriveCache(new Local($this->options['gdCacheDir']), $this->options['gdCachePrefix'].$this->netMountKey, $this->options['gdCacheExpire']);
279
            }
280
        }
281
        if ($opts['fscache']) {
282
            $filesystem = new Filesystem(new CachedAdapter($googleDrive, $opts['fscache']));
283
        } else {
284
            $filesystem = new Filesystem($googleDrive);
285
        }
286
287
        $opts['driver'] = 'FlysystemExt';
288
        $opts['filesystem'] = $filesystem;
289
        $opts['separator'] = '/';
290
        $opts['checkSubfolders'] = true;
291
        if (! isset($opts['alias'])) {
292
            $opts['alias'] = 'GoogleDrive';
293
        }
294
295
        if ($res = parent::mount($opts)) {
296
            // update access_token of session data
297
            if ($creds) {
298
                $netVolumes = $this->session->get('netvolume');
299
                $netVolumes[$this->netMountKey]['access_token'] = array_merge($netVolumes[$this->netMountKey]['access_token'], $creds);
300
                $this->session->set('netvolume', $netVolumes);
301
            }
302
        }
303
304
        return $res;
305
    }
306
307
    /**
308
     * Prepare driver before mount volume.
309
     * Return true if volume is ready.
310
     *
311
     * @return bool
312
     **/
313
    protected function init()
314
    {
315
        if (empty($this->options['icon'])) {
316
            $this->options['icon'] = true;
317
        }
318
        if ($res = parent::init()) {
319
            if ($this->options['icon'] === true) {
320
                unset($this->options['icon']);
321
            }
322
        }
323
324
        return $res;
325
    }
326
327
    /**
328
     * {@inheritdoc}
329
     */
330
    protected function tmbname($stat)
331
    {
332
        return $this->netMountKey.substr(substr($stat['hash'], strlen($this->id)), -38).$stat['ts'].'.png';
333
    }
334
}
335