Completed
Pull Request — master (#98)
by Hiraku
07:53 queued 05:39
created

Prefetcher::fetchAll()   B

Complexity

Conditions 4
Paths 13

Size

Total Lines 26
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 4.0032

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 26
ccs 16
cts 17
cp 0.9412
rs 8.5806
cc 4
eloc 18
nc 13
nop 2
crap 4.0032
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
                    $io->writeError("    <comment>$successCnt/$totalCnt</comment>:\t$url");
37
                }
38 2
            } while ($multi->remain());
39
        } catch (FetchException $e) {
40
            // do nothing
41
        }
42
43 2
        $skippedCnt = $totalCnt - $successCnt - $failureCnt;
44 2
        $io->writeError("    Finished: <comment>success: $successCnt, skipped: $skippedCnt, failure: $failureCnt, total: $totalCnt</comment>");
45 2
    }
46
47
    /**
48
     * @param IO\IOInterface $io
49
     * @param Config $config
50
     * @param Operation\OperationInterface[] $ops
51
     */
52 4
    public function fetchAllFromOperations(IO\IOInterface $io, Config $config, array $ops)
53
    {
54 4
        $cachedir = rtrim($config->get('cache-files-dir'), '\/');
55 4
        $requests = array();
56 4
        foreach ($ops as $op) {
57 4
            switch ($op->getJobType()) {
58 4
                case 'install':
59 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...
60 3
                    break;
61 2
                case 'update':
62 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...
63 1
                    break;
64
                default:
65 1
                    continue 2;
66
            }
67
68 3
            $url = $this->getUrlFromPackage($p);
69 3
            if (!$url) {
70 2
                continue;
71
            }
72
73 1
            $destination = $cachedir . DIRECTORY_SEPARATOR . FileDownloaderDummy::getCacheKeyCompat($p, $url);
74 1
            if (file_exists($destination)) {
75 1
                continue;
76
            }
77
            $useRedirector = (bool)preg_match('%^(?:https|git)://github\.com%', $p->getSourceUrl());
78
            try {
79
                $request = new CopyRequest($url, $destination, $useRedirector, $io, $config);
80
                $requests[] = $request;
81
            } catch (FetchException $e) {
82
                // do nothing
83
            }
84
        }
85
86 4
        if (count($requests) > 0) {
87
            $this->fetchAll($io, $requests);
88
        }
89 4
    }
90
91 3
    private static function getUrlFromPackage(Package\PackageInterface $package)
92
    {
93 3
        $url = $package->getDistUrl();
94 3
        if (!$url) {
95 1
            return false;
96
        }
97 2
        if ($package->getDistMirrors()) {
98
            $url = current($package->getDistUrls());
99
        }
100 2
        if (!parse_url($url, PHP_URL_HOST)) {
101 1
            return false;
102
        }
103 1
        return $url;
104
    }
105
}
106