Completed
Push — master ( 052b79...9b7d7f )
by Dmitry
08:01
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 3
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
     * @param string $full package name
106
     * @return static
107
     */
108
    public static function fromFullName($full)
109
    {
110
        list($type, $name) = static::splitFullName($full);
111
        return new static($type, $name);
112
    }
113
114
    public function getType()
115
    {
116
        return $this->_type;
117
    }
118
119
    public function getNormalName()
120
    {
121
        return static::buildNormalName($this->_type, $this->_name);
122
    }
123
124
    public function getName()
125
    {
126
        return $this->_name;
127
    }
128
129
    public function getHash()
130
    {
131
        return $this->_hash;
132
    }
133
134
    /**
135
     * findOne.
136
     *
137
     * @param string $type
138
     * @param string $name
139
     * @return static|null
140
     */
141
    public static function findOne($type, $name)
142
    {
143
        $package = new static($type, $name);
144
        $package->load();
145
146
        return $package;
147
    }
148
149
    public function load()
150
    {
151
        $data = $this->getStorage()->readPackage($this);
152
        if ($data !== null) {
153
            $this->_hash = $data['hash'];
154
            $this->_releases = $data['releases'];
155
            $this->_updateTime = $data['updateTime'];
156
        }
157
    }
158
159
    public function update()
160
    {
161
        $pool = $this->getRegistry()->getPool();
162
        $this->_releases = $this->prepareReleases($pool);
163
        $this->getStorage()->writePackage($this);
164
        $this->load();
165
    }
166
167
    /**
168
     * @param \Composer\DependencyResolver\Pool $pool
169
     * @return array
170
     */
171
    public function prepareReleases($pool)
172
    {
173
        $releases = [];
174
175
        foreach ($pool->whatProvides($this->getFullName()) as $package) {
176
            if ($package instanceof \Composer\Package\AliasPackage) {
177
                continue;
178
            }
179
180
            $version = $package->getPrettyVersion();
181
            $require = $this->prepareRequire($package->getRequires());
182
            $release = [
183
                'uid' => $this->prepareUid($version),
184
                'name' => $this->getNormalName(),
185
                'version' => $version,
186
                'version_normalized' => $package->getVersion(),
187
                'type' => $this->getType() . '-asset',
188
            ];
189
            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...
190
                $release['require'] = $require;
191
            }
192
            if ($package->getDistUrl()) {
193
                $release['dist'] = [
194
                    'type' => $package->getDistType(),
195
                    'url' => $package->getDistUrl(),
196
                    'reference' => $package->getDistReference(),
197
                ];
198
            }
199
            if ($package->getLicense()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Composer\Package\PackageInterface as the method getLicense() does only exist in the following implementations of said interface: Composer\Package\AliasPackage, Composer\Package\CompletePackage, Composer\Package\RootAliasPackage, Composer\Package\RootPackage, Fxp\Composer\AssetPlugin...ractLazyCompletePackage, Fxp\Composer\AssetPlugin...age\LazyCompletePackage.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
200
                $release['license'] = $package->getLicense();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Composer\Package\PackageInterface as the method getLicense() does only exist in the following implementations of said interface: Composer\Package\AliasPackage, Composer\Package\CompletePackage, Composer\Package\RootAliasPackage, Composer\Package\RootPackage, Fxp\Composer\AssetPlugin...ractLazyCompletePackage, Fxp\Composer\AssetPlugin...age\LazyCompletePackage.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

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