Completed
Push — master ( 2f198a...a6662e )
by Dmitry
17:58 queued 11s
created

Storage   B

Complexity

Total Complexity 46

Size/Duplication

Total Lines 280
Duplicated Lines 2.14 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 2.16%

Importance

Changes 0
Metric Value
wmc 46
lcom 1
cbo 6
dl 6
loc 280
ccs 3
cts 139
cp 0.0216
rs 8.72
c 0
b 0
f 0

19 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 4 1
A acquireLock() 0 9 2
A releaseLock() 0 7 1
A getNextId() 0 11 1
A readLastId() 0 6 3
A writeLastId() 0 6 2
A getLastIdPath() 0 4 1
A writePackage() 0 34 5
A readPackage() 0 20 4
A buildPath() 0 7 1
A buildHashedPath() 0 4 1
B writeProviderLatest() 6 40 10
A writePackagesJson() 0 21 2
A mkdir() 0 8 2
A readJson() 0 4 1
A readPackagesJson() 0 6 1
A readProvider() 0 6 1
A listPackages() 0 11 2
A checkIsSane() 0 28 5

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 Storage 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 Storage, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * Asset Packagist.
4
 *
5
 * @link      https://github.com/hiqdev/asset-packagist
6
 * @package   asset-packagist
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2016-2017, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hiqdev\assetpackagist\components;
12
13
use hiqdev\assetpackagist\exceptions\AssetFileStorageException;
14
use hiqdev\assetpackagist\models\AssetPackage;
15
use Yii;
16
use yii\base\Component;
17
use yii\helpers\Json;
18
19
class Storage extends Component implements StorageInterface
20
{
21
    protected $_path;
22
    protected $_locker;
23
24
    /**
25
     * {@inheritdoc}
26
     */
27 1
    public function init()
28
    {
29 1
        $this->_path = Yii::getAlias('@storage', false);
30 1
    }
31
32
    protected function acquireLock()
33
    {
34
        /* @var $mutex \yii\mutex\Mutex */
35
        $mutex = Yii::$app->mutex;
36
37
        if (!$mutex->acquire('lock', 5)) {
38
            throw new \Exception('failed get lock');
39
        }
40
    }
41
42
    protected function releaseLock()
43
    {
44
        /* @var $mutex \yii\mutex\Mutex */
45
        $mutex = Yii::$app->mutex;
46
47
        $mutex->release('lock');
48
    }
49
50
    /**
51
     * {@inheritdoc}
52
     */
53
    public function getNextId()
54
    {
55
        $this->acquireLock();
56
        {
57
            $nextID = $this->readLastId() + 1;
58
            $this->writeLastId($nextID);
59
        }
60
        $this->releaseLock();
61
62
        return $nextID;
63
    }
64
65
    protected function readLastId()
66
    {
67
        $path = $this->getLastIdPath();
68
69
        return (file_exists($path) ? (int) file_get_contents($path) : 0) ?: 1000000;
70
    }
71
72
    protected function writeLastId($value)
73
    {
74
        if (file_put_contents($this->getLastIdPath(), $value) === false) {
75
            throw new AssetFileStorageException('Filed to write lastId to the storage');
76
        }
77
    }
78
79
    protected function getLastIdPath()
80
    {
81
        return $this->buildPath('lastid');
82
    }
83
84
    /**
85
     * {@inheritdoc}
86
     */
87
    public function writePackage(AssetPackage $package)
88
    {
89
        $name = $package->getNormalName();
90
        $data = [
91
            'packages' => [
92
                $name => $package->getReleases(),
93
            ],
94
        ];
95
        $json = Json::encode($data);
96
        $hash = hash('sha256', $json);
97
        $path = $this->buildHashedPath($name, $hash);
98
        $latestPath = $this->buildHashedPath($name);
99
        if (!file_exists($path)) {
100
            $this->acquireLock();
101
            try {
102
                if ($this->mkdir(dirname($path)) === false) {
103
                    throw new AssetFileStorageException('Failed to create a directory for asset-package', $package);
104
                }
105
                if (file_put_contents($path, $json) === false) {
106
                    throw new AssetFileStorageException('Failed to write package', $package);
107
                }
108
                if (file_put_contents($latestPath, $json) === false) {
109
                    throw new AssetFileStorageException('Failed to write file "latest.json" for asset-packge', $package);
110
                }
111
                $this->writeProviderLatest($name, $hash);
112
            } finally {
113
                $this->releaseLock();
114
            }
115
        } else {
116
            touch($latestPath);
117
        }
118
119
        return $hash;
120
    }
121
122
    /**
123
     * {@inheritdoc}
124
     */
125
    public function readPackage(AssetPackage $package)
126
    {
127
        $name = $package->getNormalName();
128
        $path = $this->buildHashedPath($name);
129
        clearstatcache(false, $path);
130
        if (!file_exists($path)) {
131
            return null;
132
        }
133
        $json = file_get_contents($path);
134
        $updateTime = filemtime($path);
135
        $hash = hash('sha256', $json);
136
        try {
137
            $data = Json::decode($json);
138
        } catch (\Exception $e) {
139
            return null;
140
        }
141
        $releases = isset($data['packages'][$name]) ? $data['packages'][$name] : [];
142
143
        return compact('hash', 'releases', 'updateTime');
144
    }
145
146
    protected function buildPath()
147
    {
148
        $args = func_get_args();
149
        array_unshift($args, $this->_path);
150
151
        return implode(DIRECTORY_SEPARATOR, $args);
152
    }
153
154
    protected function buildHashedPath($name, $hash = 'latest')
155
    {
156
        return $this->buildPath('p', $name, $hash . '.json');
157
    }
158
159
    protected function writeProviderLatest($name, $hash)
160
    {
161
        $latestPath = $this->buildHashedPath('provider-latest');
162
        if (file_exists($latestPath)) {
163
            $data = Json::decode(file_get_contents($latestPath) ?: '[]');
164
        }
165
        if (!isset($data) || !is_array($data)) {
166
            $data = [];
167
        }
168
        if (!isset($data['providers'])) {
169
            $data['providers'] = [];
170
        }
171
        $data['providers'][$name] = ['sha256' => $hash];
172
        $json = Json::encode($data);
173
        $hash = hash('sha256', $json);
174
        $path = $this->buildHashedPath('provider-latest', $hash);
175
176
        if (!file_exists($path)) {
177
            $this->acquireLock();
178
179
            try {
180
                if ($this->mkdir(dirname($path)) === false) {
181
                    throw new AssetFileStorageException('Failed to create a directory for provider-latest storage');
182
                }
183 View Code Duplication
                if (file_put_contents($path, $json) === false) {
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...
184
                    throw new AssetFileStorageException('Failed to write package to provider-latest storage for package "' . $name . '"');
185
                }
186 View Code Duplication
                if (file_put_contents($latestPath, $json) === false) {
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...
187
                    throw new AssetFileStorageException('Failed to write file "latest.json" to provider-latest storage for package "' . $name . '"');
188
                }
189
                $this->writePackagesJson($hash);
190
            } finally {
191
                $this->releaseLock();
192
            }
193
        } else {
194
            touch($latestPath);
195
        }
196
197
        return $hash;
198
    }
199
200
    protected function writePackagesJson($hash)
201
    {
202
        $data = [
203
            'providers-url'     => '/p/%package%/%hash%.json',
204
            'provider-includes' => [
205
                'p/provider-latest/%hash%.json' => [
206
                    'sha256' => $hash,
207
                ],
208
            ],
209
        ];
210
        $this->acquireLock();
211
        $filename = $this->buildPath('packages.json');
212
        try {
213
            if (file_put_contents($filename, Json::encode($data)) === false) {
214
                throw new AssetFileStorageException('Failed to write main packages.json');
215
            }
216
            touch($filename);
217
        } finally {
218
            $this->releaseLock();
219
        }
220
    }
221
222
    /**
223
     * Creates directory $dir and sets chmod 777.
224
     * @param string $dir
225
     * @return bool whether the directory was created successfully
226
     */
227
    protected function mkdir($dir)
228
    {
229
        if (!file_exists($dir)) {
230
            return @mkdir($dir, 0777, true);
231
        }
232
233
        return true;
234
    }
235
236
    public function readJson($path)
237
    {
238
        return Json::decode(file_get_contents($this->buildPath($path)));
239
    }
240
241
    protected function readPackagesJson()
242
    {
243
        $data = $this->readJson('packages.json');
244
245
        return $data['provider-includes'];
246
    }
247
248
    protected function readProvider($path)
249
    {
250
        $data = $this->readJson($path);
251
252
        return $data['providers'];
253
    }
254
255
    /**
256
     * {@inheritdoc}
257
     */
258
    public function listPackages()
259
    {
260
        $packages = [];
261
        $providers = $this->readPackagesJson();
262
        foreach ($providers as $path => $data) {
263
            $path = strtr($path, ['%hash%' => $data['sha256']]);
264
            $packages = array_merge($packages, $this->readProvider($path));
265
        }
266
267
        return $packages;
268
    }
269
270
    public function checkIsSane(AssetPackage $package)
271
    {
272
        $name = $package->getNormalName();
273
        try {
274
            $directoryIterator = new \DirectoryIterator($this->buildPath('p', $name));
275
            $iterator = new \RegexIterator($directoryIterator, '/^.+\.json$/i', \RecursiveRegexIterator::GET_MATCH);
276
        } catch (\UnexpectedValueException $e) {
277
            return false;
278
        }
279
280
        foreach ($iterator as $match) {
281
            $filename = $match[0];
282
            $sha = basename($filename, '.json');
283
            if ($sha === 'latest') {
284
                continue;
285
            }
286
287
            $path = $this->buildPath('p', $name, $filename);
288
            $fileHash = hash_file('sha256', $path);
289
            if ($sha !== $fileHash) {
290
                unlink($path);
291
292
                return false;
293
            }
294
        }
295
296
        return true;
297
    }
298
}
299