Completed
Push — master ( 38e5b4...f4dc2f )
by Andrii
15s
created

AssetPackage::prepareReleases()   C

Complexity

Conditions 11
Paths 34

Size

Total Lines 48
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 132

Importance

Changes 0
Metric Value
dl 0
loc 48
ccs 0
cts 36
cp 0
rs 5.2653
c 0
b 0
f 0
cc 11
eloc 31
nc 34
nop 1
crap 132

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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