Completed
Pull Request — master (#615)
by
unknown
02:51
created

SelfUpdateCommand::_exit()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
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
    /**
29
     * {@inheritdoc}
30
     */
31
    protected function configure()
32
    {
33
        $this
34
            ->setName('self-update')
35
            ->setAliases(array( 'selfupdate' ))
36
            ->setDescription('Updates the robo.phar to the latest version.')
37
            ->setHelp(
38
                <<<EOT
39
The <info>self-update</info> command checks github for newer
40
versions of robo and if found, installs the latest.
41
EOT
42
            );
43
    }
44
45
    protected function getLatestReleaseFromGithub($repository)
46
    {
47
        $opts = [
48
            'http' => [
49
                'method' => 'GET',
50
                'header' => [
51
                    'User-Agent: ' . Robo::APPLICATION_NAME . ' Self-Update (PHP)'
52
                ]
53
            ]
54
        ];
55
56
        $context = stream_context_create($opts);
57
58
        $releases = file_get_contents('https://api.github.com/repos/' . $repository . '/releases', false, $context);
59
        $releases = json_decode($releases);
60
61
        if (! isset($releases[0])) {
62
            throw new \Exception('API error - no release found at GitHub repository ' . $repository);
63
        }
64
65
        $version = $releases[0]->tag_name;
66
        $url     = $releases[0]->assets[0]->browser_download_url;
67
68
        return [ $version, $url ];
69
    }
70
71
    /**
72
     * {@inheritdoc}
73
     */
74
    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...
75
    {
76
        $localFilename = realpath($_SERVER['argv'][0]) ?: $_SERVER['argv'][0];
77
        $programName   = basename($localFilename);
78
        $tempFilename  = dirname($localFilename) . '/' . basename($localFilename, '.phar') . '-temp.phar';
79
80
        // check for permissions in local filesystem before start connection process
81
        if (! is_writable($tempDirectory = dirname($tempFilename))) {
82
            throw new \Exception(
83
                $programName . ' update failed: the "' . $tempDirectory .
84
                '" directory used to download the temp file could not be written'
85
            );
86
        }
87
88
        if (! is_writable($localFilename)) {
89
            throw new \Exception(
90
                $programName . ' update failed: the "' . $localFilename . '" file could not be written'
91
            );
92
        }
93
94
        list( $latest, $downloadUrl ) = $this->getLatestReleaseFromGithub('consolidation/robo');
95
96
97
        if (Robo::VERSION == $latest) {
98
            $output->writeln('No update available');
99
            return;
100
        }
101
102
        $fs = new sfFilesystem();
103
104
        $output->writeln('Downloading ' . Robo::APPLICATION_NAME . ' ' . $latest);
105
106
        $fs->copy($downloadUrl, $tempFilename);
107
108
        $output->writeln('Download finished');
109
110
        try {
111
            \error_reporting(E_ALL); // supress notices
112
113
            @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...
114
            // test the phar validity
115
            $phar = new \Phar($tempFilename);
116
            // free the variable to unlock the file
117
            unset($phar);
118
            @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...
119
            $output->writeln('<info>Successfully updated ' . $programName . '</info>');
120
            $this->_exit();
121
        } catch (\Exception $e) {
122
            @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...
123
            if (! $e instanceof \UnexpectedValueException && ! $e instanceof \PharException) {
124
                throw $e;
125
            }
126
            $output->writeln('<error>The download is corrupted (' . $e->getMessage() . ').</error>');
127
            $output->writeln('<error>Please re-run the self-update command to try again.</error>');
128
        }
129
    }
130
131
    /**
132
     * Stop execution
133
     *
134
     * This is a workaround to prevent warning of dispatcher after replacing
135
     * the phar file.
136
     *
137
     * @return void
138
     */
139
    protected function _exit()
140
    {
141
        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...
142
    }
143
}
144