Passed
Push — master ( a42092...8afea9 )
by Goffy
03:23
created

DirectoryHandler::getDirList()   B

Complexity

Conditions 7
Paths 8

Size

Total Lines 56
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 33
c 1
b 0
f 0
nc 8
nop 5
dl 0
loc 56
rs 8.4586

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
6
namespace XoopsModules\Wgfilemanager;
7
8
/*
9
 You may not change or alter any portion of this comment or credits
10
 of supporting developers from this source code or any supporting source code
11
 which is considered copyrighted (c) material of the original comment or credit authors.
12
13
 This program is distributed in the hope that it will be useful,
14
 but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16
*/
17
18
/**
19
 * wgFileManager module for xoops
20
 *
21
 * @copyright    2021 XOOPS Project (https://xoops.org)
22
 * @license      GPL 2.0 or later
23
 * @package      wgfilemanager
24
 * @author       Goffy - Wedega - Email:[email protected] - Website:https://xoops.wedega.com
25
 */
26
27
use Xmf\Request;
28
use XoopsModules\Wgfilemanager;
29
use XoopsModules\Wgfilemanager\Common\FilesManagement;
30
31
32
/**
33
 * Class Object Handler Directory
34
 */
35
class DirectoryHandler extends \XoopsPersistableObjectHandler
36
{
37
    /**
38
     * Constructor
39
     *
40
     * @param \XoopsDatabase $db
41
     */
42
    public function __construct(\XoopsDatabase $db)
43
    {
44
        parent::__construct($db, 'wgfilemanager_directory', Directory::class, 'id', 'name');
45
    }
46
47
    /**
48
     * @param bool $isNew
49
     *
50
     * @return object
51
     */
52
    public function create($isNew = true)
53
    {
54
        return parent::create($isNew);
55
    }
56
57
    /**
58
     * retrieve a field
59
     *
60
     * @param int $id field id
61
     * @param null $fields fields
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $fields is correct as it would always require null to be passed?
Loading history...
62
     * @return \XoopsObject|null reference to the {@link Get} object
63
     */
64
    public function get($id = null, $fields = null)
65
    {
66
        return parent::get($id, $fields);
67
    }
68
69
    /**
70
     * get inserted id
71
     *
72
     * @return int reference to the {@link Get} object
73
     */
74
    public function getInsertId()
75
    {
76
        return $this->db->getInsertId();
77
    }
78
79
    /**
80
     * Get Count Directory in the database
81
     * @param int    $start
82
     * @param int    $limit
83
     * @param string $sort
84
     * @param string $order
85
     * @return int
86
     */
87
    public function getCountDirectory($start = 0, $limit = 0, $sort = 'id ASC, name', $order = 'ASC')
88
    {
89
        $crCountDirectory = new \CriteriaCompo();
90
        $crCountDirectory = $this->getDirectoryCriteria($crCountDirectory, $start, $limit, $sort, $order);
91
        return $this->getCount($crCountDirectory);
0 ignored issues
show
Bug introduced by
$crCountDirectory of type integer is incompatible with the type CriteriaElement|null expected by parameter $criteria of XoopsPersistableObjectHandler::getCount(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

91
        return $this->getCount(/** @scrutinizer ignore-type */ $crCountDirectory);
Loading history...
92
    }
93
94
    /**
95
     * Get All Directory in the database
96
     * @param int    $start
97
     * @param int    $limit
98
     * @param string $sort
99
     * @param string $order
100
     * @return array
101
     */
102
    public function getAllDirectory($start = 0, $limit = 0, $sort = 'id ASC, name', $order = 'ASC')
103
    {
104
        $crAllDirectory = new \CriteriaCompo();
105
        $crAllDirectory = $this->getDirectoryCriteria($crAllDirectory, $start, $limit, $sort, $order);
106
        return $this->getAll($crAllDirectory);
0 ignored issues
show
Bug introduced by
$crAllDirectory of type integer is incompatible with the type CriteriaElement|null expected by parameter $criteria of XoopsPersistableObjectHandler::getAll(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

106
        return $this->getAll(/** @scrutinizer ignore-type */ $crAllDirectory);
Loading history...
107
    }
108
109
    /**
110
     * Get Criteria Directory
111
     * @param        $crDirectory
112
     * @param int    $start
113
     * @param int    $limit
114
     * @param string $sort
115
     * @param string $order
116
     * @return int
117
     */
118
    private function getDirectoryCriteria($crDirectory, $start, $limit, $sort, $order)
119
    {
120
        $crDirectory->setStart($start);
121
        $crDirectory->setLimit($limit);
122
        $crDirectory->setSort($sort);
123
        $crDirectory->setOrder($order);
124
        return $crDirectory;
125
    }
126
127
    /**
128
     * Get full path of given parent directory
129
     *
130
     * @param int $parent_id
131
     * @return string
132
     */
133
    public function getFullPath($parent_id) {
134
135
        $path = '';
136
        if ($parent_id > 0) {
137
            $path = $this->getFullPathRecursive($parent_id);
138
        }
139
        if ('' === $path) {
140
            return '';
141
        }
142
        $pathArray = \explode('/', $path);
143
        \krsort($pathArray);
144
145
        return \implode('/', \array_filter($pathArray));
146
    }
147
148
    /**
149
     * Get full path of given parent directory
150
     *
151
     * @param int $parent_id
152
     * @return string
153
     */
154
    public function getFullPathRecursive($parent_id) {
155
        $path = '';
156
        if ($parent_id > 1) {
157
            $directoryObj = $this->get($parent_id);
158
            $path .= mb_strtolower($directoryObj->getVar('name'));
159
            if ($directoryObj->getVar('parent_id') > 1) {
160
                $path .= '/' . $this->getFullPathRecursive($directoryObj->getVar('parent_id'));
161
            }
162
        }
163
        return $path;
164
    }
165
166
    /**
167
     * Check whether given path is a directory
168
     *
169
     * @param string $path
170
     * @return boolean
171
     */
172
    public function existDirectory ($path) {
173
174
        return \is_dir(\WGFILEMANAGER_REPO_PATH . $path);
175
176
    }
177
178
    /**
179
     * Create directory from given path
180
     *
181
     * @param string $path
182
     * @return boolean
183
     */
184
    public function createDirectory($path) {
185
186
        FilesManagement::createFolder(\WGFILEMANAGER_REPO_PATH . $path);
187
188
    }
189
190
    /**
191
     * Rename directory
192
     *
193
     * @param string $oldDirname
194
     * @param string $newDirname
195
     * @return boolean
196
     */
197
    public function renameDirectory($oldDirname, $newDirname)
198
    {
199
        $oldFilePath = \WGFILEMANAGER_REPO_PATH . $oldDirname;
200
        $newFilePath = \WGFILEMANAGER_REPO_PATH . $newDirname;
201
202
        if (\file_exists($oldFilePath)) {
203
            if (!\file_exists($newFilePath)) {
204
                return \rename($oldFilePath, $newFilePath);
205
            } else {
206
                throw new \Exception('New filename already exists.');
207
            }
208
        } else {
209
            throw new \Exception('Old file does not exist.');
210
        }
211
    }
212
213
    /**
214
     * Delete directory from given path
215
     *
216
     * @param string $path
217
     * @return boolean
218
     */
219
    public function deleteDirectory($path)
220
    {
221
        $fullPath = \WGFILEMANAGER_REPO_PATH . $path;
222
223
        if (!FilesManagement::deleteDirectory($fullPath)) {
224
            return false;
225
        }
226
227
        return !$this->existDirectory($fullPath);
228
229
    }
230
231
    /**
232
     * Check whether given directory is used as parent
233
     *
234
     * @param int $dirId
235
     * @return boolean
236
     */
237
    public function dirIsParent ($dirId) {
238
        $crCountDirectory = new \CriteriaCompo();
239
        $crCountDirectory->add(new \Criteria('parent_id', $dirId));
240
241
        return $this->getCount($crCountDirectory) > 0;
242
243
    }
244
245
    /**
246
     * Count subdirectories from given directory
247
     *
248
     * @param int $dirId
249
     * @return integer
250
     */
251
    public function countSubDirs($dirId) {
252
253
        $crSubDir = new \CriteriaCompo();
254
        $crSubDir->add(new \Criteria('parent_id', $dirId));
255
256
        return $this->getCount($crSubDir) ;
257
258
    }
259
260
    /**
261
     * Count files in given directory
262
     *
263
     * @param string $fullpath
264
     * @return integer
265
     */
266
    public function countFiles($fullpath) {
267
        $file_new = [];
268
        $path = \WGFILEMANAGER_REPO_PATH . $fullpath;
269
        if (!\file_exists($path)) {
270
            return -1;
271
        }
272
        $files = scandir($path);
273
        for($i = 0 ; $i < count($files) ; $i++){
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
274
            if(\is_file($path .  '/' . $files[$i]) && $files[$i] !='.' && $files[$i] !='..'  && $files[$i] !='index.php'  && $files[$i] !='index.html') {
275
                $file_new[] = $files[$i];
276
            }
277
        }
278
279
        return count($file_new);
280
    }
281
282
    /**
283
     * Delete data from all subdirectories from given directory
284
     *
285
     * @param int $dirId
286
     * @return boolean
287
     */
288
    public function deleteSubDirData($dirId) {
289
290
        $crSubDir = new \CriteriaCompo();
291
        $crSubDir->add(new \Criteria('parent_id', $dirId));
292
        if ($this->getCount($crSubDir) > 0) {
293
            $directoryAll = $this->getAll($crSubDir);
294
            foreach (\array_keys($directoryAll) as $i) {
295
                if (!$this->deleteSubDirData($i)) {
296
                    return false;
297
                }
298
            }
299
        }
300
        $directoryObj = $this->get($dirId);
301
        if (\is_object($directoryObj) && !$this->delete($directoryObj)) {
302
            return false;
303
        }
304
305
        return true;
306
307
    }
308
309
    /**
310
     * Move directory
311
     *
312
     * @param string $pathSource
313
     * @param string $pathDest
314
     * @return boolean
315
     */
316
    public function moveDirectory($pathSource, $pathDest) {
317
318
        if(!FilesManagement::rcopy(\WGFILEMANAGER_REPO_PATH . $pathSource, \WGFILEMANAGER_REPO_PATH . $pathDest)){
319
            return false;
320
        }
321
        if (!FilesManagement::deleteDirectory(\WGFILEMANAGER_REPO_PATH . $pathSource)) {
322
            return false;
323
        }
324
325
        return true;
326
    }
327
328
    /**
329
     * Returns an array directories
330
     *
331
     * @param int    $dirId
332
     * @param int    $dirCurrent
333
     * @param int    $levelCurrent
334
     * @param string $sortBy
335
     * @param string $orderBy
336
     * @return array
337
     */
338
    public function getDirList($dirId, $dirCurrent, $levelCurrent = 1, $sortBy = 'weight ASC, id', $orderBy = 'ASC') {
339
340
        $result = [];
341
/*        if (0 === $dirId) {
342
            $result[0]['id'] = 0;
343
            $result[0]['parent_id'] = 0;
344
            $result[0]['name'] = \_MA_WGFILEMANAGER_DIRECTORY_HOME;
345
            $result[0]['state'] = 0 === $dirCurrent ? 'open' : 'closed';
346
            $result[0]['class'] = 'home';
347
            $result[0]['level'] = 0;
348
            $crSubDir = new \CriteriaCompo();
349
            $crSubDir->add(new \Criteria('parent_id', $dirId));
350
            $result[0]['count_subdirs'] = $this->getCount($crSubDir);
351
            $result[0]['count_files'] = $this->countFiles('');
352
            $result[0]['subdirs'] = [];
353
        }*/
354
        //create list of parents
355
        $parents  = [];
356
        $parentId = 0;
357
        $dirCurrObj = $this->get($dirCurrent);
358
        if (\is_object($dirCurrObj)) {
359
            $parentId = $dirCurrObj->getVar('parent_id');
360
        }
361
        $parents[] = $parentId;
362
        while ($parentId > 0) {
363
            $parentId = $this->get($parentId)->getVar('parent_id');
364
            $parents[] = $parentId;
365
        }
366
367
        $levelCurrent++;
368
        $crSubDir = new \CriteriaCompo();
369
        $crSubDir->add(new \Criteria('parent_id', $dirId));
370
        $crSubDir->setSort($sortBy);
371
        $crSubDir->setOrder($orderBy);
372
        if ($this->getCount($crSubDir) > 0) {
373
            $directoryAll = $this->getAll($crSubDir);
374
            foreach (\array_keys($directoryAll) as $i) {
375
                $directory = $directoryAll[$i]->getValuesDir();
376
                $result[$i]['id'] = $directory['id'];
377
                $result[$i]['parent_id'] = $directory['parent_id'];
378
                $result[$i]['name'] = $directory['name'];
379
                $result[$i]['state'] = $i === $dirCurrent ? 'open' : 'closed';
380
                $result[$i]['highlight'] = $i === $dirCurrent;
381
                $result[$i]['show'] = in_array($i, $parents);
382
                $result[$i]['count_subdirs'] = $directory['count_subdirs'];
383
                $result[$i]['count_files'] = $directory['count_files'];
384
                $result[$i]['level'] = $levelCurrent;
385
                $result[$i]['weight'] = $directory['weight'];
386
                $result[$i]['favorite_id'] = $directory['favorite_id'];
387
                if ($directory['count_subdirs'] > 0) {
388
                    $result[$i]['subdirs'] = $this->getDirList($i, $dirCurrent, $levelCurrent);
389
                }
390
            }
391
        }
392
393
        return $result;
394
395
    }
396
397
    /**
398
     * Returns an array directories for form select
399
     *
400
     * @param int $dirId
401
     * @return array
402
     */
403
    public function getDirListFormSelect($dirId) {
404
405
        $result = [];
406
        $crSubDir = new \CriteriaCompo();
407
        $crSubDir->add(new \Criteria('parent_id', $dirId));
408
        $crSubDir->setSort('weight ASC, id');
409
        $crSubDir->setOrder('ASC');
410
        if ($this->getCount($crSubDir) > 0) {
411
            $directoryAll = $this->getAll($crSubDir);
412
            foreach (\array_keys($directoryAll) as $i) {
413
                $directory = $directoryAll[$i]->getValuesDir();
414
                $name = $directory['name'];
415
                if ($dirId > 0) {
416
                    $level = \mb_substr_count($directory['fullpath'], '/');
417
                    $name = \str_repeat('- ', $level) . $name;
418
                }
419
                $result[$i] = [$directory['id'] => $name];
420
                if ($directory['count_subdirs'] > 0) {
421
                    $result[$i][]= $this->getDirListFormSelect($i);
422
                }
423
            }
424
        }
425
426
        return $result;
427
    }
428
429
    /**
430
     * Returns an array directories for breadcrumbs
431
     *
432
     * @param int $dirId
433
     * @return array
434
     */
435
    public function getDirListBreadcrumb($dirId) {
436
437
        $result = [];
438
        do {
439
            $dirObj = $this->get($dirId);
440
            if (\is_object($dirObj)) {
441
                if ($dirId > 1) {
442
                    $result[$dirId] = $dirObj->getVar('name');
443
                }
444
                $dirId = $dirObj->getVar('parent_id');
445
            } else {
446
                $dirId = 0;
447
            }
448
        } while ($dirId > 0);
449
450
        return $result;
451
    }
452
453
    /**
454
     * Returns an array of directories
455
     *
456
     * @param int    $dirId
457
     * @param string $sortBy
458
     * @param string $orderBy
459
     * @return array
460
     */
461
    public function getSubDirList($dirId, $sortBy = 'weight ASC, id', $orderBy = 'ASC') {
462
463
        $result = [];
464
        $crSubDir = new \CriteriaCompo();
465
        $crSubDir->add(new \Criteria('parent_id', $dirId));
466
        $crSubDir->setSort($sortBy);
467
        $crSubDir->setOrder($orderBy);
468
        if ($this->getCount($crSubDir) > 0) {
469
            $directoryAll = $this->getAll($crSubDir);
470
            foreach (\array_keys($directoryAll) as $i) {
471
                $result[$i] = $directoryAll[$i]->getValuesDir();
472
            }
473
        }
474
475
        return $result;
476
477
    }
478
479
    /**
480
     * Returns an array of favorite directories
481
     *
482
     * @return array
483
     */
484
    public function getFavDirList() {
485
        $result = [];
486
        //get current user
487
        $userUid = 0;
488
        if (isset($GLOBALS['xoopsUser']) && \is_object($GLOBALS['xoopsUser'])) {
489
            $userUid = $GLOBALS['xoopsUser']->uid();
490
        }
491
        if ($userUid > 0) {
492
            $crDirectory = new \CriteriaCompo();
493
            $directoryCount = $this->getCount($crDirectory);
494
            if ($directoryCount > 0) {
495
                $crDirectory->setSort('name');
496
                $crDirectory->setOrder('asc');
497
                $directoryAll = $this->getAll($crDirectory);
498
                foreach (\array_keys($directoryAll) as $i) {
499
                    $dirValues = $directoryAll[$i]->getValuesDir();
500
                    if ((int)$dirValues['favorite_id'] > 0) {
501
                        $result[] = $dirValues;
502
                    }
503
                }
504
            }
505
        }
506
        return $result;
507
    }
508
509
    /**
510
     * Returns an array directories
511
     *
512
     * @param int $parentId
513
     * @return boolean
514
     */
515
    public function setDirWeight($parentId) {
516
517
        if (0 == $parentId) {
518
            return true;
519
        }
520
        $crSubDir = new \CriteriaCompo();
521
        $crSubDir->add(new \Criteria('parent_id', $parentId));
522
        $crSubDir->setSort('weight ASC, id');
523
        $crSubDir->setOrder('ASC');
524
        if ($this->getCount($crSubDir) > 0) {
525
            $directoryAll = $this->getAll($crSubDir);
526
            $counter = 0;
527
            foreach (\array_keys($directoryAll) as $i) {
528
                $counter++;
529
                $directoryObj = $this->get($i);
530
                $directoryObj->setVar('weight', $counter);
531
                $this->insert($directoryObj);
0 ignored issues
show
Bug introduced by
It seems like $directoryObj can also be of type null; however, parameter $object of XoopsPersistableObjectHandler::insert() does only seem to accept XoopsObject, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

531
                $this->insert(/** @scrutinizer ignore-type */ $directoryObj);
Loading history...
532
                $this->setDirWeight($i);
533
            }
534
        }
535
536
        return true;
537
538
    }
539
540
}
541