Completed
Pull Request — master (#108)
by Vasile
12:35
created

FileHelper::normalizeOptions()   B

Complexity

Conditions 8
Paths 8

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 21
rs 7.1429
cc 8
eloc 12
nc 8
nop 1
1
<?php
2
/**
3
 * This file is part of yii2-imperavi-widget.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 *
8
 * @see https://github.com/vova07/yii2-imperavi-widget
9
 */
10
11
namespace vova07\imperavi\helpers;
12
13
use vova07\imperavi\actions\GetImagesAction;
14
use yii\base\InvalidParamException;
15
use yii\helpers\BaseFileHelper;
16
use yii\helpers\StringHelper;
17
18
/**
19
 * File system helper.
20
 *
21
 * @author Vasile Crudu <[email protected]>
22
 *
23
 * @link https://github.com/vova07/yii2-imperavi-widget
24
 */
25
class FileHelper extends BaseFileHelper
26
{
27
    /**
28
     * @inheritdoc
29
     *
30
     * @param array $options {
31
     *
32
     * @type array $except
33
     * @type array $only
34
     * }
35
     */
36
    public static function findFiles($dir, $options = [], $type = GetImagesAction::TYPE_IMAGES)
37
    {
38
        if (!is_dir($dir)) {
39
            throw new InvalidParamException('The dir argument must be a directory.');
40
        }
41
        $dir = rtrim($dir, DIRECTORY_SEPARATOR);
42
        if (isset($options['url'])) {
43
            $options['url'] = rtrim($options['url'], '/');
44
        }
45
        if (!isset($options['basePath'])) {
46
            $options['basePath'] = realpath($dir);
47
            // this should also be done only once
48
            $options = static::normalizeOptions($options);
49
        }
50
        $list = [];
51
        $handle = opendir($dir);
52
        if ($handle === false) {
53
            // @codeCoverageIgnoreStart
54
            throw new InvalidParamException('Unable to open directory: ' . $dir);
55
            // @codeCoverageIgnoreEnd
56
        }
57
        while (($file = readdir($handle)) !== false) {
58
            if ($file === '.' || $file === '..') {
59
                continue;
60
            }
61
            $path = $dir . DIRECTORY_SEPARATOR . $file;
62
            if (static::filterPath($path, $options)) {
63
                if (is_file($path)) {
64
                    if (isset($options['url'])) {
65
                        $url = str_replace([$options['basePath'], '\\'], [$options['url'], '/'], static::normalizePath($path));
66
67
                        if ($type === GetImagesAction::TYPE_IMAGES) {
68
                            $list[] = [
69
                                'title' => $file,
70
                                'thumb' => $url,
71
                                'image' => $url
72
                            ];
73
                        } elseif ($type === GetImagesAction::TYPE_FILES) {
74
                            $size = self::getFileSize($path);
75
                            $list[] = [
76
                                'title' => $file,
77
                                'name' => $file,
78
                                'link' => $url,
79
                                'size' => $size
80
                            ];
81
                        } else {
82
                            $list[] = $path;
83
                        }
84
                    } else {
85
                        $list[] = $path;
86
                    }
87
                } elseif (!isset($options['recursive']) || $options['recursive']) {
88
                    $list = array_merge($list, static::findFiles($path, $options, $type));
89
                }
90
            }
91
        }
92
        closedir($handle);
93
94
        return $list;
95
    }
96
97
    /**
98
     * @param string $path
99
     *
100
     * @return string filesize in(B|KB|MB|GB)
101
     */
102
    protected static function getFileSize($path)
103
    {
104
        $size = filesize($path);
105
        $labels = ['B', 'KB', 'MB', 'GB'];
106
        $factor = floor((strlen($size) - 1) / 3);
107
108
        return sprintf("%.1f ", $size / pow(1024, $factor)) . $labels[$factor];
109
    }
110
111
    /**
112
     * @inheritdoc
113
     *
114
     * @codeCoverageIgnore
115
     */
116
    private static function parseExcludePattern($pattern)
0 ignored issues
show
Bug introduced by
Consider using a different method name as you override a private method of the parent class.

Overwriting private methods is generally fine as long as you also use private visibility. It might still be preferable for understandability to use a different method name.

Loading history...
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
117
    {
118
        if (!is_string($pattern)) {
119
            throw new InvalidParamException('Exclude/include pattern must be a string.');
120
        }
121
        $result = [
122
            'pattern' => $pattern,
123
            'flags' => 0,
124
            'firstWildcard' => false,
125
        ];
126
        if (!isset($pattern[0])) {
127
            return $result;
128
        }
129
130
        if ($pattern[0] == '!') {
131
            $result['flags'] |= self::PATTERN_NEGATIVE;
132
            $pattern = StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern));
133
        }
134
        $len = StringHelper::byteLength($pattern);
135
        if ($len && StringHelper::byteSubstr($pattern, -1, 1) == '/') {
136
            $pattern = StringHelper::byteSubstr($pattern, 0, -1);
137
            $len--;
138
            $result['flags'] |= self::PATTERN_MUSTBEDIR;
139
        }
140
        if (strpos($pattern, '/') === false) {
141
            $result['flags'] |= self::PATTERN_NODIR;
142
        }
143
        $result['firstWildcard'] = self::firstWildcardInPattern($pattern);
144
        if ($pattern[0] == '*' && self::firstWildcardInPattern(StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern))) === false) {
145
            $result['flags'] |= self::PATTERN_ENDSWITH;
146
        }
147
        $result['pattern'] = $pattern;
148
149
        return $result;
150
    }
151
152
    /**
153
     * @inheritdoc
154
     *
155
     * @codeCoverageIgnore
156
     */
157
    private static function firstWildcardInPattern($pattern)
0 ignored issues
show
Bug introduced by
Consider using a different method name as you override a private method of the parent class.

Overwriting private methods is generally fine as long as you also use private visibility. It might still be preferable for understandability to use a different method name.

Loading history...
158
    {
159
        $wildcards = ['*', '?', '[', '\\'];
160
        $wildcardSearch = function ($r, $c) use ($pattern) {
161
            $p = strpos($pattern, $c);
162
163
            return $r === false ? $p : ($p === false ? $r : min($r, $p));
164
        };
165
166
        return array_reduce($wildcards, $wildcardSearch, false);
167
    }
168
}
169