Completed
Push — master ( 5c01aa...2b4547 )
by Hiraku
9s
created

Prefetcher::getUrlFromPackage()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4.0218

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 8
cts 9
cp 0.8889
rs 9.2
c 0
b 0
f 0
cc 4
eloc 9
nc 5
nop 1
crap 4.0218
1
<?php
2
/*
3
 * hirak/prestissimo
4
 * @author Hiraku NAKANO
5
 * @license MIT https://github.com/hirak/prestissimo
6
 */
7
namespace Hirak\Prestissimo;
8
9
use Composer\IO;
10
use Composer\Config;
11
use Composer\Package;
12
use Composer\DependencyResolver\Operation;
13
14
class Prefetcher
15
{
16
    /**
17
     * @param IO\IOInterface $io
18
     * @param CopyRequest[] $requests
19
     */
20 2
    public function fetchAll(IO\IOInterface $io, array $requests)
21
    {
22 2
        $successCnt = $failureCnt = 0;
23 2
        $totalCnt = count($requests);
24
25 2
        $multi = new CurlMulti;
26 2
        $multi->setRequests($requests);
27
        try {
28
            do {
29 2
                $multi->setupEventLoop();
30 2
                $multi->wait();
31
32 2
                $result = $multi->getFinishedResults();
33 2
                $successCnt += $result['successCnt'];
34 2
                $failureCnt += $result['failureCnt'];
35 2
                foreach ($result['urls'] as $url) {
36 1
                    if (isset($result['errors'][$url])) {
37
                        $io->writeError("    <warning>{$result['errors'][$url]}</warning>:\t$url", true, IO\IOInterface::NORMAL);
38
                    } else {
39 1
                        $io->writeError("    <comment>$successCnt/$totalCnt</comment>:\t$url", true, IO\IOInterface::NORMAL);
40
                    }
41
                }
42 2
            } while ($multi->remain());
43
        } catch (FetchException $e) {
44
            // do nothing
45
        }
46
47 2
        $skippedCnt = $totalCnt - $successCnt - $failureCnt;
48 2
        $io->writeError("    Finished: <comment>success: $successCnt, skipped: $skippedCnt, failure: $failureCnt, total: $totalCnt</comment>", true, IO\IOInterface::NORMAL);
49 2
    }
50
51
    /**
52
     * @param IO\IOInterface $io
53
     * @param Config $config
54
     * @param Operation\OperationInterface[] $ops
55
     */
56 4
    public function fetchAllFromOperations(IO\IOInterface $io, Config $config, array $ops)
57
    {
58 4
        $cachedir = rtrim($config->get('cache-files-dir'), '\/');
59 4
        $requests = array();
60 4
        foreach ($ops as $op) {
61 4
            switch ($op->getJobType()) {
62 4
                case 'install':
63 3
                    $p = $op->getPackage();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Composer\DependencyResol...tion\OperationInterface as the method getPackage() does only exist in the following implementations of said interface: Composer\DependencyResol...ration\InstallOperation, Composer\DependencyResol...AliasInstalledOperation, Composer\DependencyResol...iasUninstalledOperation, Composer\DependencyResol...tion\UninstallOperation.

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...
64 3
                    break;
65 2
                case 'update':
66 1
                    $p = $op->getTargetPackage();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Composer\DependencyResol...tion\OperationInterface as the method getTargetPackage() does only exist in the following implementations of said interface: Composer\DependencyResol...eration\UpdateOperation.

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...
67 1
                    break;
68
                default:
69 1
                    continue 2;
70
            }
71
72 3
            $url = $this->getUrlFromPackage($p);
73 3
            if (!$url) {
74 2
                continue;
75
            }
76
77 1
            $destination = $cachedir . DIRECTORY_SEPARATOR . FileDownloaderDummy::getCacheKeyCompat($p, $url);
78 1
            if (file_exists($destination)) {
79 1
                continue;
80
            }
81
            $useRedirector = (bool)preg_match('%^(?:https|git)://github\.com%', $p->getSourceUrl());
82
            try {
83
                $request = new CopyRequest($url, $destination, $useRedirector, $io, $config);
84
                $requests[] = $request;
85
            } catch (FetchException $e) {
86
                // do nothing
87
            }
88
        }
89
90 4
        if (count($requests) > 0) {
91
            $this->fetchAll($io, $requests);
92
        }
93 4
    }
94
95 3
    private static function getUrlFromPackage(Package\PackageInterface $package)
96
    {
97 3
        $url = $package->getDistUrl();
98 3
        if (!$url) {
99 1
            return false;
100
        }
101 2
        if ($package->getDistMirrors()) {
102
            $url = current($package->getDistUrls());
103
        }
104 2
        if (!parse_url($url, PHP_URL_HOST)) {
105 1
            return false;
106
        }
107 1
        return $url;
108
    }
109
}
110