Storage::checkIsSane()   A
last analyzed

Complexity

Conditions 5
Paths 6

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 28
ccs 0
cts 17
cp 0
rs 9.1608
c 0
b 0
f 0
cc 5
nc 6
nop 1
crap 30
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
        $isOk = true;
273
        $name = $package->getNormalName();
274
        try {
275
            $directoryIterator = new \DirectoryIterator($this->buildPath('p', $name));
276
            $iterator = new \RegexIterator($directoryIterator, '/^.+\.json$/i', \RecursiveRegexIterator::GET_MATCH);
277
        } catch (\UnexpectedValueException $e) {
278
            return false;
279
        }
280
281
        foreach ($iterator as $match) {
282
            $filename = $match[0];
283
            $sha = basename($filename, '.json');
284
            if ($sha === 'latest') {
285
                continue;
286
            }
287
288
            $path = $this->buildPath('p', $name, $filename);
289
            $fileHash = hash_file('sha256', $path);
290
            if ($sha !== $fileHash) {
291
                unlink($path);
292
                $isOk = false;
293
            }
294
        }
295
296
        return $isOk;
297
    }
298
}
299