Completed
Push — master ( 62cea1...761e56 )
by Joas
14s
created

GroupHelper::addActivity()   F

Complexity

Conditions 12
Paths 400

Size

Total Lines 55

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 52.856

Importance

Changes 0
Metric Value
dl 0
loc 55
ccs 12
cts 35
cp 0.3429
rs 3.6333
c 0
b 0
f 0
cc 12
nc 400
nop 1
crap 52.856

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
 * @copyright Copyright (c) 2016, ownCloud, Inc.
4
 *
5
 * @author Joas Schilling <[email protected]>
6
 *
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 OCA\Activity;
24
25
use OCA\Activity\Extension\LegacyParser;
26
use OCA\Activity\Parameter\IParameter;
27
use OCP\Activity\IEvent;
28
use OCP\Activity\IManager;
29
use OCP\IL10N;
30
use OCP\ILogger;
31
use OCP\RichObjectStrings\InvalidObjectExeption;
32
use OCP\RichObjectStrings\IValidator;
33
34
class GroupHelper {
35
	/** @var IEvent[] */
36
	protected $event = [];
37
	/** @var int */
38
	protected $lastEvent = 0;
39
40
	/** @var bool */
41
	protected $allowGrouping;
42
43
	/** @var IL10N */
44
	protected $l;
45
46
	/** @var \OCP\Activity\IManager */
47
	protected $activityManager;
48
49
	/** @var \OCA\Activity\DataHelper */
50
	protected $dataHelper;
51
52
	/** @var IValidator */
53
	protected $richObjectValidator;
54
55
	/** @var ILogger */
56
	protected $logger;
57
58
	/** @var LegacyParser */
59
	protected $legacyParser;
60
61 20
	public function __construct(IL10N $l,
62
								IManager $activityManager,
63
								DataHelper $dataHelper,
64
								IValidator $richObjectValidator,
65
								ILogger $logger,
66
								LegacyParser $legacyParser) {
67 20
		$this->allowGrouping = true;
68
69 20
		$this->l = $l;
70 20
		$this->activityManager = $activityManager;
71 20
		$this->dataHelper = $dataHelper;
72 20
		$this->richObjectValidator = $richObjectValidator;
73 20
		$this->logger = $logger;
74 20
		$this->legacyParser = $legacyParser;
75 20
	}
76
77
	/**
78
	 * @param string $user
79
	 */
80 6
	public function setUser($user) {
81 6
		$this->dataHelper->setUser($user);
82 6
	}
83
84
	/**
85
	 * @param IL10N $l
86
	 */
87 1
	public function setL10n(IL10N $l) {
88 1
		$this->l = $l;
89 1
		$this->dataHelper->setL10n($l);
90 1
	}
91
92
	/**
93
	 * Add an activity to the internal array
94
	 *
95
	 * @param array $activity
96
	 */
97 4
	public function addActivity($activity) {
98 4
		$id = (int) $activity['activity_id'];
99 4
		$event = $this->arrayToEvent($activity);
100 4
		$language = $this->l->getLanguageCode();
101
102 4
		foreach ($this->activityManager->getProviders() as $provider) {
103
			try {
104
				$this->activityManager->setFormattingObject($event->getObjectType(), $event->getObjectId());
105
				if ($this->allowGrouping && $this->lastEvent !== 0 && isset($this->event[$this->lastEvent])) {
106
					$event = $provider->parse($language, $event, $this->event[$this->lastEvent]);
107
				} else {
108
					$event = $provider->parse($language, $event);
109
				}
110
				try {
111
					$this->richObjectValidator->validate($event->getRichSubject(), $event->getRichSubjectParameters());
112
				} catch (InvalidObjectExeption $e) {
0 ignored issues
show
Bug introduced by
The class OCP\RichObjectStrings\InvalidObjectExeption does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
113
					$this->logger->logException($e);
114
					$event->setRichSubject('Rich subject or a parameter for "' . $event->getRichSubject() . '" is malformed', []);
115
					$event->setParsedSubject('Rich subject or a parameter for "' . $event->getRichSubject() . '" is malformed');
116
				}
117
118
				if ($event->getRichMessage()) {
119
					try {
120
						$this->richObjectValidator->validate($event->getRichMessage(), $event->getRichMessageParameters());
121
					} catch (InvalidObjectExeption $e) {
0 ignored issues
show
Bug introduced by
The class OCP\RichObjectStrings\InvalidObjectExeption does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
122
						$this->logger->logException($e);
123
						$event->setRichMessage('Rich message or a parameter is malformed', []);
124
						$event->setParsedMessage('Rich message or a parameter is malformed');
125
					}
126
				}
127
128
				$this->activityManager->setFormattingObject('', 0);
129
130
				$child = $event->getChildEvent();
131
				if ($child instanceof IEvent) {
0 ignored issues
show
Bug introduced by
The class OCP\Activity\IEvent does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
132
					unset($this->event[$this->lastEvent]);
133
				}
134
			} catch (\InvalidArgumentException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
135
			}
136
		}
137
138 4
		if (!$event->getParsedSubject()) {
139
			try {
140 4
				$this->activityManager->setFormattingObject($event->getObjectType(), $event->getObjectId());
141 4
				$event = $this->legacyParser->parse($language, $event);
142 4
				$this->activityManager->setFormattingObject('', 0);
143
			} catch (\InvalidArgumentException $e) {
144
				\OC::$server->getLogger()->debug('Failed to parse activity');
145
				return;
146
			}
147
		}
148
149 4
		$this->event[$id] = $event;
150 4
		$this->lastEvent = $id;
151 4
	}
152
153
	/**
154
	 * Get the prepared activities
155
	 *
156
	 * @return array translated activities ready for use
157
	 */
158 5
	public function getActivities() {
159 5
		$return = [];
160 5
		foreach ($this->event as $id => $event) {
161 4
			$return[] = $this->eventToArray($event, $id);
162
		}
163 5
		$this->event = [];
164
165 5
		return $return;
166
	}
167
168
	/**
169
	 * @param array $row
170
	 * @return IEvent
171
	 */
172 6
	protected function arrayToEvent(array $row) {
173 6
		$event = $this->activityManager->generateEvent();
174 6
		$event->setApp((string) $row['app'])
175 6
			->setType((string) $row['type'])
176 6
			->setAffectedUser((string) $row['affecteduser'])
177 6
			->setAuthor((string) $row['user'])
178 6
			->setTimestamp((int) $row['timestamp'])
179 6
			->setSubject((string) $row['subject'], json_decode($row['subjectparams'], true))
180 6
			->setMessage((string) $row['message'], json_decode($row['messageparams'], true))
181 6
			->setObject((string) $row['object_type'], (int) $row['object_id'], (string) $row['file'])
182 6
			->setLink((string) $row['link']);
183
184 6
		return $event;
185
	}
186
187
	/**
188
	 * @param IEvent $event
189
	 * @return array
190
	 */
191 4
	protected function eventToArray(IEvent $event, $id) {
192
		return [
193 4
			'activity_id' => $id,
194 4
			'app' => $event->getApp(),
195 4
			'type' => $event->getType(),
196 4
			'affecteduser' => $event->getAffectedUser(),
197 4
			'user' => $event->getAuthor(),
198 4
			'timestamp' => $event->getTimestamp(),
199 4
			'subject' => $event->getParsedSubject(),
200
			'subject_rich' => [
201 4
				(string) $event->getRichSubject(),
202 4
				(array) $event->getRichSubjectParameters(),
203
			],
204 4
			'message' => $event->getParsedMessage(),
205
			'message_rich' => [
206 4
				(string) $event->getRichMessage(),
207 4
				(array) $event->getRichMessageParameters(),
208
			],
209 4
			'object_type' => $event->getObjectType(),
210 4
			'object_id' => $event->getObjectId(),
211 4
			'object_name' => $event->getObjectName(),
212 4
			'objects' => $this->getObjectsFromChildren($event),
213 4
			'link' => $event->getLink(),
214 4
			'icon' => $event->getIcon(),
215
		];
216
	}
217
218
	/**
219
	 * @param IEvent $event
220
	 * @return array
221
	 */
222 4
	protected function getObjectsFromChildren(IEvent $event) {
223 4
		$child = $event->getChildEvent();
224 4
		if ($child instanceof IEvent) {
0 ignored issues
show
Bug introduced by
The class OCP\Activity\IEvent does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
225
			$objects = $this->getObjectsFromChildren($child);
226
			$objects[$event->getObjectId()] = $event->getObjectName();
227
			return $objects;
228
		} else {
229 4
			return [$event->getObjectId() => $event->getObjectName()];
230
		}
231
	}
232
}
233