Completed
Push — master ( 41033a...b5b2fa )
by Andrii
06:05 queued 03:01
created

Storage::readLastId()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 6
ccs 0
cts 0
cp 0
rs 9.4285
cc 3
eloc 3
nc 4
nop 0
crap 12
1
<?php
2
3
/*
4
 * Asset Packagist
5
 *
6
 * @link      https://github.com/hiqdev/asset-packagist
7
 * @package   asset-packagist
8
 * @license   BSD-3-Clause
9
 * @copyright Copyright (c) 2016, HiQDev (http://hiqdev.com/)
10
 */
11
12
namespace hiqdev\assetpackagist\components;
13
14
use hiqdev\assetpackagist\helpers\Locker;
15
use hiqdev\assetpackagist\models\AssetPackage;
16
use Yii;
17
use yii\base\Component;
18
use yii\helpers\Json;
19
20
class Storage extends Component
21
{
22
    protected $_path;
23
    protected $_locker;
24
25 1
    public function init()
26
    {
27 1
        $this->_path = Yii::getAlias('@storage', false);
28 1
    }
29
30
    protected function getLocker()
31
    {
32
        if ($this->_locker === null) {
33
            $this->_locker = Locker::getInstance($this->buildPath('lock'));
34
        }
35
36
        return $this->_locker;
37
    }
38
39
    public function getNextID()
40
    {
41
        $this->getLocker()->lock();
42
        {
43
            $nextID = $this->readLastID() + 1;
44
            $this->writeLastID($nextID);
45
        }
46
        $this->getLocker()->release();
47
48
        return $nextID;
49
    }
50
51
    protected function readLastId()
52
    {
53
        $path = $this->getLastIDPath();
54
55
        return (file_exists($path) ? (int) file_get_contents($path) : 0) ?: 1000000;
56
    }
57
58
    protected function writeLastId($value)
59
    {
60
        file_put_contents($this->getLastIDPath(), $value);
61
    }
62
63
    protected function getLastIDPath()
64
    {
65
        return $this->buildPath('lastid');
66
    }
67
68
    public function writePackage(AssetPackage $package)
69
    {
70
        $name = $package->getNormalName();
71
        $data = [
72
            'packages' => [
73
                $name => $package->getReleases(),
74
            ],
75
        ];
76
        $json = Json::encode($data);
77
        $hash = hash('sha256', $json);
78
        $path = $this->buildHashedPath($name, $hash);
79 View Code Duplication
        if (!file_exists($path)) {
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...
80
            $this->getLocker()->lock();
81
            {
82
                static::mkdir(dirname($path));
83
                file_put_contents($path, $json);
84
                file_put_contents($this->buildHashedPath($name), $json);
85
                $this->writeProviderLatest($name, $hash);
86
            }
87
            $this->getLocker()->release();
88
        }
89
90
        return $hash;
91
    }
92
93
    /**
94
     * Reads the $package information from the storage.
95
     *
96
     * @param AssetPackage $package
97
     * @return array|null array of two elements:
98
     *  0 - string sha256 hash of the package
99
     *  1 - array[] releases
100
     *
101
     * Returns null, when package does not exist.
102
     */
103
    public function readPackage(AssetPackage $package)
104
    {
105
        $name = $package->getNormalName();
106
        $path = $this->buildHashedPath($name);
107
        if (!file_exists($path)) {
108
            return null;
109
        }
110
        $json = file_get_contents($path);
111
        $updateTime = filemtime($path);
112
        $hash = hash('sha256', $json);
113
        $data = Json::decode($json);
114
        $releases = isset($data['packages'][$name]) ? $data['packages'][$name] : [];
115
116
        return compact('hash', 'releases', 'updateTime');
117
    }
118
119
    public function buildPath()
120
    {
121
        $args = func_get_args();
122
        array_unshift($args, $this->_path);
123
124
        return implode(DIRECTORY_SEPARATOR, $args);
125
    }
126
127
    public function buildHashedPath($name, $hash = 'latest')
128
    {
129
        return $this->buildPath('p', $name, $hash . '.json');
130
    }
131
132
    protected function writeProviderLatest($name, $hash)
133
    {
134
        $latest_path = $this->buildHashedPath('provider-latest');
135
        if (file_exists($latest_path)) {
136
            $data = Json::decode(file_get_contents($latest_path) ?: '[]');
137
        }
138
        if (!isset($data) || !is_array($data)) {
139
            $data = [];
140
        }
141
        if (!isset($data['providers'])) {
142
            $data['providers'] = [];
143
        }
144
        $data['providers'][$name] = ['sha256' => $hash];
145
        $json = Json::encode($data);
146
        $hash = hash('sha256', $json);
147
        $path = $this->buildHashedPath('provider-latest', $hash);
148 View Code Duplication
        if (!file_exists($path)) {
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...
149
            $this->getLocker()->lock();
150
            {
151
                static::mkdir(dirname($path));
152
                file_put_contents($path, $json);
153
                file_put_contents($latest_path, $json);
154
                $this->writePackagesJson($hash);
155
            }
156
            $this->getLocker()->release();
157
        }
158
159
        return $hash;
160
    }
161
162
    protected function writePackagesJson($hash)
163
    {
164
        $data = [
165
            'providers-url'     => '/p/%package%/%hash%.json',
166
            'provider-includes' => [
167
                'p/provider-latest/%hash%.json' => [
168
                    'sha256' => $hash,
169
                ],
170
            ],
171
        ];
172
        $this->getLocker()->lock();
173
        {
174
            file_put_contents($this->buildPath('packages.json'), Json::encode($data));
175
        }
176
        $this->getLocker()->release();
177
    }
178
179
    public static function mkdir($dir)
180
    {
181
        if (!file_exists($dir)) {
182
            mkdir($dir, 0777, true);
183
        }
184
    }
185
186
    public function readJson($path)
187
    {
188
        return Json::decode(file_get_contents($this->buildPath($path)));
189
    }
190
191
    protected function readPackagesJson()
192
    {
193
        $data = $this->readJson('packages.json');
194
195
        return $data['provider-includes'];
196
    }
197
198
    protected function readProvider($path)
199
    {
200
        $data = $this->readJson($path);
201
202
        return $data['providers'];
203
    }
204
205
    public function listPackages()
206
    {
207
        $packages = [];
208
        $providers = $this->readPackagesJson();
209
        foreach ($providers as $path => $data) {
210
            $path = strtr($path, ['%hash%' => $data['sha256']]);
211
            $packages = array_merge($packages, $this->readProvider($path));
212
        }
213
214
        return $packages;
215
    }
216
}
217