Completed
Push — master ( bdb8e8...32094f )
by Phil
29s
created

isUpgradeAllowed()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 10
ccs 6
cts 6
cp 1
rs 9.9332
cc 4
nc 3
nop 3
crap 4
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
/**
34
 * Class ExecuteCoreUpgradeScriptsCommand
35
 *
36
 * @package Owncloud\Updater\Command
37
 */
38
class ExecuteCoreUpgradeScriptsCommand extends Command {
39
40
	/**
41
	 * @var OccRunner $occRunner
42
	 */
43
	protected $occRunner;
44
45
	/**
46
	 * ExecuteCoreUpgradeScriptsCommand constructor.
47
	 *
48
	 * @param null|string $occRunner
49
	 */
50
	public function __construct($occRunner){
51
		parent::__construct();
52
		$this->occRunner = $occRunner;
0 ignored issues
show
Documentation Bug introduced by
It seems like $occRunner can also be of type string. However, the property $occRunner is declared as type object<Owncloud\Updater\Utils\OccRunner>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

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

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
53
	}
54
55
	protected function configure(){
56
		$this
57
				->setName('upgrade:executeCoreUpgradeScripts')
58
				->setDescription('execute core upgrade scripts [danger, might take long]');
59
	}
60
61
	/**
62
	 * @param InputInterface $input
63
	 * @param OutputInterface $output
64
	 * @throws \Exception
65
	 */
66
	protected function execute(InputInterface $input, OutputInterface $output){
67
		$locator = $this->container['utils.locator'];
68
		/** @var FilesystemHelper $fsHelper */
69
		$fsHelper = $this->container['utils.filesystemhelper'];
70
		$registry = $this->container['utils.registry'];
71
		$fetcher = $this->container['utils.fetcher'];
72
		/** @var Checkpoint $checkpoint */
73
		$checkpoint = $this->container['utils.checkpoint'];
74
75
		$installedVersion = implode('.', $locator->getInstalledVersion());
76
		$registry->set('installedVersion', $installedVersion);
77
78
		/** @var  \Owncloud\Updater\Utils\Feed $feed */
79
		$feed = $registry->get('feed');
80
81
		if ($feed){
82
			$path = $fetcher->getBaseDownloadPath($feed);
83
			$fullExtractionPath = $locator->getExtractionBaseDir() . '/' . $feed->getVersion();
84
85
			if (file_exists($fullExtractionPath)){
86
				$fsHelper->removeIfExists($fullExtractionPath);
87
			}
88
			try{
89
				$fsHelper->mkdir($fullExtractionPath, true);
90
			} catch (\Exception $e){
91
					$output->writeln('Unable create directory ' . $fullExtractionPath);
92
					throw $e;
93
			}
94
95
			$output->writeln('Extracting source into ' . $fullExtractionPath);
96
			$extractor = new ZipExtractor($path, $fullExtractionPath, $output);
97
98
			try{
99
				$extractor->extract();
100
			} catch (\Exception $e){
101
				$output->writeln('Extraction has been failed');
102
				$fsHelper->removeIfExists($locator->getExtractionBaseDir());
103
				throw $e;
104
			}
105
106
			$tmpDir = $locator->getExtractionBaseDir() . '/' . $installedVersion;
107
			$fsHelper->removeIfExists($tmpDir);
108
			$fsHelper->mkdir($tmpDir);
109
			$oldSourcesDir = $locator->getOwncloudRootPath();
110
			$newSourcesDir = $fullExtractionPath . '/owncloud';
111
112
			$packageVersion = $this->loadVersion($newSourcesDir);
113
			$allowedPreviousVersions = $this->loadAllowedPreviousVersions($newSourcesDir);
114
115
			if (!$this->isUpgradeAllowed($installedVersion, $packageVersion, $allowedPreviousVersions)){
116
				$message = sprintf(
117
					'Update from %s to %s is not possible. Updates between multiple major versions and downgrades are unsupported.',
118
					$installedVersion,
119
					$packageVersion
120
				);
121
				$this->getApplication()->getLogger()->error($message);
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...
122
				$output->writeln('<error>'. $message .'</error>');
123
				return 1;
124
			}
125
126 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...
127
				$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...
128
				$fsHelper->tripleMove($oldSourcesDir, $newSourcesDir, $tmpDir, $dir);
129
			}
130
			
131
			$fsHelper->copyr($tmpDir . '/config/config.php', $oldSourcesDir . '/config/config.php');
132
133
			//Get a new shipped apps list
134
			$newAppsDir = $fullExtractionPath . '/owncloud/apps';
135
			$newAppsList = $fsHelper->scandirFiltered($newAppsDir);
136
137
			//Remove old apps
138
			$appDirectories = $fsHelper->scandirFiltered($oldSourcesDir . '/apps');
139
			$oldAppList = array_intersect($appDirectories, $newAppsList);
140
			foreach ($oldAppList as $appDirectory){
141
				$fsHelper->rmdirr($oldSourcesDir . '/apps/' . $appDirectory);
142
			}
143
144
			foreach ($newAppsList as $appId){
145
				$output->writeln('Copying the application ' . $appId);
146
				$fsHelper->copyr($newAppsDir . '/' . $appId, $locator->getOwnCloudRootPath() . '/apps/' . $appId, false);
147
			}
148
			
149
			try {
150
				$plain = $this->occRunner->run('upgrade');
151
				$output->writeln($plain);
152
			} catch (ProcessFailedException $e){
153
				$lastCheckpointId = $checkpoint->getLastCheckpointId();
154
				if ($lastCheckpointId){
155
					$lastCheckpointPath = $checkpoint->getCheckpointPath($lastCheckpointId);
0 ignored issues
show
Bug introduced by
It seems like $lastCheckpointId defined by $checkpoint->getLastCheckpointId() on line 153 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...
156
					$fsHelper->copyr($lastCheckpointPath . '/apps', $oldSourcesDir . '/apps', false);
157
				}
158
				if ($e->getProcess()->getExitCode() != 3){
159
					throw ($e);
160
				}
161
			}
162
		}
163
	}
