Completed
Push — master ( 524f68...5fad21 )
by Dmitry
02:35
created

Storage::readPackage()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 11

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 15
ccs 0
cts 11
cp 0
rs 9.4285
cc 3
eloc 11
nc 3
nop 1
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\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->getFullName();
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->getFullName();
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
            'search'            => '/search.json?q=%query%',
166
            'providers-url'     => '/p/%package%/%hash%.json',
167
            'provider-includes' => [
168
                'p/provider-latest/%hash%.json' => [
169
                    'sha256' => $hash,
170
                ],
171
            ],
172
        ];
173
        $this->getLocker()->lock();
174
        {
175
            file_put_contents($this->buildPath('packages.json'), Json::encode($data));
176
        }
177
        $this->getLocker()->release();
178
    }
179
180
    public static function mkdir($dir)
181
    {
182
        if (!file_exists($dir)) {
183
            mkdir($dir, 0777, true);
184
        }
185
    }
186
187
    public function readJson($path)
188
    {
189
        return Json::decode(file_get_contents($this->buildPath($path)));
190
    }
191
192
    protected function readPackagesJson()
193
    {
194
        $data = $this->readJson('packages.json');
195
196
        return $data['provider-includes'];
197
    }
198
199
    protected function readProvider($path)
200
    {
201
        $data = $this->readJson($path);
202
203
        return $data['providers'];
204
    }
205
206
    public function listPackages()
207
    {
208
        $packages = [];
209
        $providers = $this->readPackagesJson();
210
        foreach ($providers as $path => $data) {
211
            $path = strtr($path, ['%hash%' => $data['sha256']]);
212
            $packages = array_merge($packages, $this->readProvider($path));
213
        }
214
215
        return $packages;
216
    }
217
}
218