Completed
Pull Request — master (#615)
by
unknown
03:19
created

SelfUpdateCommand::getLatestReleaseFromGithub()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 25
rs 8.8571
c 1
b 0
f 0
cc 2
eloc 14
nc 2
nop 0
1
<?php
2
3
/*
4
 * This file is part of the Symfony package.
5
 *
6
 * (c) Fabien Potencier <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Robo;
13
14
use Symfony\Component\Console\Command\Command;
15
use Symfony\Component\Console\Input\InputInterface;
16
use Symfony\Component\Console\Output\OutputInterface;
17
use Symfony\Component\Filesystem\Filesystem as sfFilesystem;
18
19
/**
20
 * Update the robo.phar from the latest github release
21
 *
22
 * @author Alexander Menk <[email protected]>
23
 */
24
class SelfUpdateCommand extends Command
25
{
26
    private $command;
0 ignored issues
show
Unused Code introduced by
The property $command is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
27
28
    protected $gitHubRepository;
29
30
    protected $currentVersion;
31
32
    public function __construct( $name = null, $currentVersion = null, $gitHubRepository = null) {
33
        parent::__construct( $name );
34
        $this->currentVersion = $currentVersion;
35
        $this->gitHubRepository = $gitHubRepository;
36
    }
37
38
39
    /**
40
     * {@inheritdoc}
41
     */
42
    protected function configure()
43
    {
44
        $this
45
            ->setName('self-update')
46
            ->setAliases(array( 'selfupdate' ))
47
            ->setDescription('Updates the robo.phar to the latest version.')
48
            ->setHelp(
49
                <<<EOT
50
The <info>self-update</info> command checks github for newer
51
versions of robo and if found, installs the latest.
52
EOT
53
            );
54
    }
55
56
    protected function getLatestReleaseFromGithub()
57
    {
58
        $opts = [
59
            'http' => [
60
                'method' => 'GET',
61
                'header' => [
62
                    'User-Agent: ' . Robo::APPLICATION_NAME . ' Self-Update (PHP)'
63
                ]
64
            ]
65
        ];
66
67
        $context = stream_context_create($opts);
68
69
        $releases = file_get_contents('https://api.github.com/repos/' . $this->gitHubRepository . '/releases', false, $context);
70
        $releases = json_decode($releases);
71
72
        if (! isset($releases[0])) {
73
            throw new \Exception('API error - no release found at GitHub repository ' . $this->gitHubRepository);
74
        }
75
76
        $version = $releases[0]->tag_name;
77
        $url     = $releases[0]->assets[0]->browser_download_url;
78
79
        return [ $version, $url ];
80
    }
81
82
    /**
83
     * {@inheritdoc}
84
     */
85
    protected function execute(InputInterface $input, OutputInterface $output)
0 ignored issues
show
Coding Style introduced by
execute uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
86
    {
87
        $localFilename = realpath($_SERVER['argv'][0]) ?: $_SERVER['argv'][0];
88
        $programName   = basename($localFilename);
89
        $tempFilename  = dirname($localFilename) . '/' . basename($localFilename, '.phar') . '-temp.phar';
90
91
        // check for permissions in local filesystem before start connection process
92
        if (! is_writable($tempDirectory = dirname($tempFilename))) {
93
            throw new \Exception(
94
                $programName . ' update failed: the "' . $tempDirectory .
95
                '" directory used to download the temp file could not be written'
96
            );
97
        }
98
99
        if (! is_writable($localFilename)) {
100
            throw new \Exception(
101
                $programName . ' update failed: the "' . $localFilename . '" file could not be written'
102
            );
103
        }
104
105
        list( $latest, $downloadUrl ) = $this->getLatestReleaseFromGithub();
106
107
108
        if ($this->currentVersion == $latest) {
109
            $output->writeln('No update available');
110
            return;
111
        }
112
113
        $fs = new sfFilesystem();
114
115
        $output->writeln('Downloading ' . Robo::APPLICATION_NAME . ' ' . $latest);
116
117
        $fs->copy($downloadUrl, $tempFilename);
118
119
        $output->writeln('Download finished');
120
121
        try {
122
            \error_reporting(E_ALL); // supress notices
123
124
            @chmod($tempFilename, 0777 & ~umask());
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
125
            // test the phar validity
126
            $phar = new \Phar($tempFilename);
127
            // free the variable to unlock the file
128
            unset($phar);
129
            @rename($tempFilename, $localFilename);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
130
            $output->writeln('<info>Successfully updated ' . $programName . '</info>');
131
            $this->_exit();
132
        } catch (\Exception $e) {
133
            @unlink($tempFilename);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
134
            if (! $e instanceof \UnexpectedValueException && ! $e instanceof \PharException) {
135
                throw $e;
136
            }
137
            $output->writeln('<error>The download is corrupted (' . $e->getMessage() . ').</error>');
138
            $output->writeln('<error>Please re-run the self-update command to try again.</error>');
139
        }
140
    }
141
142
    /**
143
     * Stop execution
144
     *
145
     * This is a workaround to prevent warning of dispatcher after replacing
146
     * the phar file.
147
     *
148
     * @return void
149
     */
150
    protected function _exit()
151
    {
152
        exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method _exit() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
153
    }
154
}
155