164
165 8
	public function isUpgradeAllowed($installedVersion, $packageVersion, $canBeUpgradedFrom){
166 8
		if (version_compare($installedVersion, $packageVersion, '<=')){
167 5
			foreach ($canBeUpgradedFrom as $allowedPreviousVersion){
168 5
				if (version_compare($allowedPreviousVersion, $installedVersion, '<=')){
169 5
					return true;
170
				}
171
			}
172
		}
173 3
		return false;
174
	}
175
176
	/**
177
	 * @param string $pathToPackage
178
	 * @return string
179
	 */
180
	protected function loadVersion($pathToPackage){
181
		require  $pathToPackage . '/version.php';
182
		/** @var $OC_Version array */
183
		return implode('.', $OC_Version);
0 ignored issues
show
Bug introduced by
The variable $OC_Version does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
184
	}
185
186
	/**
187
	 * @param string $pathToPackage
188
	 * @return string[]
189
	 */
190 2
	protected function loadAllowedPreviousVersions($pathToPackage) {
191 2
		$canBeUpgradedFrom = $this->loadCanBeUpgradedFrom($pathToPackage);
192
		
193 2
		$firstItem = reset($canBeUpgradedFrom);
194 2
		if (!is_array($firstItem)){
195 1
			$canBeUpgradedFrom = [$canBeUpgradedFrom];
196
		}
197
		
198 2
		$allowedVersions = [];
199 2
		foreach ($canBeUpgradedFrom as $version){
200 2
			$allowedVersions[] = implode('.', $version);
201
		}
202
203 2
		return $allowedVersions;
204
	}
205
	
206
	/**
207
	 * @param string $pathToPackage
208
	 * @return array
209
	 */
210
	protected function loadCanBeUpgradedFrom($pathToPackage){
211
		require $pathToPackage . '/version.php';
212
		/** @var array $OC_VersionCanBeUpgradedFrom */
213
		return $OC_VersionCanBeUpgradedFrom;
0 ignored issues
show
Bug introduced by
The variable $OC_VersionCanBeUpgradedFrom does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
214
	}
215
}
216