Completed
Push — master ( f10575...593920 )
by Andrii
03:26
created

Storage::getNextID()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 11
ccs 0
cts 6
cp 0
rs 9.4285
cc 1
eloc 6
nc 1
nop 0
crap 2
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\models\AssetPackage;
15
use Yii;
16
use yii\base\Component;
17
use yii\helpers\Json;
18
use hiqdev\assetpackagist\helpers\Locker;
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 [];
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 (!is_array($data)) {
0 ignored issues
show
Bug introduced by
The variable $data does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
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