Completed
Push — master ( 5f2536...50c982 )
by Joas
91:18 queued 89:28
created

Provider::getParsedParameters()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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