Completed
Push — master ( 3aeedd...be0cda )
by Maxence
03:35 queued 11s
created

CircleLeave::selectNewOwner()   B

Complexity

Conditions 10
Paths 12

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 29
rs 7.6666
c 0
b 0
f 0
cc 10
nc 12
nop 1

How to fix   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
declare(strict_types=1);
4
5
6
/**
7
 * Circles - Bring cloud-users closer together.
8
 *
9
 * This file is licensed under the Affero General Public License version 3 or
10
 * later. See the COPYING file.
11
 *
12
 * @author Maxence Lange <[email protected]>
13
 * @copyright 2021
14
 * @license GNU AGPL version 3 or any later version
15
 *
16
 * This program is free software: you can redistribute it and/or modify
17
 * it under the terms of the GNU Affero General Public License as
18
 * published by the Free Software Foundation, either version 3 of the
19
 * License, or (at your option) any later version.
20
 *
21
 * This program is distributed in the hope that it will be useful,
22
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24
 * GNU Affero General Public License for more details.
25
 *
26
 * You should have received a copy of the GNU Affero General Public License
27
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
28
 *
29
 */
30
31
32
namespace OCA\Circles\FederatedItems;
33
34
35
use daita\MySmallPhpTools\Traits\Nextcloud\nc22\TNC22Deserialize;
36
use OCA\Circles\Db\CircleRequest;
37
use OCA\Circles\Db\MemberRequest;
38
use OCA\Circles\Exceptions\FederatedItemException;
39
use OCA\Circles\Exceptions\MemberNotFoundException;
40
use OCA\Circles\Exceptions\RequestBuilderException;
41
use OCA\Circles\IFederatedItem;
42
use OCA\Circles\IFederatedItemAsyncProcess;
43
use OCA\Circles\IFederatedItemHighSeverity;
44
use OCA\Circles\IFederatedItemInitiatorMembershipNotRequired;
45
use OCA\Circles\IFederatedItemMemberOptional;
46
use OCA\Circles\Model\Circle;
47
use OCA\Circles\Model\Federated\FederatedEvent;
48
use OCA\Circles\Model\FederatedUser;
49
use OCA\Circles\Model\Helpers\MemberHelper;
50
use OCA\Circles\Model\Member;
51
use OCA\Circles\Service\ConfigService;
52
use OCA\Circles\Service\EventService;
53
use OCA\Circles\Service\MembershipService;
54
use OCA\Circles\StatusCode;
55
56
57
/**
58
 * Class CircleLeave
59
 *
60
 * @package OCA\Circles\FederatedItems
61
 */
62
class CircleLeave implements
63
	IFederatedItem,
64
	IFederatedItemHighSeverity,
65
	IFederatedItemAsyncProcess,
66
	IFederatedItemInitiatorMembershipNotRequired,
