Completed
Push — master ( cf2d54...6e59f3 )
by Andrii
05:31
created

Storage::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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