Completed
Pull Request — master (#348)
by Victor
04:50
created

DetectCommand::execute()   C

Complexity

Conditions 12
Paths 62

Size

Total Lines 82
Code Lines 56

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 156

Importance

Changes 6
Bugs 1 Features 0
Metric Value
c 6
b 1
f 0
dl 0
loc 82
ccs 0
cts 69
cp 0
rs 5.034
cc 12
eloc 56
nc 62
nop 2
crap 156

How to fix   Long Method    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
 * @author Victor Dubiniuk <[email protected]>
4
 *
5
 * @copyright Copyright (c) 2015, ownCloud, Inc.
6
 * @license AGPL-3.0
7
 *
8
 * This code is free software: you can redistribute it and/or modify
9
 * it under the terms of the GNU Affero General Public License, version 3,
10
 * as published by the Free Software Foundation.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
 * GNU Affero General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Affero General Public License, version 3,
18
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
19
 *
20
 */
21
22
namespace Owncloud\Updater\Command;
23
24
use Symfony\Component\Console\Input\InputInterface;
25
use Symfony\Component\Console\Input\InputOption;
26
use Symfony\Component\Console\Output\OutputInterface;
27
use Symfony\Component\Console\Question\ChoiceQuestion;
28
use GuzzleHttp\Event\ProgressEvent;
29
use GuzzleHttp\Exception\ClientException;
30
use Owncloud\Updater\Utils\Fetcher;
31
use Owncloud\Updater\Utils\ConfigReader;
32
use \Owncloud\Updater\Controller\DownloadController;
33
34
class DetectCommand extends Command {
35
36
	/**
37
	 * @var Fetcher $fetcher
38
	 */
39
	protected $fetcher;
40
41
	/**
42
	 * @var ConfigReader $configReader
43
	 */
44
	protected $configReader;
45
46
	/**
47
	 *
48
	 */
49
	protected $output;
50
51
	/**
52
	 * Constructor
53
	 *
54
	 * @param Fetcher $fetcher
55
	 * @param ConfigReader $configReader
56
	 */
57
	public function __construct(Fetcher $fetcher, ConfigReader $configReader){
58
		parent::__construct();
59
		$this->fetcher = $fetcher;
60
		$this->configReader = $configReader;
61
	}
62
63
	protected function configure(){
64
		$this
65
				->setName('upgrade:detect')
66
				->setDescription('Detect
67
- 1. currently existing code, 
68
- 2. version in config.php, 
69
- 3. online available verison.
70
(ASK) what to do? (download, upgrade, abort, …)')
71
				->addOption(
72
						'exit-if-none', null, InputOption::VALUE_NONE, 'exit with non-zero status code if new version is not found'
73
				)
74
				->addOption(
75
						'only-check', null, InputOption::VALUE_NONE, 'Only check if update is available'
76
				)
77
		;
78
		;
79
	}
80
81
	protected function execute(InputInterface $input, OutputInterface $output){
82
		$registry = $this->container['utils.registry'];
83
		$registry->set('feed', false);
84
85
		$fsHelper = $this->container['utils.filesystemhelper'];
86
		$downloadController = new DownloadController($this->fetcher, $registry, $fsHelper);
87
		try {
88
			$currentVersion = $this->configReader->getByPath('system.version');
89
			if (!strlen($currentVersion)){
90
				throw new \UnexpectedValueException('Could not detect installed version.');
91
			}
92
93
			$this->getApplication()->getLogger()->info('ownCloud ' . $currentVersion . ' found');
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Symfony\Component\Console\Application as the method getLogger() does only exist in the following sub-classes of Symfony\Component\Console\Application: Owncloud\Updater\Console\Application. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
94
			$output->writeln('Current version is ' . $currentVersion);
95
96
			$feedData = $downloadController->checkFeed();
97
			if (!$feedData['success']){
98
				// Network errors, etc
99
				$output->writeln("Can't fetch feed.");
100
				$output->writeln($feedData['exception']->getMessage());
101
				$this->getApplication()->logException($feedData['exception']);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Symfony\Component\Console\Application as the method logException() does only exist in the following sub-classes of Symfony\Component\Console\Application: Owncloud\Updater\Console\Application. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
102
				// Return a number to stop the queue
103
				return $input->getOption('exit-if-none') ? 4 : null;
104
			}
105
106
			$feed = $feedData['data']['feed'];
107
			if (!$feed->isValid()){
108
				// Feed is empty. Means there are no updates
109
				$output->writeln('No updates found online.');
110
				return $input->getOption('exit-if-none') ? 4 : null;
111
			}
112
113
			$registry->set('feed', $feed);
114
			$output->writeln(
115
				sprintf(
116
					'Online version is %s [%s]',
117
					$feed->getVersion(),
118
					$this->fetcher->getUpdateChannel()
119
				)
120
			);
121
122
			if ($input->getOption('only-check')){
123
				return;
124
			}
125
126
			$action = $this->ask($input, $output);
127
			if ($action === 'abort'){
128
				$output->writeln('Exiting on user command.');
129
				return 128;
130
			}
131
132
			$this->output = $output;
133
			$packageData = $downloadController->downloadOwncloud([$this, 'progress']);
134
			//Empty line, in order not to overwrite the progress message
135
			$this->output->writeln('');
136
			if (!$packageData['success']){
137
				$registry->set('feed', null);
138
				throw $packageData['exception'];
139
			}
140
	
141
			if ($action === 'download'){
142
				$output->writeln('Downloading has been completed. Exiting.');
143
				return 64;
144
			}
145
		} catch (\GuzzleHttp\Exception\ClientException $e){
146
			$this->getApplication()->getLogger()->error($e->getMessage());
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Symfony\Component\Console\Application as the method getLogger() does only exist in the following sub-classes of Symfony\Component\Console\Application: Owncloud\Updater\Console\Application. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
147
			$output->writeln('<error>Network error</error>');
148
			$output->writeln(
149
					sprintf(
150
							'<error>Error %d: %s while fetching an URL %s</error>',
151
							$e->getCode(),
152
							$e->getResponse()->getReasonPhrase(),
153
							$e->getResponse()->getEffectiveUrl()
154
							)
155
			);
156
			return 2;
157
		} catch (\Exception $e){
158
			$this->getApplication()->getLogger()->error($e->getMessage());
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Symfony\Component\Console\Application as the method getLogger() does only exist in the following sub-classes of Symfony\Component\Console\Application: Owncloud\Updater\Console\Application. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
159
			$output->writeln('<error>'.$e->getMessage().'</error>');
160
			return 2;
161
		}
162
	}
163
164
	/**
165
	 * Ask what to do
166
	 * @param InputInterface $input
167
	 * @param OutputInterface $output
168
	 * @return string
169
	 */
170
	public function ask(InputInterface $input, OutputInterface $output){
171
		$helper = $this->getHelper('question');
172
		$question = new ChoiceQuestion(
173
			'What would you do next?',
174
			['download', 'upgrade', 'abort'],
175
			'1'
176
		);
177
		$action = $helper->ask($input, $output, $question);
178
179
		return $action;
180
	}
181
182
	/**
183
	 * Callback to output download progress
184
	 * @param ProgressEvent $e
185
	 */
186
	public function progress(ProgressEvent $e){
187
		if ($e->downloadSize){
188
			$percent = intval(100 * $e->downloaded / $e->downloadSize );
189
			$percentString = $percent . '%';
190
			$this->output->write( 'Downloaded ' . $percentString . ' (' . $e->downloaded . ' of ' . $e->downloadSize . ")\r");
191
		}
192
	}
193
}
194