UnifiedAccount   A
last analyzed

Complexity

Total Complexity 26

Size/Duplication

Total Lines 213
Duplicated Lines 3.76 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 4.67%

Importance

Changes 0
Metric Value
wmc 26
c 0
b 0
f 0
lcom 1
cbo 4
dl 8
loc 213
ccs 5
cts 107
cp 0.0467
rs 10

13 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getConfiguration() 0 5 1
A getListArray() 0 10 1
B buildInbox() 0 37 6
A getMailbox() 0 3 1
A getEmail() 0 15 4
A sendMessage() 0 3 1
A saveDraft() 0 3 1
A deleteMessage() 0 8 1
B getChangedMailboxes() 0 34 6
A getInbox() 0 3 1
A getId() 0 3 1
A resolve() 8 8 1

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 Christoph Wurst <[email protected]>
5
 * @author Thomas Müller <[email protected]>
6
 *
7
 * Mail
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
namespace OCA\Mail\Service;
23
24
use OCP\IL10N;
25
use OCA\Mail\Model\IMessage;
26
27
class UnifiedAccount implements IAccount {
28
29
	const ID = -1;
30
	const INBOX_ID = 'all-inboxes';
31
32
	/** @var AccountService */
33
	private $accountService;
34
35
	/** @var string */
36
	private $userId;
37
38
	/** @var IL10N */
39
	private $l10n;
40
41
	/** @var Horde_Mail_Rfc822_List */
42
	private $email;
43
44
	/**
45
	 * @param AccountService $accountService
46
	 * @param string $userId
47
	 * @param IL10N $l10n
48
	 */
49 1
	public function __construct(AccountService $accountService, $userId, IL10N $l10n) {
50 1
		$this->accountService = $accountService;
51 1
		$this->userId = $userId;
52 1
		$this->l10n = $l10n;
53 1
	}
54
55
	/**
56
	 * @return array
57
	 */
58
	public function getConfiguration() {
59
		return [
60
			'accountId' => UnifiedAccount::ID,
61
		];
62
	}
63
64
	/**
65
	 * @return array
66
	 * TODO: function name is :hankey:
67
	 */
68
	public function getListArray() {
69
		$inbox = $this->buildInbox();
70
		return [
71
			'id'             => UnifiedAccount::ID,
72
			'email'          => '',
73
			'folders'        => [$inbox],
74
			'specialFolders' => [],
75
			'delimiter' => '.',
76
		];
77
	}
78
79
	private function buildInbox() {
80
		$displayName = (string)$this->l10n->t('All inboxes');
81
82
		$allAccounts = $this->accountService->findByUserId($this->userId);
83
84
		$uidValidity = [];
85
		$uidNext = [];
86
		$unseen = 0;
87
88
		foreach($allAccounts as $account) {
89
			/** @var IAccount $account */
90
			$inbox = $account->getInbox();
91
			if (is_null($inbox)) {
92
				continue;
93
			}
94
95
			$status = $inbox->getStatus();
96
			$unseen += isset($status['unseen']) ? $status['unseen'] : 0;
97
			$uidValidity[$account->getId()] = isset($status['uidvalidity']) ? $status['uidvalidity'] : 0;
98
			$uidNext[$account->getId()] = isset($status['uidnext']) ? $status['uidnext'] : 0;
99
		}
100
101
		return [
102
			'id' => base64_encode(self::INBOX_ID),
103
			'parent' => null,
104
			'name' => $displayName,
105
			'specialRole' => 'inbox',
106
			'unseen' => $unseen,
107
			'total' => 100,
108
			'isEmpty' => false,
109
			'accountId' => UnifiedAccount::ID,
110
			'noSelect' => false,
111
			'uidvalidity' => $uidValidity,
112
			'uidnext' => $uidNext,
113
			'delimiter' => '.'
114
		];
115
	}
116
117
	/**
118
	 * @param $folderId
119
	 * @return IMailBox
120
	 */
121
	public function getMailbox($folderId) {
122
		return new UnifiedMailbox($this->accountService, $this->userId);
123
	}
124
125
	/**
126
	 * @return string
127
	 */
128
	public function getEmail() {
129
		if ($this->email === null) {
130
			$allAccounts = $this->accountService->findByUserId($this->userId);
131
			$addressesList = new \Horde_Mail_Rfc822_List();
132
			foreach ($allAccounts as $account) {
133
				$inbox = $account->getInbox();
134
				if (is_null($inbox)) {
135
					continue;
136
				}
137
				$addressesList->add($account->getEmail());
138
			}
139
			$this->email = $addressesList;
0 ignored issues
show
Documentation Bug introduced by
It seems like $addressesList of type object<Horde_Mail_Rfc822_List> is incompatible with the declared type object<OCA\Mail\Service\Horde_Mail_Rfc822_List> of property $email.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
140
		}
141
		return $this->email;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->email; (Horde_Mail_Rfc822_List|O...\Horde_Mail_Rfc822_List) is incompatible with the return type declared by the interface OCA\Mail\Service\IAccount::getEmail of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
142
	}
143
144
	/**
145
	 * @param IMessage $message
146
	 * @param int|null $draftUID
147
	 */
148
	public function sendMessage(IMessage $message, $draftUID) {
149
		throw new Exception('Not implemented');
150
	}
151
152
	/**
153
	 * @param IMessage $message
154
	 * @param int|null $previousUID
155
	 * @return int
156
	 */
157
	public function saveDraft(IMessage $message, $previousUID) {
158
		throw new Exception('Not implemented');
159
	}
160
161
	/**
162
	 * @param string $folderId
163
	 * @param string $messageId
164
	 */
165
	public function deleteMessage($folderId, $messageId) {
166
		$data = json_decode(base64_decode($messageId), true);
167
		$account = $this->accountService->find($this->userId, $data[0]);
168
		$inbox = $account->getInbox();
169
		$messageId = $data[1];
170
171
		$account->deleteMessage($inbox->getFolderId(), $messageId);
172
	}
173
174
	/**
175
	 * @param string[] $query
176
	 * @return array
177
	 */
178
	public function getChangedMailboxes($query) {
179
		$accounts = $this->accountService->findByUserId($this->userId);
180
		$changedBoxes = [];
181
182
		foreach($accounts as $account) {
183
			/** @var IAccount $account */
184
			if ($account->getId() === UnifiedAccount::ID) {
185
				continue;
186
			}
187
			$inbox = $account->getInbox();
188
			$inboxName = $inbox->getFolderId();
189
			$changes = $account->getChangedMailboxes([$inboxName => [
0 ignored issues
show
Documentation introduced by
array($inboxName => arra...'][$account->getId()])) is of type array<string,array<strin...","uidnext":"string"}>>, but the function expects a array<integer,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...
190
				'uidvalidity' => $query[self::INBOX_ID]['uidvalidity'][$account->getId()],
191
				'uidnext' => $query[self::INBOX_ID]['uidnext'][$account->getId()],
192
			]]);
193
			if (!isset($changes[$inboxName])) {
194
				continue;
195
			}
196
			if (!isset($changedBoxes[self::INBOX_ID])) {
197
				$changedBoxes[self::INBOX_ID] = $this->buildInbox();
198
				$changedBoxes[self::INBOX_ID]['messages'] = [];
199
				$changedBoxes[self::INBOX_ID]['newUnReadCounter'] = 0;
200
			}
201
			// Create special unified inbox message IDs
202
			foreach ($changes[$inboxName]['messages'] as &$message) {
203
				$id = base64_encode(json_encode([$account->getId(), $message['id']]));
204
				$message['id'] = $id;
205
				$message['accountMail'] = $account->getEmail();
206
			}
207
			$changedBoxes[self::INBOX_ID]['messages'] = array_merge($changedBoxes[self::INBOX_ID]['messages'], $changes[$inboxName]['messages']);
208
			$changedBoxes[self::INBOX_ID]['newUnReadCounter'] += $changes[$inboxName]['newUnReadCounter'];
209
		}
210
		return $changedBoxes;
211
	}
212
213
	/**
214
	 * @return IMailBox
215
	 */
216
	public function getInbox() {
217
		return null;
218
	}
219
220
	/**
221
	 * @return int
222
	 */
223
	public function getId() {
224
		return UnifiedAccount::ID;
225
	}
226
227
	/**
228
	 * @param string $messageId
229
	 * @return array
230
	 */
231 View Code Duplication
	public function resolve($messageId) {
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...
232
		$data = json_decode(base64_decode($messageId), true);
233
		$account = $this->accountService->find($this->userId, $data[0]);
234
		$inbox = $account->getInbox();
235
		$messageId = $data[1];
236
237
		return [$account, base64_encode($inbox->getFolderId()), $messageId];
238
	}
239
}
240