Completed
Push — master ( d428ee...8ea9f6 )
by Andrii
02:16
created

AssetPackage::isAvailable()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
ccs 0
cts 2
cp 0
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
crap 2
1
<?php
2
/**
3
 * Asset Packagist.
4
 *
5
 * @link      https://github.com/hiqdev/asset-packagist
6
 * @package   asset-packagist
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2016-2017, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hiqdev\assetpackagist\models;
12
13
use Composer\Package\Link;
14
use Exception;
15
use hiqdev\assetpackagist\components\Storage;
16
use hiqdev\assetpackagist\registry\RegistryFactory;
17
use hiqdev\assetpackagist\repositories\PackageRepository;
18
use Yii;
19
use yii\base\Object;
20
21
class AssetPackage extends Object
22
{
23
    protected $_type;
24
    protected $_name;
25
    protected $_hash;
26
    /**
27
     * @var array
28
     */
29
    protected $_releases = [];
30
    protected $_saved;
31
32
    /**
33
     * @var integer UNIX Epoch timestamp of the latest package update
34
     */
35
    protected $_updateTime;
36
37
    public static function normalizeName($name)
38
    {
39
        return strtolower($name);
40
    }
41
42
    /**
43
     * AssetPackage constructor.
44
     * @param string $type
45
     * @param string $name
46
     * @param array $config
47
     * @throws Exception
48
     */
49 1
    public function __construct($type, $name, $config = [])
50
    {
51 1
        parent::__construct($config);
52
53 1
        if (!$this->checkType($type)) {
54
            throw new Exception('wrong type');
55
        }
56 1
        if (!$this->checkName($name)) {
57
            throw new Exception('wrong name');
58
        }
59 1
        $this->_type = $type;
60 1
        $this->_name = $name;
61 1
    }
62
63
    /**
64
     * @return RegistryFactory
65
     */
66
    public function getRegistry()
67
    {
68
        return Yii::$app->get('registryFactory');
69
    }
70
71 1
    public function checkType($type)
72
    {
73 1
        return $type === 'bower' || $type === 'npm';
74
    }
75
76 1
    public function checkName($name)
77
    {
78 1
        return strlen($name) > 0;
79
    }
80
81 1
    public function getFullName()
82
    {
83 1
        return static::buildFullName($this->_type, $this->_name);
84
    }
85
86
    public static function buildNormalName($type, $name)
87
    {
88
        return static::buildFullName($type, static::normalizeName($name));
89
    }
90
91 1
    public static function buildFullName($type, $name)
92
    {
93 1
        return $type . '-asset/' . $name;
94
    }
95
96
    public static function splitFullName($full)
97
    {
98
        list($temp, $name) = explode('/', $full);
99
        list($type) = explode('-', $temp);
100
101
        return [$type, $name];
102
    }
103
104
105
    /**
106
     * @param string $full package name
107
     * @return static
108
     */
109
    public static function fromFullName($full)
110
    {
111
        list($type, $name) = static::splitFullName($full);
112
        return new static($type, $name);
113
    }
114
115
    public function getType()
116
    {
117
        return $this->_type;
118
    }
119
120
    public function getNormalName()
121
    {
122
        return static::buildNormalName($this->_type, $this->_name);
123
    }
124
125
    public function getName()
126
    {
127
        return $this->_name;
128
    }
129
130
    public function getHash()
131
    {
132
        return $this->_hash;
133
    }
134
135
    /**
136
     * findOne.
137
     *
138
     * @param string $type
139
     * @param string $name
140
     * @return static|null
141
     */
142
    public static function findOne($type, $name)
143
    {
144
        $package = new static($type, $name);
145
        $package->load();
146
147
        return $package;
148
    }
149
150
    public function load()
151
    {
152
        $data = $this->getStorage()->readPackage($this);
153
        if ($data !== null) {
154
            $this->_hash = $data['hash'];
155
            $this->_releases = $data['releases'];
156
            $this->_updateTime = $data['updateTime'];
157
        }
158
    }
159
160
    public function update()
161
    {
162
        $pool = $this->getRegistry()->getPool();
163
        $this->_releases = $this->prepareReleases($pool);
164
        $this->getStorage()->writePackage($this);
165
        $this->load();
166
    }
