Completed
Pull Request — master (#355)
by Victor
03:12
created

ExecuteCoreUpgradeScriptsCommand   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 100
Duplicated Lines 4 %

Coupling/Cohesion

Components 1
Dependencies 9

Test Coverage

Coverage 0%

Importance

Changes 14
Bugs 3 Features 0
Metric Value
wmc 13
c 14
b 3
f 0
lcom 1
cbo 9
dl 4
loc 100
ccs 0
cts 74
cp 0
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A configure() 0 5 1
D execute() 4 81 11

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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
33
class ExecuteCoreUpgradeScriptsCommand extends Command {
34
35
	/**
36
	 * @var OccRunner $occRunner
37
	 */
38
	protected $occRunner;
39
40
	public function __construct($occRunner){
41
		parent::__construct();
42
		$this->occRunner = $occRunner;
43
	}
44
45
	protected function configure(){
46
		$this
47
				->setName('upgrade:executeCoreUpgradeScripts')
48
				->setDescription('execute core upgrade scripts [danger, might take long]');
49
	}
50
51
	protected function execute(InputInterface $input, OutputInterface $output){
52
		$locator = $this->container['utils.locator'];
53
		/** @var FilesystemHelper $fsHelper */
54
		$fsHelper = $this->container['utils.filesystemhelper'];
55
		$registry = $this->container['utils.registry'];
56
		$fetcher = $this->container['utils.fetcher'];
57
		/** @var Checkpoint $checkpoint */
58
		$checkpoint = $this->container['utils.checkpoint'];
59
60
		$installedVersion = implode('.', $locator->getInstalledVersion());
61
		$registry->set('installedVersion', $installedVersion);
62
		
63
		$feed = $registry->get('feed');
64
65
		if ($feed){
66
			$path = $fetcher->getBaseDownloadPath($feed);
67
			$fullExtractionPath = $locator->getExtractionBaseDir() . '/' . $feed->getVersion();
68
69
			if (file_exists($fullExtractionPath)){
70
				$fsHelper->removeIfExists($fullExtractionPath);
71
			}
72
			try{
73
				$fsHelper->mkdir($fullExtractionPath, true);
74
			} catch (\Exception $e){
75
					$output->writeln('Unable create directory ' . $fullExtractionPath);
76
					throw $e;
77
			}
78
79
			$output->writeln('Extracting source into ' . $fullExtractionPath);
80
			$extractor = new ZipExtractor($path, $fullExtractionPath, $output);
81
82
			try{
83
				$extractor->extract();
84
			} catch (\Exception $e){
85
				$output->writeln('Extraction has been failed');
86
				$fsHelper->removeIfExists($locator->getExtractionBaseDir());
87
				throw $e;
88
			}
89
90
			$tmpDir = $locator->getExtractionBaseDir() . '/' . $installedVersion;
91
			$fsHelper->removeIfExists($tmpDir);
92
			$fsHelper->mkdir($tmpDir);
93
			$oldSourcesDir = $locator->getOwncloudRootPath();
94
			$newSourcesDir = $fullExtractionPath . '/owncloud';
95
96 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...
97
				$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...
98
				$fsHelper->tripleMove($oldSourcesDir, $newSourcesDir, $tmpDir, $dir);
99
			}
100
			
101
			$fsHelper->copyr($tmpDir . '/config/config.php', $oldSourcesDir . '/config/config.php');
102
103
			//Remove old apps
104
			$appDirectories = $fsHelper->scandirFiltered($oldSourcesDir . '/apps');
105
			foreach ($appDirectories as $appDirectory){
106
				$fsHelper->rmdirr($oldSourcesDir . '/apps/' . $appDirectory);
107
			}
108
109
			//Put new shipped apps
110
			$newAppsDir = $fullExtractionPath . '/owncloud/apps';
111
			$newAppsList = $fsHelper->scandirFiltered($newAppsDir);
112
			foreach ($newAppsList as $appId){
113
				$output->writeln('Copying the application ' . $appId);
114
				$fsHelper->copyr($newAppsDir . '/' . $appId, $locator->getOwnCloudRootPath() . '/apps/' . $appId, false);
115
			}
116
			
117
			try {
118
				$plain = $this->occRunner->run('upgrade');
119
				$output->writeln($plain);
120
			} catch (ProcessFailedException $e){
121
				$lastCheckpointId = $checkpoint->getLastCheckpointId();
122
				if ($lastCheckpointId){
123
					$lastCheckpointPath = $checkpoint->getCheckpointPath($lastCheckpointId);
0 ignored issues
show
Bug introduced by
It seems like $lastCheckpointId defined by $checkpoint->getLastCheckpointId() on line 121 can also be of type boolean; however, Owncloud\Updater\Utils\C...nt::getCheckpointPath() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
124
					$fsHelper->copyr($lastCheckpointPath . '/apps', $oldSourcesDir . '/apps', false);
125
				}
126
				if ($e->getProcess()->getExitCode() != 3){
127
					throw ($e);
128
				}
129
			}
130
		}
131
	}
132
}
133