Completed
Pull Request — master (#347)
by Victor
02:27
created

ExecuteCoreUpgradeScriptsCommand::execute()   D

Complexity

Conditions 11
Paths 223

Size

Total Lines 73
Code Lines 52

Duplication

Lines 4
Ratio 5.48 %

Code Coverage

Tests 0
CRAP Score 132

Importance

Changes 11
Bugs 2 Features 0
Metric Value
c 11
b 2
f 0
dl 4
loc 73
ccs 0
cts 63
cp 0
rs 4.6285
cc 11
eloc 52
nc 223
nop 2
crap 132

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
/**
4
 * @author Victor Dubiniuk <[email protected]>
5
 *
6
 * @copyright Copyright (c) 2015, ownCloud, Inc.
7
 * @license AGPL-3.0
8
 *
9
 * This code is free software: you can redistribute it and/or modify
10
 * it under the terms of the GNU Affero General Public License, version 3,
11
 * as published by the Free Software Foundation.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
 * GNU Affero General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Affero General Public License, version 3,
19
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
20
 *
21
 */
22
23
namespace Owncloud\Updater\Command;
24
25
use Owncloud\Updater\Utils\Checkpoint;
26
use Owncloud\Updater\Utils\FilesystemHelper;
27
use Symfony\Component\Console\Input\InputInterface;
28
use Symfony\Component\Console\Output\OutputInterface;
29
use Symfony\Component\Process\Exception\ProcessFailedException;
30
use Owncloud\Updater\Utils\OccRunner;
31
use Owncloud\Updater\Utils\ZipExtractor;
32
use Owncloud\Updater\Utils\BzipExtractor;
33
34
class ExecuteCoreUpgradeScriptsCommand extends Command {
35
36
	/**
37
	 * @var OccRunner $occRunner
38
	 */
39
	protected $occRunner;
40
41
	public function __construct($occRunner){
42
		parent::__construct();
43
		$this->occRunner = $occRunner;
44
	}
45
46
	protected function configure(){
47
		$this
48
				->setName('upgrade:executeCoreUpgradeScripts')
49
				->setDescription('execute core upgrade scripts [danger, might take long]');
50
	}
51
52
	protected function execute(InputInterface $input, OutputInterface $output){
53
		$locator = $this->container['utils.locator'];
54
		/** @var FilesystemHelper $fsHelper */
55
		$fsHelper = $this->container['utils.filesystemhelper'];
56
		$registry = $this->container['utils.registry'];
57
		$fetcher = $this->container['utils.fetcher'];
58
		/** @var Checkpoint $checkpoint */
59
		$checkpoint = $this->container['utils.checkpoint'];
60
61
		$installedVersion = implode('.', $locator->getInstalledVersion());
62
		$registry->set('installedVersion', $installedVersion);
63
		
64
		$feed = $registry->get('feed');
65
66
		if ($feed){
67
			$path = $fetcher->getBaseDownloadPath($feed);
68
			$fullExtractionPath = $locator->getExtractionBaseDir() . '/' . $feed->getVersion();
69
70
			if (file_exists($fullExtractionPath)){
71
				$fsHelper->removeIfExists($fullExtractionPath);
72
			}
73
			try{
74
				$fsHelper->mkdir($fullExtractionPath, true);
75
			} catch (\Exception $e){
76
					$output->writeln('Unable create directory ' . $fullExtractionPath);
77
					throw $e;
78
			}
79
80
			$output->writeln('Extracting source into ' . $fullExtractionPath);
81
			if (preg_match('|\.tar\.bz2$|', $path)){
82
				$extractor = new BzipExtractor($path, $fullExtractionPath);
83
			} else {
84
				$extractor = new ZipExtractor($path, $fullExtractionPath);
85
			}
86
			try{
87
				$extractor->extract();
88
			} catch (\Exception $e){
89
				$output->writeln('Extraction has been failed');
90
				$fsHelper->removeIfExists($locator->getExtractionBaseDir());
91
				throw $e;
92
			}
93
94
			$tmpDir = $locator->getExtractionBaseDir() . '/' . $installedVersion;
95
			$fsHelper->removeIfExists($tmpDir);
96
			$fsHelper->mkdir($tmpDir);
97
			$fsHelper->mkdir($tmpDir . '/config');
98
			$oldSourcesDir = $locator->getOwncloudRootPath();
99
			$newSourcesDir = $fullExtractionPath . '/owncloud';
100
101 View Code Duplication
			foreach ($locator->getRootDirContent() as $dir){
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
102
				$this->getApplication()->getLogger()->debug('Replacing ' . $dir);
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...
103
				$fsHelper->tripleMove($oldSourcesDir, $newSourcesDir, $tmpDir, $dir);
104
			}
105
			
106
			try {
107
				$appDirectories = $fsHelper->scandirFiltered($oldSourcesDir . '/apps');
108
				foreach ($appDirectories as $appDirectory){
109
					$fsHelper->rmdirr($oldSourcesDir . '/apps/' . $appDirectory);
110
				}
111
				$plain = $this->occRunner->run('upgrade');
112
				$output->writeln($plain);
113
			} catch (ProcessFailedException $e){
114
				$lastCheckpointId = $checkpoint->getLastCheckpointId();
115
				if ($lastCheckpointId){
116
					$lastCheckpointPath = $checkpoint->getCheckpointPath($lastCheckpointId);
0 ignored issues
show
Documentation introduced by
$lastCheckpointId is of type boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
117
					$fsHelper->copyr($lastCheckpointPath . '/apps', $oldSourcesDir . '/apps', false);
118
				}
119
				if ($e->getProcess()->getExitCode() != 3){
120
					throw ($e);
121
				}
122
			}
123
		}
124
	}
125
126
}
127