Passed
Push — master ( 19aa92...2464a6 )
by Roeland
11:02 queued 10s
created

RuleMatcher::logCandidate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
nc 1
nop 0
1
<?php
2
3
declare(strict_types=1);
4
/**
5
 * @copyright Copyright (c) 2019 Arthur Schiwon <[email protected]>
6
 *
7
 * @author Arthur Schiwon <[email protected]>
8
 *
9
 * @license GNU AGPL version 3 or any later version
10
 *
11
 * This program is free software: you can redistribute it and/or modify
12
 * it under the terms of the GNU Affero General Public License as
13
 * published by the Free Software Foundation, either version 3 of the
14
 * License, or (at your option) any later version.
15
 *
16
 * This program is distributed in the hope that it will be useful,
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19
 * GNU Affero General Public License for more details.
20
 *
21
 * You should have received a copy of the GNU Affero General Public License
22
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23
 *
24
 */
25
26
namespace OCA\WorkflowEngine\Service;
27
28
use OCA\WorkflowEngine\Helper\LogContext;
29
use OCA\WorkflowEngine\Helper\ScopeContext;
30
use OCA\WorkflowEngine\Manager;
31
use OCP\AppFramework\QueryException;
32
use OCP\Files\Storage\IStorage;
33
use OCP\IL10N;
34
use OCP\IServerContainer;
35
use OCP\IUserSession;
36
use OCP\WorkflowEngine\ICheck;
37
use OCP\WorkflowEngine\IEntity;
38
use OCP\WorkflowEngine\IEntityCheck;
39
use OCP\WorkflowEngine\IFileCheck;
40
use OCP\WorkflowEngine\IManager;
41
use OCP\WorkflowEngine\IOperation;
42
use OCP\WorkflowEngine\IRuleMatcher;
43
use RuntimeException;
44
45
class RuleMatcher implements IRuleMatcher {
46
47
	/** @var IUserSession */
48
	protected $session;
49
	/** @var IManager */
50
	protected $manager;
51
	/** @var array */
52
	protected $contexts;
53
	/** @var IServerContainer */
54
	protected $container;
55
	/** @var array */
56
	protected $fileInfo = [];
57
	/** @var IL10N */
58
	protected $l;
59
	/** @var IOperation */
60
	protected $operation;
61
	/** @var IEntity */
62
	protected $entity;
63
	/** @var Logger */
64
	protected $logger;
65
66
	public function __construct(
67
		IUserSession $session,
68
		IServerContainer $container,
69
		IL10N $l,
70
		Manager $manager,
71
		Logger $logger
72
	) {
73
		$this->session = $session;
74
		$this->manager = $manager;
75
		$this->container = $container;
76
		$this->l = $l;
77
		$this->logger = $logger;
78
	}
79
80
	public function setFileInfo(IStorage $storage, string $path, bool $isDir = false): void {
81
		$this->fileInfo['storage'] = $storage;
82
		$this->fileInfo['path'] = $path;
83
		$this->fileInfo['isDir'] = $isDir;
84
	}
85
86
	public function setEntitySubject(IEntity $entity, $subject): void {
87
		$this->contexts[get_class($entity)] = [$entity, $subject];
88
	}
89
90
	public function setOperation(IOperation $operation): void {
91
		if ($this->operation !== null) {
92
			throw new RuntimeException('This method must not be called more than once');
93
		}
94
		$this->operation = $operation;
95
	}
96
97
	public function setEntity(IEntity $entity): void {
98
		if ($this->entity !== null) {
99
			throw new RuntimeException('This method must not be called more than once');
100
		}
101
		$this->entity = $entity;
102
	}
103
104
	public function getEntity(): IEntity {
105
		if ($this->entity === null) {
106
			throw new \LogicException('Entity was not set yet');
107
		}
108
		return $this->entity;
109
	}
110
111
	public function getFlows(bool $returnFirstMatchingOperationOnly = true): array {
112
		if (!$this->operation) {
113
			throw new RuntimeException('Operation is not set');
114
		}
115
		return $this->getMatchingOperations(get_class($this->operation), $returnFirstMatchingOperationOnly);
116
	}
117
118
	public function getMatchingOperations(string $class, bool $returnFirstMatchingOperationOnly = true): array {
119
		$scopes[] = new ScopeContext(IManager::SCOPE_ADMIN);
0 ignored issues
show
Comprehensibility Best Practice introduced by
$scopes was never initialized. Although not strictly required by PHP, it is generally a good practice to add $scopes = array(); before regardless.
Loading history...
120
		$user = $this->session->getUser();
121
		if ($user !== null && $this->manager->isUserScopeEnabled()) {
0 ignored issues
show
Bug introduced by
The method isUserScopeEnabled() does not exist on OCP\WorkflowEngine\IManager. Since it exists in all sub-types, consider adding an abstract or default implementation to OCP\WorkflowEngine\IManager. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

121
		if ($user !== null && $this->manager->/** @scrutinizer ignore-call */ isUserScopeEnabled()) {
Loading history...
122
			$scopes[] = new ScopeContext(IManager::SCOPE_USER, $user->getUID());
123
		}
124
125
		$ctx = new LogContext();
126
		$ctx
127
			->setScopes($scopes)
128
			->setEntity($this->entity)
129
			->setOperation($this->operation);
130
		$this->logger->logFlowRequests($ctx);
131
132
		$operations = [];
133
		foreach ($scopes as $scope) {
134
			$operations = array_merge($operations, $this->manager->getOperations($class, $scope));
0 ignored issues
show
Bug introduced by
The method getOperations() does not exist on OCP\WorkflowEngine\IManager. Since it exists in all sub-types, consider adding an abstract or default implementation to OCP\WorkflowEngine\IManager. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

134
			$operations = array_merge($operations, $this->manager->/** @scrutinizer ignore-call */ getOperations($class, $scope));
Loading history...
135
		}
136
137
		if ($this->entity instanceof IEntity) {
0 ignored issues
show
introduced by
$this->entity is always a sub-type of OCP\WorkflowEngine\IEntity.
Loading history...
138
			/** @var ScopeContext[] $additionalScopes */
139
			$additionalScopes = $this->manager->getAllConfiguredScopesForOperation($class);
0 ignored issues
show
Bug introduced by
The method getAllConfiguredScopesForOperation() does not exist on OCP\WorkflowEngine\IManager. Since it exists in all sub-types, consider adding an abstract or default implementation to OCP\WorkflowEngine\IManager. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

139
			/** @scrutinizer ignore-call */ 
140
   $additionalScopes = $this->manager->getAllConfiguredScopesForOperation($class);
Loading history...
140
			foreach ($additionalScopes as $hash => $scopeCandidate) {
141
				if ($scopeCandidate->getScope() !== IManager::SCOPE_USER || in_array($scopeCandidate, $scopes)) {
142
					continue;
143
				}
144
				if ($this->entity->isLegitimatedForUserId($scopeCandidate->getScopeId())) {
145
					$ctx = new LogContext();
146
					$ctx
147
						->setScopes([$scopeCandidate])
148
						->setEntity($this->entity)
149
						->setOperation($this->operation);
150
					$this->logger->logScopeExpansion($ctx);
151
					$operations = array_merge($operations, $this->manager->getOperations($class, $scopeCandidate));
152
				}
153
			}
154
		}
155
156
		$matches = [];
157
		foreach ($operations as $operation) {
158
			$checkIds = json_decode($operation['checks'], true);
159
			$checks = $this->manager->getChecks($checkIds);
0 ignored issues
show
Bug introduced by
The method getChecks() does not exist on OCP\WorkflowEngine\IManager. Since it exists in all sub-types, consider adding an abstract or default implementation to OCP\WorkflowEngine\IManager. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

159
			/** @scrutinizer ignore-call */ 
160
   $checks = $this->manager->getChecks($checkIds);
Loading history...
160
161
			foreach ($checks as $check) {
162
				if (!$this->check($check)) {
163
					// Check did not match, continue with the next operation
164
					continue 2;
165
				}
166
			}
167
168
			$ctx = new LogContext();
169
			$ctx
170
				->setEntity($this->entity)
171
				->setOperation($this->operation)
172
				->setConfiguration($operation);
173
			$this->logger->logPassedCheck($ctx);
174
175
			if ($returnFirstMatchingOperationOnly) {
176
				$ctx = new LogContext();
177
				$ctx
178
					->setEntity($this->entity)
179
					->setOperation($this->operation)
180
					->setConfiguration($operation);
181
				$this->logger->logRunSingle($ctx);
182
				return $operation;
183
			}
184
			$matches[] = $operation;
185
		}
186
187
		$ctx = new LogContext();
188
		$ctx
189
			->setEntity($this->entity)
190
			->setOperation($this->operation);
191
		if (!empty($matches)) {
192
			$ctx->setConfiguration($matches);
193
			$this->logger->logRunAll($ctx);
194
		} else {
195
			$this->logger->logRunNone($ctx);
196
		}
197
198
		return $matches;
199
	}
200
201
	/**
202
	 * @param array $check
203
	 * @return bool
204
	 */
205
	public function check(array $check) {
206
		try {
207
			$checkInstance = $this->container->query($check['class']);
208
		} catch (QueryException $e) {
209
			// Check does not exist, assume it matches.
210
			return true;
211
		}
212
213
		if ($checkInstance instanceof IFileCheck) {
214
			if (empty($this->fileInfo)) {
215
				throw new RuntimeException('Must set file info before running the check');
216
			}
217
			$checkInstance->setFileInfo($this->fileInfo['storage'], $this->fileInfo['path'], $this->fileInfo['isDir']);
218
		} elseif ($checkInstance instanceof IEntityCheck) {
219
			foreach ($this->contexts as $entityInfo) {
220
				list($entity, $subject) = $entityInfo;
221
				$checkInstance->setEntitySubject($entity, $subject);
222
			}
223
		} elseif (!$checkInstance instanceof ICheck) {
224
			// Check is invalid
225
			throw new \UnexpectedValueException($this->l->t('Check %s is invalid or does not exist', $check['class']));
226
		}
227
		return $checkInstance->executeCheck($check['operator'], $check['value']);
228
	}
229
}
230