67
	IFederatedItemMemberOptional {
68
69
70
	use TNC22Deserialize;
71
72
73
	/** @var MemberRequest */
74
	private $memberRequest;
75
76
	/** @var CircleRequest */
77
	private $circleRequest;
78
79
	/** @var MembershipService */
80
	private $membershipService;
81
82
	/** @var EventService */
83
	private $eventService;
84
85
	/** @var ConfigService */
86
	private $configService;
87
88
89
	/**
90
	 * CircleLeave constructor.
91
	 *
92
	 * @param MemberRequest $memberRequest
93
	 * @param CircleRequest $circleRequest
94
	 * @param MembershipService $membershipService
95
	 * @param EventService $eventService
96
	 * @param ConfigService $configService
97
	 */
98 View Code Duplication
	public function __construct(
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
99
		MemberRequest $memberRequest,
100
		CircleRequest $circleRequest,
101
		MembershipService $membershipService,
102
		EventService $eventService,
103
		ConfigService $configService
104
	) {
105
		$this->memberRequest = $memberRequest;
106
		$this->circleRequest = $circleRequest;
107
		$this->membershipService = $membershipService;
108
		$this->eventService = $eventService;
109
		$this->configService = $configService;
110
	}
111
112
113
	/**
114
	 * @param FederatedEvent $event
115
	 *
116
	 * @throws FederatedItemException
117
	 * @throws RequestBuilderException
118
	 */
119
	public function verify(FederatedEvent $event): void {
120
		$circle = $event->getCircle();
121
		$member = $circle->getInitiator();
122
123
		if (!$event->getParams()->gBool('force')) {
124
			$memberHelper = new MemberHelper($member);
125
			$memberHelper->cannotBeOwner();
126
		} else if ($this->configService->isLocalInstance($event->getOrigin())) {
127
			if ($member->getLevel() === Member::LEVEL_OWNER) {
128
				try {
129
					$newOwner = $this->selectNewOwner($circle);
130
					$event->getData()->s('newOwnerId', $newOwner->getId());
131
				} catch (MemberNotFoundException $e) {
132
					$event->getData()->sBool('destroyCircle', true);
133
				}
134
			}
135
		}
136
		if ($member->getId() === '') {
137
			throw new MemberNotFoundException(StatusCode::$CIRCLE_LEAVE[120], 120);
0 ignored issues
show
Bug introduced by
The property CIRCLE_LEAVE cannot be accessed from this context as it is declared private in class OCA\Circles\StatusCode.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
138
		}
139
140
		$event->setMember($member);
141
		$this->memberRequest->delete($member);
142
143
		$initiator = new FederatedUser();
144
		$initiator->importFromIFederatedUser($member);
145
146
		$outcome = $this->circleRequest->getCircle($circle->getSingleId(), $initiator);
147
148
		$event->setOutcome($this->serialize($outcome));
149
	}
150
151
152
	/**
153
	 * @param FederatedEvent $event
154
	 *
155
	 * @throws RequestBuilderException
156
	 * @throws MemberNotFoundException
157
	 */
158
	public function manage(FederatedEvent $event): void {
159
		$member = $event->getMember();
160
		$newOwnerId = $event->getData()->g('newOwnerId');
161
		if ($newOwnerId !== '') {
162
			$newOwner = $this->memberRequest->getMemberById($newOwnerId);
163
			$newOwner->setLevel(Member::LEVEL_OWNER);
164
			$this->memberRequest->updateLevel($newOwner);
165
			$this->membershipService->onUpdate($newOwner->getSingleId());
166
		}
167
168
		$this->memberRequest->delete($member);
169
170
		$destroyingCircle = $event->getData()->gBool('destroyCircle');
171
		if ($destroyingCircle) {
172
			$circle = $event->getCircle();
173
			$this->circleRequest->delete($circle);
174
		}
175
176
		$this->membershipService->onUpdate($member->getSingleId());
177
		$this->eventService->memberLeaving($event);
178
179
		if ($destroyingCircle) {
180
			$this->membershipService->onUpdate($circle->getSingleId());
0 ignored issues
show
Bug introduced by
The variable $circle does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
181
			$this->eventService->circleDestroying($event);
182
		}
183
	}
184
185
186
	/**
187
	 * @param FederatedEvent $event
188
	 * @param array $results
189
	 */
190
	public function result(FederatedEvent $event, array $results): void {
191
		$this->eventService->memberLeft($event, $results);
192
193
		if ($event->getData()->gBool('destroyCircle')) {
194
			$this->eventService->circleDestroyed($event, $results);
195
		}
196
	}
197
198
199
	/**
200
	 * @param Circle $circle
201
	 *
202
	 * @return Member
203
	 * @throws RequestBuilderException
204
	 * @throws MemberNotFoundException
205
	 */
206
	private function selectNewOwner(Circle $circle): Member {
207
		$members = $this->memberRequest->getMembers($circle->getSingleId());
208
		$newOwner = null;
209
		foreach ($members as $member) {
210
			if ($member->getLevel() === Member::LEVEL_OWNER) {
211
				continue;
212
			}
213
			if (is_null($newOwner)) {
214
				$newOwner = $member;
215
				continue;
216
			}
217
218
			if ($member->getLevel() > $newOwner->getLevel()) {
219
				$newOwner = $member;
220
			} else if ($member->getLevel() === $newOwner->getLevel()
221
					   && ($member->getJoined() < $newOwner->getJoined()
222
						   || ($this->configService->isLocalInstance($member->getInstance())
223
							   && !$this->configService->isLocalInstance($newOwner->getInstance()))
224
					   )) {
225
				$newOwner = $member;
226
			}
227
		}
228
229
		if (is_null($newOwner)) {
230
			throw new MemberNotFoundException();
231
		}
232
233
		return $newOwner;
234
	}
235
236
}
237
238