167
168
    /**
169
     * @param \Composer\DependencyResolver\Pool $pool
170
     * @return array
171
     */
172
    public function prepareReleases($pool)
173
    {
174
        $releases = [];
175
176
        foreach ($pool->whatProvides($this->getFullName()) as $package) {
177
            if ($package instanceof \Composer\Package\AliasPackage) {
178
                continue;
179
            }
180
181
            $version = $package->getPrettyVersion();
182
            $require = $this->prepareRequire($package->getRequires());
183
            $release = [
184
                'uid' => $this->prepareUid($version),
185
                'name' => $this->getNormalName(),
186
                'version' => $version,
187
                'version_normalized' => $package->getVersion(),
188
                'type' => $this->getType() . '-asset',
189
            ];
190
            if ($require) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $require of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
191
                $release['require'] = $require;
192
            }
193
            if ($package->getDistUrl()) {
194
                $release['dist'] = [
195
                    'type' => $package->getDistType(),
196
                    'url' => $package->getDistUrl(),
197
                    'reference' => $package->getDistReference(),
198
                ];
199
            }
200
            if ($package->getSourceUrl()) {
201
                $release['source'] = [
202
                    'type' => $package->getSourceType(),
203
                    'url' => $package->getSourceUrl(),
204
                    'reference' => $package->getSourceReference(),
205
                ];
206
            }
207
            if ((isset($release['dist']) && $release['dist']) || (isset($release['source']) && $release['source'])) {
208
                $releases[$version] = $release;
209
            }
210
        }
211
212
        //Sort before save
213
        \hiqdev\assetpackagist\components\PackageUtil::sort($releases);
214
215
        return $releases;
216
    }
217
218
    /**
219
     * Prepares array of requires: name => constraint.
220
     * @param Link[] array of package requires
221
     * @return array
222
     */
223
    public function prepareRequire(array $links)
224
    {
225
        $requires = [];
226
        foreach ($links as $name => $link) {
227
            /** @var Link $link */
228
            $requires[$name] = $link->getPrettyConstraint();
229
        }
230
231
        return $requires;
232
    }
233
234
    public function prepareUid($version)
235
    {
236
        $known = $this->getSaved()->getRelease($version);
237
238
        return isset($known['uid']) ? $known['uid'] : $this->getStorage()->getNextId();
239
    }
240
241
    /**
242
     * @return array
243
     */
244
    public function getReleases()
245
    {
246
        return $this->_releases;
247
    }
248
249
    /**
250
     * @param $version
251
     * @return array
252
     */
253
    public function getRelease($version)
254
    {
255
        return isset($this->_releases[$version]) ? $this->_releases[$version] : [];
256
    }
257
258
    public function getSaved()
259
    {
260
        if ($this->_saved === null) {
261
            $this->_saved = static::findOne($this->getType(), $this->getName());
262
        }
263
264
        return $this->_saved;
265
    }
266
267
    /**
268
     * @return Storage
269
     */
270
    public function getStorage()
271
    {
272
        return Yii::$app->get('packageStorage');
273
    }
274
275
    /**
276
     * Returns the latest update time (UNIX Epoch).
277
     * @return int|null
278
     */
279
    public function getUpdateTime()
280
    {
281
        return $this->_updateTime;
282
    }
283
284
    /**
285
     * Package can be updated not more often than once in 10 min.
286
     * @return bool
287
     */
288
    public function canBeUpdated()
289
    {
290
        return time() - $this->getUpdateTime() > 60 * 10; // 10 min
291
    }
292
293
    /**
294
     * Whether tha package should be auth-updated (if it is older than 1 day).
295
     * @return bool
296
     */
297
    public function canAutoUpdate()
298
    {
299
        return time() - $this->getUpdateTime() > 60 * 60 * 24; // 1 day
300
    }
301
302
    public function isAvailable()
303
    {
304
        $repository = Yii::createObject(PackageRepository::class, []);
305
306
        return $repository->exists($this);
307
    }
308
309
    /**
310
     * @return array
311
     */
312
    public function __sleep()
313
    {
314
        return ['_type', '_name', '_hash'];
315
    }
316
}
317