Completed
Push — master ( 2ec9f0...d428ee )
by Andrii
30:10 queued 22:08
created

AssetPackage::getCommonComposer()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 13
c 0
b 0
f 0
ccs 0
cts 10
cp 0
rs 9.4285
cc 2
eloc 8
nc 2
nop 0
crap 6
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 Yii;
18
use yii\base\Object;
19
20
class AssetPackage extends Object
21
{
22
    protected $_type;
23
    protected $_name;
24
    protected $_hash;
25
    /**
26
     * @var array
27
     */
28
    protected $_releases = [];
29
    protected $_saved;
30
31
    /**
32
     * @var integer UNIX Epoch timestamp of the latest package update
33
     */
34
    protected $_updateTime;
35
36
    public static function normalizeName($name)
37
    {
38
        return strtolower($name);
39
    }
40
41
    /**
42
     * AssetPackage constructor.
43
     * @param string $type
44
     * @param string $name
45
     * @param array $config
46
     * @throws Exception
47
     */
48
    public function __construct($type, $name, $config = [])
49
    {
50
        parent::__construct($config);
51
52
        if (!$this->checkType($type)) {
53
            throw new Exception('wrong type');
54
        }
55
        if (!$this->checkName($name)) {
56
            throw new Exception('wrong name');
57
        }
58
        $this->_type = $type;
59
        $this->_name = $name;
60
    }
61
62
    /**
63
     * @return RegistryFactory
64
     */
65
    public function getRegistry()
66
    {
67
        return Yii::$app->get('registryFactory');
68
    }
69
70
    public function checkType($type)
71 1
    {
72
        return $type === 'bower' || $type === 'npm';
73 1
    }
74
75 1
    public function checkName($name)
76
    {
77
        return strlen($name) > 0;
78 1
    }
79
80
    public function getFullName()
81 1
    {
82 1
        return static::buildFullName($this->_type, $this->_name);
83 1
    }
84
85
    public static function buildFullName($type, $name)
86
    {
87
        return $type . '-asset/' . $name;
88
    }
89
90
    public static function splitFullName($full)
91
    {
92
        list($temp, $name) = explode('/', $full);
93
        list($type) = explode('-', $temp);
94 1
95
        return [$type, $name];
96 1
    }
97
98
    /**
99 1
     * @param string $full package name
100
     * @return static
101 1
     */
102
    public static function fromFullName($full)
103
    {
104 1
        list($type, $name) = static::splitFullName($full);
105
        return new static($type, $name);
106 1
    }
107
108
    public function getType()
109 1
    {
110
        return $this->_type;
111 1
    }
112
113
    public function getNormalName()
114
    {
115
        return static::buildFullName($this->_type, static::normalizeName($this->_name));
116
    }
117
118
    public function getName()
119
    {
120
        return $this->_name;
121
    }
122
123
    public function getHash()
124
    {
125
        return $this->_hash;
126
    }
127
128
    /**
129
     * findOne.
130
     *
131
     * @param string $type
132
     * @param string $name
133
     * @return static|null
134
     */
135
    public static function findOne($type, $name)
136
    {
137
        $package = new static($type, $name);
138
        $package->load();
139
140
        return $package;
141
    }
142
143
    public function load()
144
    {
145
        $data = $this->getStorage()->readPackage($this);
146
        if ($data !== null) {
147
            $this->_hash = $data['hash'];
148
            $this->_releases = $data['releases'];
149
            $this->_updateTime = $data['updateTime'];
150
        }
151
    }
152
153
    public function update()
154
    {
155
        $pool = $this->getRegistry()->getPool();
156
        $this->_releases = $this->prepareReleases($pool);
157
        $this->getStorage()->writePackage($this);
158
        $this->load();
159
    }
160
161
    /**
162
     * @param \Composer\DependencyResolver\Pool $pool
163
     * @return array
164
     */
165
    public function prepareReleases($pool)
166
    {
167
        $releases = [];
168
169
        foreach ($pool->whatProvides($this->getFullName()) as $package) {
170
            if ($package instanceof \Composer\Package\AliasPackage) {
171
                continue;
172
            }
173
174
            $version = $package->getPrettyVersion();
175
            $require = $this->prepareRequire($package->getRequires());
176
            $release = [
177
                'uid' => $this->prepareUid($version),
178
                'name' => $this->getNormalName(),
179
                'version' => $version,
180
                'version_normalized' => $package->getVersion(),
181
                'type' => $this->getType() . '-asset',
182
            ];
183
            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...
184
                $release['require'] = $require;
185
            }
186
            if ($package->getDistUrl()) {
187
                $release['dist'] = [
188
                    'type' => $package->getDistType(),
189
                    'url' => $package->getDistUrl(),
190
                    'reference' => $package->getDistReference(),
191
                ];
192
            }
193
            if ($package->getSourceUrl()) {
194
                $release['source'] = [
195
                    'type' => $package->getSourceType(),
196
                    'url' => $package->getSourceUrl(),
197
                    'reference' => $package->getSourceReference(),
198
                ];
199
            }
200
            if ((isset($release['dist']) && $release['dist']) || (isset($release['source']) && $release['source'])) {
201
                $releases[$version] = $release;
202
            }
203
        }
204
205
        //Sort before save
206
        \hiqdev\assetpackagist\components\PackageUtil::sort($releases);
207
208
        return $releases;
209
    }
210
211
    /**
212
     * Prepares array of requires: name => constraint.
213
     * @param Link[] array of package requires
214
     * @return array
215
     */
216
    public function prepareRequire(array $links)
217
    {
218
        $requires = [];
219
        foreach ($links as $name => $link) {
220
            /** @var Link $link */
221
            $requires[$name] = $link->getPrettyConstraint();
222
        }
223
224
        return $requires;
225
    }
226
227
    public function prepareUid($version)
228
    {
229
        $known = $this->getSaved()->getRelease($version);
230
231
        return isset($known['uid']) ? $known['uid'] : $this->getStorage()->getNextId();
232
    }
233
234
    /**
235
     * @return array
236
     */
237
    public function getReleases()
238
    {
239
        return $this->_releases;
240
    }
241
242
    /**
243
     * @param $version
244
     * @return array
245
     */
246
    public function getRelease($version)
247
    {
248
        return isset($this->_releases[$version]) ? $this->_releases[$version] : [];
249
    }
250
251
    public function getSaved()
252
    {
253
        if ($this->_saved === null) {
254
            $this->_saved = static::findOne($this->getType(), $this->getName());
255
        }
256
257
        return $this->_saved;
258
    }
259
260
    /**
261
     * @return Storage
262
     */
263
    public function getStorage()
264
    {
265
        return Yii::$app->get('packageStorage');
266
    }
267
268
    /**
269
     * Returns the latest update time (UNIX Epoch).
270
     * @return int|null
271
     */
272
    public function getUpdateTime()
273
    {
274
        return $this->_updateTime;
275
    }
276
277
    /**
278
     * Package can be updated not more often than once in 10 min.
279
     * @return bool
280
     */
281
    public function canBeUpdated()
282
    {
283
        return time() - $this->getUpdateTime() > 60 * 10; // 10 min
284
    }
285
286
    /**
287
     * Whether tha package should be auth-updated (if it is older than 1 day).
288
     * @return bool
289
     */
290
    public function canAutoUpdate()
291
    {
292
        return time() - $this->getUpdateTime() > 60 * 60 * 24; // 1 day
293
    }
294
295
    /**
296
     * @return array
297
     */
298
    public function __sleep()
299
    {
300
        return ['_type', '_name', '_hash'];
301
    }
302
}
303