Completed
Push — master ( 4f34f2...9208b7 )
by Roeland
8s
created

Provider::generateUserParameter()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 0
cts 6
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
nop 1
crap 6
1
<?php
2
/**
3
 * @copyright Copyright (c) 2016 Joas Schilling <[email protected]>
4
 *
5
 * @license GNU AGPL version 3 or any later version
6
 *
7
 * This program is free software: you can redistribute it and/or modify
8
 * it under the terms of the GNU Affero General Public License as
9
 * published by the Free Software Foundation, either version 3 of the
10
 * License, or (at your option) any later version.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU Affero General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Affero General Public License
18
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
 *
20
 */
21
22
namespace OCA\AnnouncementCenter\Activity;
23
24
use OCA\AnnouncementCenter\Manager;
25
use OCP\Activity\IEvent;
26
use OCP\Activity\IManager;
27
use OCP\Activity\IProvider;
28
use OCP\IURLGenerator;
29
use OCP\IUser;
30
use OCP\IUserManager;
31
use OCP\L10N\IFactory;
32
33
class Provider implements IProvider {
34
35
	/** @var IFactory */
36
	protected $languageFactory;
37
38
	/** @var IURLGenerator */
39
	protected $url;
40
41
	/** @var IManager */
42
	protected $activityManager;
43
44
	/** @var IUserManager */
45
	protected $userManager;
46
47
	/** @var Manager */
48
	protected $manager;
49
50
	/** @var string[] */
51
	protected $displayNames = [];
52
53
	/**
54
	 * @param IFactory $languageFactory
55
	 * @param IURLGenerator $url
56
	 * @param IManager $activityManager
57
	 * @param IUserManager $userManager
58
	 * @param Manager $manager
59
	 */
60 1
	public function __construct(IFactory $languageFactory, IURLGenerator $url, IManager $activityManager, IUserManager $userManager, Manager $manager) {
61 1
		$this->languageFactory = $languageFactory;
62 1
		$this->url = $url;
63 1
		$this->activityManager = $activityManager;
64 1
		$this->userManager = $userManager;
65 1
		$this->manager = $manager;
66 1
	}
67
68
	/**
69
	 * @param string $language
70
	 * @param IEvent $event
71
	 * @param IEvent|null $previousEvent
72
	 * @return IEvent
73
	 * @throws \InvalidArgumentException
74
	 * @since 11.0.0
75
	 */
76
	public function parse($language, IEvent $event, IEvent $previousEvent = null) {
77
		if ($event->getApp() !== 'announcementcenter' || (
78
			$event->getSubject() !== 'announcementsubject' && // 3.1 and later
79
			strpos($event->getSubject(), 'announcementsubject#') !== 0) // 3.0 and before
80
		) {
81
			throw new \InvalidArgumentException();
82
		}
83
84
		$l = $this->languageFactory->get('announcementcenter', $language);
85
86
		if (method_exists($this->activityManager, 'getRequirePNG') && $this->activityManager->getRequirePNG()) {
87
			$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('announcementcenter', 'announcementcenter-dark.png')));
88
		} else {
89
			$event->setIcon($this->url->getAbsoluteURL($this->url->imagePath('announcementcenter', 'announcementcenter-dark.svg')));
90
		}
91
92
		try {
93
			$announcement = $this->manager->getAnnouncement($event->getObjectId(), true, false, false);
94
95
			$parsedParameters = $this->getParameters($event, $announcement);
96 View Code Duplication
			if ($parsedParameters['actor']['id'] === $this->activityManager->getCurrentUserId()) {
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
				$subject = $l->t('You announced {announcement}');
98
				unset($parsedParameters['actor']);
99
			} else {
100
				$subject = $l->t('{actor} announced {announcement}');
101
			}
102
			$event->setParsedMessage($announcement['message']);
103
		} catch (\InvalidArgumentException $e) {
104
			$parsedParameters = $this->getParameters($event, []);
105 View Code Duplication
			if ($parsedParameters['actor']['id'] === $this->activityManager->getCurrentUserId()) {
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...
106
				$subject = $l->t('You posted an announcement');
107
				unset($parsedParameters['actor']);
108
			} else {
109
				$subject = $l->t('{actor} posted an announcement');
110
			}
111
112
			$event->setParsedMessage($l->t('Announcement does not exist anymore'));
113
		}
114
115
116
		$this->setSubjects($event, $subject, $parsedParameters);
117
118
		return $event;
119
	}
120
121
	/**
122
	 * @param IEvent $event
123
	 * @param array $announcement
124
	 * @return array
125
	 */
126
	protected function getParameters(IEvent $event, array $announcement) {
127
		$parameters = $event->getSubjectParameters();
128
129
		if (!empty($announcement)) {
130
			return [
131
				'actor' => $this->generateUserParameter($parameters[0]),
132
				'announcement' => $this->generateAnnouncementParameter($announcement),
133
			];
134
		} else {
135
			return [
136
				'actor' => $this->generateUserParameter($parameters[0]),
137
			];
138
		}
139
	}
140
141
	/**
142
	 * @param IEvent $event
143
	 * @param string $subject
144
	 * @param array $parameters
145
	 */
146
	protected function setSubjects(IEvent $event, $subject, array $parameters) {
147
		$placeholders = $replacements = [];
148
		foreach ($parameters as $placeholder => $parameter) {
149
			$placeholders[] = '{' . $placeholder . '}';
150
			$replacements[] = $parameter['name'];
151
		}
152
153
		$event->setParsedSubject(str_replace($placeholders, $replacements, $subject))
154
			->setRichSubject($subject, $parameters);
155
	}
156
157
	/**
158
	 * @param array $announcement
159
	 * @return array
160
	 */
161
	protected function generateAnnouncementParameter(array $announcement) {
162
		return [
163
			'type' => 'announcement',
164
			'id' => $announcement['id'],
165
			'name' => $announcement['subject'],
166
			'link' => $this->url->linkToRouteAbsolute('announcementcenter.page.index', [
167
				'announcement' => $announcement['id'],
168
			]),
169
		];
170
	}
171
172
	/**
173
	 * @param string $uid
174
	 * @return array
175
	 */
176
	protected function generateUserParameter($uid) {
177
		if (!isset($this->displayNames[$uid])) {
178
			$this->displayNames[$uid] = $this->getDisplayName($uid);
179
		}
180
181
		return [
182
			'type' => 'user',
183
			'id' => $uid,
184
			'name' => $this->displayNames[$uid],
185
		];
186
	}
187
188
	/**
189
	 * @param string $uid
190
	 * @return string
191
	 */
192
	protected function getDisplayName($uid) {
193
		$user = $this->userManager->get($uid);
194
		if ($user instanceof IUser) {
0 ignored issues
show
Bug introduced by
The class OCP\IUser 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...
195
			return $user->getDisplayName();
196
		} else {
197
			return $uid;
198
		}
199
	}
200
}
201