Completed
Push — master ( 2ec9f0...d428ee )
by Andrii
30:10 queued 22:08
created

Storage   B

Complexity

Total Complexity 40

Size/Duplication

Total Lines 247
Duplicated Lines 2.43 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 2.31%

Importance

Changes 5
Bugs 2 Features 1
Metric Value
wmc 40
c 5
b 2
f 1
lcom 1
cbo 6
dl 6
loc 247
ccs 3
cts 130
cp 0.0231
rs 8.2608

18 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
B writePackage() 0 34 5
A readPackage() 0 16 3
A buildPath() 0 7 1
A buildHashedPath() 0 4 1
D 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

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
    public function init()
28 1
    {
29
        $this->_path = Yii::getAlias('@storage', false);
30 1
    }
31 1
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
        $data = Json::decode($json);
137
        $releases = isset($data['packages'][$name]) ? $data['packages'][$name] : [];
138
139
        return compact('hash', 'releases', 'updateTime');
140
    }
141
142
    protected function buildPath()
143
    {
144
        $args = func_get_args();
145
        array_unshift($args, $this->_path);
146
147
        return implode(DIRECTORY_SEPARATOR, $args);
148
    }
149
150
    protected function buildHashedPath($name, $hash = 'latest')
151
    {
152
        return $this->buildPath('p', $name, $hash . '.json');
153
    }
154
155
    protected function writeProviderLatest($name, $hash)
156
    {
157
        $latestPath = $this->buildHashedPath('provider-latest');
158
        if (file_exists($latestPath)) {
159
            $data = Json::decode(file_get_contents($latestPath) ?: '[]');
160
        }
161
        if (!isset($data) || !is_array($data)) {
162
            $data = [];
163
        }
164
        if (!isset($data['providers'])) {
165
            $data['providers'] = [];
166
        }
167
        $data['providers'][$name] = ['sha256' => $hash];
168
        $json = Json::encode($data);
169
        $hash = hash('sha256', $json);
170
        $path = $this->buildHashedPath('provider-latest', $hash);
171
172
        if (!file_exists($path)) {
173
            $this->acquireLock();
174
175
            try {
176
                if ($this->mkdir(dirname($path)) === false) {
177
                    throw new AssetFileStorageException('Failed to create a directory for provider-latest storage');
178
                }
179 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...
180
                    throw new AssetFileStorageException('Failed to write package to provider-latest storage for package "' . $name . '"');
181
                }
182 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...
183
                    throw new AssetFileStorageException('Failed to write file "latest.json" to provider-latest storage for package "' . $name . '"');
184
                }
185
                $this->writePackagesJson($hash);
186
            } finally {
187
                $this->releaseLock();
188
            }
189
        } else {
190
            touch($latestPath);
191
        }
192
193
        return $hash;
194
    }
195
196
    protected function writePackagesJson($hash)
197
    {
198
        $data = [
199
            'providers-url'     => '/p/%package%/%hash%.json',
200
            'provider-includes' => [
201
                'p/provider-latest/%hash%.json' => [
202
                    'sha256' => $hash,
203
                ],
204
            ],
205
        ];
206
        $this->acquireLock();
207
        $filename = $this->buildPath('packages.json');
208
        try {
209
            if (file_put_contents($filename, Json::encode($data)) === false) {
210
                throw new AssetFileStorageException('Failed to write main packages.json');
211
            }
212
            touch($filename);
213
        } finally {
214
            $this->releaseLock();
215
        }
216
    }
217
218
    /**
219
     * Creates directory $dir and sets chmod 777.
220
     * @param string $dir
221
     * @return bool whether the directory was created successfully
222
     */
223
    protected function mkdir($dir)
224
    {
225
        if (!file_exists($dir)) {
226
            return @mkdir($dir, 0777, true);
227
        }
228
229
        return true;
230
    }
231
232
    public function readJson($path)
233
    {
234
        return Json::decode(file_get_contents($this->buildPath($path)));
235
    }
236
237
    protected function readPackagesJson()
238
    {
239
        $data = $this->readJson('packages.json');
240
241
        return $data['provider-includes'];
242
    }
243
244
    protected function readProvider($path)
245
    {
246
        $data = $this->readJson($path);
247
248
        return $data['providers'];
249
    }
250
251
    /**
252
     * {@inheritdoc}
253
     */
254
    public function listPackages()
255
    {
256
        $packages = [];
257
        $providers = $this->readPackagesJson();
258
        foreach ($providers as $path => $data) {
259
            $path = strtr($path, ['%hash%' => $data['sha256']]);
260
            $packages = array_merge($packages, $this->readProvider($path));
261
        }
262
263
        return $packages;
264
    }
265
}
266