Completed
Push — master ( fa7735...d98913 )
by Andrii
03:39 queued 01:35
created

Storage::writePackage()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 24
Code Lines 16

Duplication

Lines 10
Ratio 41.67 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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