Completed
Push — master ( 351351...40b79f )
by Joas
28:10
created
tests/lib/Preview/GeneratorTest.php 1 patch
Indentation   +425 added lines, -425 removed lines patch added patch discarded remove patch
@@ -33,429 +33,429 @@
 block discarded – undo
33 33
 }
34 34
 
35 35
 class GeneratorTest extends TestCase {
36
-	private IConfig&MockObject $config;
37
-	private IPreview&MockObject $previewManager;
38
-	private GeneratorHelper&MockObject $helper;
39
-	private IEventDispatcher&MockObject $eventDispatcher;
40
-	private Generator $generator;
41
-	private LoggerInterface&MockObject $logger;
42
-	private StorageFactory&MockObject $storageFactory;
43
-	private PreviewMapper&MockObject $previewMapper;
44
-
45
-	protected function setUp(): void {
46
-		parent::setUp();
47
-
48
-		$this->config = $this->createMock(IConfig::class);
49
-		$this->previewManager = $this->createMock(IPreview::class);
50
-		$this->helper = $this->createMock(GeneratorHelper::class);
51
-		$this->eventDispatcher = $this->createMock(IEventDispatcher::class);
52
-		$this->logger = $this->createMock(LoggerInterface::class);
53
-		$this->previewMapper = $this->createMock(PreviewMapper::class);
54
-		$this->storageFactory = $this->createMock(StorageFactory::class);
55
-
56
-		$this->generator = new Generator(
57
-			$this->config,
58
-			$this->previewManager,
59
-			$this->helper,
60
-			$this->eventDispatcher,
61
-			$this->logger,
62
-			$this->previewMapper,
63
-			$this->storageFactory,
64
-		);
65
-	}
66
-
67
-	private function getFile(int $fileId, string $mimeType, bool $hasVersion = false): File {
68
-		$mountPoint = $this->createMock(IMountPoint::class);
69
-		$mountPoint->method('getNumericStorageId')->willReturn(42);
70
-		if ($hasVersion) {
71
-			$file = $this->createMock(VersionedPreviewFile::class);
72
-			$file->method('getPreviewVersion')->willReturn('abc');
73
-		} else {
74
-			$file = $this->createMock(File::class);
75
-		}
76
-		$file->method('isReadable')
77
-			->willReturn(true);
78
-		$file->method('getMimeType')
79
-			->willReturn($mimeType);
80
-		$file->method('getId')
81
-			->willReturn($fileId);
82
-		$file->method('getMountPoint')
83
-			->willReturn($mountPoint);
84
-		return $file;
85
-	}
86
-
87
-	#[TestWith([true])]
88
-	#[TestWith([false])]
89
-	public function testGetCachedPreview(bool $hasPreview): void {
90
-		$file = $this->getFile(42, 'myMimeType', $hasPreview);
91
-
92
-		$this->previewManager->method('isMimeSupported')
93
-			->with($this->equalTo('myMimeType'))
94
-			->willReturn(true);
95
-
96
-		$maxPreview = new Preview();
97
-		$maxPreview->setWidth(1000);
98
-		$maxPreview->setHeight(1000);
99
-		$maxPreview->setMax(true);
100
-		$maxPreview->setSize(1000);
101
-		$maxPreview->setCropped(false);
102
-		$maxPreview->setStorageId(1);
103
-		$maxPreview->setVersion($hasPreview ? 'abc' : null);
104
-		$maxPreview->setMimeType('image/png');
105
-
106
-		$previewFile = new Preview();
107
-		$previewFile->setWidth(256);
108
-		$previewFile->setHeight(256);
109
-		$previewFile->setMax(false);
110
-		$previewFile->setSize(1000);
111
-		$previewFile->setVersion($hasPreview ? 'abc' : null);
112
-		$previewFile->setCropped(false);
113
-		$previewFile->setStorageId(1);
114
-		$previewFile->setMimeType('image/png');
115
-
116
-		$this->previewMapper->method('getAvailablePreviews')
117
-			->with($this->equalTo([42]))
118
-			->willReturn([42 => [
119
-				$maxPreview,
120
-				$previewFile,
121
-			]]);
122
-
123
-		$this->eventDispatcher->expects($this->once())
124
-			->method('dispatchTyped')
125
-			->with(new BeforePreviewFetchedEvent($file, 100, 100, false, IPreview::MODE_FILL, null));
126
-
127
-		$result = $this->generator->getPreview($file, 100, 100);
128
-		$this->assertSame($hasPreview ? 'abc-256-256.png' : '256-256.png', $result->getName());
129
-		$this->assertSame(1000, $result->getSize());
130
-	}
131
-
132
-	#[TestWith([true])]
133
-	#[TestWith([false])]
134
-	public function testGetNewPreview(bool $hasVersion): void {
135
-		$file = $this->getFile(42, 'myMimeType', $hasVersion);
136
-
137
-		$this->previewManager->method('isMimeSupported')
138
-			->with($this->equalTo('myMimeType'))
139
-			->willReturn(true);
140
-
141
-		$this->previewMapper->method('getAvailablePreviews')
142
-			->with($this->equalTo([42]))
143
-			->willReturn([42 => []]);
144
-
145
-		$this->config->method('getSystemValueString')
146
-			->willReturnCallback(function ($key, $default) {
147
-				return $default;
148
-			});
149
-
150
-		$this->config->method('getSystemValueInt')
151
-			->willReturnCallback(function ($key, $default) {
152
-				return $default;
153
-			});
154
-
155
-		$invalidProvider = $this->createMock(IProviderV2::class);
156
-		$invalidProvider->method('isAvailable')
157
-			->willReturn(true);
158
-		$unavailableProvider = $this->createMock(IProviderV2::class);
159
-		$unavailableProvider->method('isAvailable')
160
-			->willReturn(false);
161
-		$validProvider = $this->createMock(IProviderV2::class);
162
-		$validProvider->method('isAvailable')
163
-			->with($file)
164
-			->willReturn(true);
165
-
166
-		$this->previewManager->method('getProviders')
167
-			->willReturn([
168
-				'/image\/png/' => ['wrongProvider'],
169
-				'/myMimeType/' => ['brokenProvider', 'invalidProvider', 'unavailableProvider', 'validProvider'],
170
-			]);
171
-
172
-		$this->helper->method('getProvider')
173
-			->willReturnCallback(function ($provider) use ($invalidProvider, $validProvider, $unavailableProvider) {
174
-				if ($provider === 'wrongProvider') {
175
-					$this->fail('Wrongprovider should not be constructed!');
176
-				} elseif ($provider === 'brokenProvider') {
177
-					return false;
178
-				} elseif ($provider === 'invalidProvider') {
179
-					return $invalidProvider;
180
-				} elseif ($provider === 'validProvider') {
181
-					return $validProvider;
182
-				} elseif ($provider === 'unavailableProvider') {
183
-					return $unavailableProvider;
184
-				}
185
-				$this->fail('Unexpected provider requested');
186
-			});
187
-
188
-		$image = $this->createMock(IImage::class);
189
-		$image->method('width')->willReturn(2048);
190
-		$image->method('height')->willReturn(2048);
191
-		$image->method('valid')->willReturn(true);
192
-		$image->method('dataMimeType')->willReturn('image/png');
193
-
194
-		$this->helper->method('getThumbnail')
195
-			->willReturnCallback(function ($provider, $file, $x, $y) use ($invalidProvider, $validProvider, $image): false|IImage {
196
-				if ($provider === $validProvider) {
197
-					return $image;
198
-				} else {
199
-					return false;
200
-				}
201
-			});
202
-
203
-		$image->method('data')
204
-			->willReturn('my data');
205
-
206
-		$this->previewMapper->method('insert')
207
-			->willReturnCallback(fn (Preview $preview): Preview => $preview);
208
-
209
-		$this->previewMapper->method('update')
210
-			->willReturnCallback(fn (Preview $preview): Preview => $preview);
211
-
212
-		$this->storageFactory->method('writePreview')
213
-			->willReturnCallback(function (Preview $preview, mixed $data) use ($hasVersion): int {
214
-				$data = stream_get_contents($data);
215
-				if ($hasVersion) {
216
-					switch ($preview->getName()) {
217
-						case 'abc-2048-2048-max.png':
218
-							$this->assertSame('my data', $data);
219
-							return 1000;
220
-						case 'abc-256-256.png':
221
-							$this->assertSame('my resized data', $data);
222
-							return 1000;
223
-					}
224
-				} else {
225
-					switch ($preview->getName()) {
226
-						case '2048-2048-max.png':
227
-							$this->assertSame('my data', $data);
228
-							return 1000;
229
-						case '256-256.png':
230
-							$this->assertSame('my resized data', $data);
231
-							return 1000;
232
-					}
233
-				}
234
-				$this->fail('file name is wrong:' . $preview->getName());
235
-			});
236
-
237
-		$image = $this->getMockImage(2048, 2048, 'my resized data');
238
-		$this->helper->method('getImage')
239
-			->willReturn($image);
240
-
241
-		$this->eventDispatcher->expects($this->once())
242
-			->method('dispatchTyped')
243
-			->with(new BeforePreviewFetchedEvent($file, 100, 100, false, IPreview::MODE_FILL, null));
244
-
245
-		$result = $this->generator->getPreview($file, 100, 100);
246
-		$this->assertSame($hasVersion ? 'abc-256-256.png' : '256-256.png', $result->getName());
247
-		$this->assertSame(1000, $result->getSize());
248
-	}
249
-
250
-	public function testInvalidMimeType(): void {
251
-		$this->expectException(NotFoundException::class);
252
-
253
-		$file = $this->getFile(42, 'invalidType');
254
-
255
-		$this->previewManager->method('isMimeSupported')
256
-			->with('invalidType')
257
-			->willReturn(false);
258
-
259
-		$maxPreview = new Preview();
260
-		$maxPreview->setWidth(2048);
261
-		$maxPreview->setHeight(2048);
262
-		$maxPreview->setMax(true);
263
-		$maxPreview->setSize(1000);
264
-		$maxPreview->setVersion(null);
265
-		$maxPreview->setMimetype('image/png');
266
-
267
-		$this->previewMapper->method('getAvailablePreviews')
268
-			->with($this->equalTo([42]))
269
-			->willReturn([42 => [
270
-				$maxPreview,
271
-			]]);
272
-
273
-		$this->eventDispatcher->expects($this->once())
274
-			->method('dispatchTyped')
275
-			->with(new BeforePreviewFetchedEvent($file, 1024, 512, true, IPreview::MODE_COVER, 'invalidType'));
276
-
277
-		$this->generator->getPreview($file, 1024, 512, true, IPreview::MODE_COVER, 'invalidType');
278
-	}
279
-
280
-	public function testReturnCachedPreviewsWithoutCheckingSupportedMimetype(): void {
281
-		$file = $this->getFile(42, 'myMimeType');
282
-
283
-		$maxPreview = new Preview();
284
-		$maxPreview->setWidth(2048);
285
-		$maxPreview->setHeight(2048);
286
-		$maxPreview->setMax(true);
287
-		$maxPreview->setSize(1000);
288
-		$maxPreview->setVersion(null);
289
-		$maxPreview->setMimeType('image/png');
290
-
291
-		$previewFile = new Preview();
292
-		$previewFile->setWidth(1024);
293
-		$previewFile->setHeight(512);
294
-		$previewFile->setMax(false);
295
-		$previewFile->setSize(1000);
296
-		$previewFile->setCropped(true);
297
-		$previewFile->setVersion(null);
298
-		$previewFile->setMimeType('image/png');
299
-
300
-		$this->previewMapper->method('getAvailablePreviews')
301
-			->with($this->equalTo([42]))
302
-			->willReturn([42 => [
303
-				$maxPreview,
304
-				$previewFile,
305
-			]]);
306
-
307
-		$this->previewManager->expects($this->never())
308
-			->method('isMimeSupported');
309
-
310
-		$this->eventDispatcher->expects($this->once())
311
-			->method('dispatchTyped')
312
-			->with(new BeforePreviewFetchedEvent($file, 1024, 512, true, IPreview::MODE_COVER, 'invalidType'));
313
-
314
-		$result = $this->generator->getPreview($file, 1024, 512, true, IPreview::MODE_COVER, 'invalidType');
315
-		$this->assertSame('1024-512-crop.png', $result->getName());
316
-	}
317
-
318
-	public function testNoProvider(): void {
319
-		$file = $this->getFile(42, 'myMimeType');
320
-
321
-		$this->previewMapper->method('getAvailablePreviews')
322
-			->with($this->equalTo([42]))
323
-			->willReturn([42 => []]);
324
-
325
-		$this->previewManager->method('getProviders')
326
-			->willReturn([]);
327
-
328
-		$this->eventDispatcher->expects($this->once())
329
-			->method('dispatchTyped')
330
-			->with(new BeforePreviewFetchedEvent($file, 100, 100, false, IPreview::MODE_FILL, null));
331
-
332
-		$this->expectException(NotFoundException::class);
333
-		$this->generator->getPreview($file, 100, 100);
334
-	}
335
-
336
-	private function getMockImage(int $width, int $height, string $data = '') {
337
-		$image = $this->createMock(IImage::class);
338
-		$image->method('height')->willReturn($width);
339
-		$image->method('width')->willReturn($height);
340
-		$image->method('valid')->willReturn(true);
341
-		$image->method('dataMimeType')->willReturn('image/png');
342
-		$image->method('data')->willReturn($data);
343
-
344
-		$image->method('resizeCopy')->willReturnCallback(function ($size) use ($data) {
345
-			return $this->getMockImage($size, $size, $data);
346
-		});
347
-		$image->method('preciseResizeCopy')->willReturnCallback(function ($width, $height) use ($data) {
348
-			return $this->getMockImage($width, $height, $data);
349
-		});
350
-		$image->method('cropCopy')->willReturnCallback(function ($x, $y, $width, $height) use ($data) {
351
-			return $this->getMockImage($width, $height, $data);
352
-		});
353
-
354
-		return $image;
355
-	}
356
-
357
-	public static function dataSize(): array {
358
-		return [
359
-			[1024, 2048, 512, 512, false, IPreview::MODE_FILL, 256, 512],
360
-			[1024, 2048, 512, 512, false, IPreview::MODE_COVER, 512, 1024],
361
-			[1024, 2048, 512, 512, true, IPreview::MODE_FILL, 1024, 1024],
362
-			[1024, 2048, 512, 512, true, IPreview::MODE_COVER, 1024, 1024],
363
-
364
-			[1024, 2048, -1, 512, false, IPreview::MODE_COVER, 256, 512],
365
-			[1024, 2048, 512, -1, false, IPreview::MODE_FILL, 512, 1024],
366
-
367
-			[1024, 2048, 250, 1100, true, IPreview::MODE_COVER, 256, 1126],
368
-			[1024, 1100, 250, 1100, true, IPreview::MODE_COVER, 250, 1100],
369
-
370
-			[1024, 2048, 4096, 2048, false, IPreview::MODE_FILL, 1024, 2048],
371
-			[1024, 2048, 4096, 2048, false, IPreview::MODE_COVER, 1024, 2048],
372
-
373
-
374
-			[2048, 1024, 512, 512, false, IPreview::MODE_FILL, 512, 256],
375
-			[2048, 1024, 512, 512, false, IPreview::MODE_COVER, 1024, 512],
376
-			[2048, 1024, 512, 512, true, IPreview::MODE_FILL, 1024, 1024],
377
-			[2048, 1024, 512, 512, true, IPreview::MODE_COVER, 1024, 1024],
378
-
379
-			[2048, 1024, -1, 512, false, IPreview::MODE_FILL, 1024, 512],
380
-			[2048, 1024, 512, -1, false, IPreview::MODE_COVER, 512, 256],
381
-
382
-			[2048, 1024, 4096, 1024, true, IPreview::MODE_FILL, 2048, 512],
383
-			[2048, 1024, 4096, 1024, true, IPreview::MODE_COVER, 2048, 512],
384
-
385
-			//Test minimum size
386
-			[2048, 1024, 32, 32, false, IPreview::MODE_FILL, 64, 32],
387
-			[2048, 1024, 32, 32, false, IPreview::MODE_COVER, 64, 32],
388
-			[2048, 1024, 32, 32, true, IPreview::MODE_FILL, 64, 64],
389
-			[2048, 1024, 32, 32, true, IPreview::MODE_COVER, 64, 64],
390
-		];
391
-	}
392
-
393
-	#[DataProvider('dataSize')]
394
-	public function testCorrectSize(int $maxX, int $maxY, int $reqX, int $reqY, bool $crop, string $mode, int $expectedX, int $expectedY): void {
395
-		$file = $this->getFile(42, 'myMimeType');
396
-
397
-		$this->previewManager->method('isMimeSupported')
398
-			->with($this->equalTo('myMimeType'))
399
-			->willReturn(true);
400
-
401
-		$maxPreview = new Preview();
402
-		$maxPreview->setWidth($maxX);
403
-		$maxPreview->setHeight($maxY);
404
-		$maxPreview->setMax(true);
405
-		$maxPreview->setSize(1000);
406
-		$maxPreview->setVersion(null);
407
-		$maxPreview->setMimeType('image/png');
408
-
409
-		$this->assertSame($maxPreview->getName(), $maxX . '-' . $maxY . '-max.png');
410
-		$this->assertSame($maxPreview->getMimeType(), 'image/png');
411
-
412
-		$this->previewMapper->method('getAvailablePreviews')
413
-			->with($this->equalTo([42]))
414
-			->willReturn([42 => [
415
-				$maxPreview,
416
-			]]);
417
-
418
-		$filename = $expectedX . '-' . $expectedY;
419
-		if ($crop) {
420
-			$filename .= '-crop';
421
-		}
422
-		$filename .= '.png';
423
-
424
-		$image = $this->getMockImage($maxX, $maxY);
425
-		$this->helper->method('getImage')
426
-			->willReturn($image);
427
-
428
-		$this->previewMapper->method('insert')
429
-			->willReturnCallback(function (Preview $preview) use ($filename): Preview {
430
-				$this->assertSame($preview->getName(), $filename);
431
-				return $preview;
432
-			});
433
-
434
-		$this->previewMapper->method('update')
435
-			->willReturnCallback(fn (Preview $preview): Preview => $preview);
436
-
437
-		$this->storageFactory->method('writePreview')
438
-			->willReturn(1000);
439
-
440
-		$this->eventDispatcher->expects($this->once())
441
-			->method('dispatchTyped')
442
-			->with(new BeforePreviewFetchedEvent($file, $reqX, $reqY, $crop, $mode, null));
443
-
444
-		$result = $this->generator->getPreview($file, $reqX, $reqY, $crop, $mode);
445
-		if ($expectedX === $maxX && $expectedY === $maxY) {
446
-			$this->assertSame($maxPreview->getName(), $result->getName());
447
-		} else {
448
-			$this->assertSame($filename, $result->getName());
449
-		}
450
-	}
451
-
452
-	public function testUnreadbleFile(): void {
453
-		$file = $this->createMock(File::class);
454
-		$file->method('isReadable')
455
-			->willReturn(false);
456
-
457
-		$this->expectException(NotFoundException::class);
458
-
459
-		$this->generator->getPreview($file, 100, 100, false);
460
-	}
36
+    private IConfig&MockObject $config;
37
+    private IPreview&MockObject $previewManager;
38
+    private GeneratorHelper&MockObject $helper;
39
+    private IEventDispatcher&MockObject $eventDispatcher;
40
+    private Generator $generator;
41
+    private LoggerInterface&MockObject $logger;
42
+    private StorageFactory&MockObject $storageFactory;
43
+    private PreviewMapper&MockObject $previewMapper;
44
+
45
+    protected function setUp(): void {
46
+        parent::setUp();
47
+
48
+        $this->config = $this->createMock(IConfig::class);
49
+        $this->previewManager = $this->createMock(IPreview::class);
50
+        $this->helper = $this->createMock(GeneratorHelper::class);
51
+        $this->eventDispatcher = $this->createMock(IEventDispatcher::class);
52
+        $this->logger = $this->createMock(LoggerInterface::class);
53
+        $this->previewMapper = $this->createMock(PreviewMapper::class);
54
+        $this->storageFactory = $this->createMock(StorageFactory::class);
55
+
56
+        $this->generator = new Generator(
57
+            $this->config,
58
+            $this->previewManager,
59
+            $this->helper,
60
+            $this->eventDispatcher,
61
+            $this->logger,
62
+            $this->previewMapper,
63
+            $this->storageFactory,
64
+        );
65
+    }
66
+
67
+    private function getFile(int $fileId, string $mimeType, bool $hasVersion = false): File {
68
+        $mountPoint = $this->createMock(IMountPoint::class);
69
+        $mountPoint->method('getNumericStorageId')->willReturn(42);
70
+        if ($hasVersion) {
71
+            $file = $this->createMock(VersionedPreviewFile::class);
72
+            $file->method('getPreviewVersion')->willReturn('abc');
73
+        } else {
74
+            $file = $this->createMock(File::class);
75
+        }
76
+        $file->method('isReadable')
77
+            ->willReturn(true);
78
+        $file->method('getMimeType')
79
+            ->willReturn($mimeType);
80
+        $file->method('getId')
81
+            ->willReturn($fileId);
82
+        $file->method('getMountPoint')
83
+            ->willReturn($mountPoint);
84
+        return $file;
85
+    }
86
+
87
+    #[TestWith([true])]
88
+    #[TestWith([false])]
89
+    public function testGetCachedPreview(bool $hasPreview): void {
90
+        $file = $this->getFile(42, 'myMimeType', $hasPreview);
91
+
92
+        $this->previewManager->method('isMimeSupported')
93
+            ->with($this->equalTo('myMimeType'))
94
+            ->willReturn(true);
95
+
96
+        $maxPreview = new Preview();
97
+        $maxPreview->setWidth(1000);
98
+        $maxPreview->setHeight(1000);
99
+        $maxPreview->setMax(true);
100
+        $maxPreview->setSize(1000);
101
+        $maxPreview->setCropped(false);
102
+        $maxPreview->setStorageId(1);
103
+        $maxPreview->setVersion($hasPreview ? 'abc' : null);
104
+        $maxPreview->setMimeType('image/png');
105
+
106
+        $previewFile = new Preview();
107
+        $previewFile->setWidth(256);
108
+        $previewFile->setHeight(256);
109
+        $previewFile->setMax(false);
110
+        $previewFile->setSize(1000);
111
+        $previewFile->setVersion($hasPreview ? 'abc' : null);
112
+        $previewFile->setCropped(false);
113
+        $previewFile->setStorageId(1);
114
+        $previewFile->setMimeType('image/png');
115
+
116
+        $this->previewMapper->method('getAvailablePreviews')
117
+            ->with($this->equalTo([42]))
118
+            ->willReturn([42 => [
119
+                $maxPreview,
120
+                $previewFile,
121
+            ]]);
122
+
123
+        $this->eventDispatcher->expects($this->once())
124
+            ->method('dispatchTyped')
125
+            ->with(new BeforePreviewFetchedEvent($file, 100, 100, false, IPreview::MODE_FILL, null));
126
+
127
+        $result = $this->generator->getPreview($file, 100, 100);
128
+        $this->assertSame($hasPreview ? 'abc-256-256.png' : '256-256.png', $result->getName());
129
+        $this->assertSame(1000, $result->getSize());
130
+    }
131
+
132
+    #[TestWith([true])]
133
+    #[TestWith([false])]
134
+    public function testGetNewPreview(bool $hasVersion): void {
135
+        $file = $this->getFile(42, 'myMimeType', $hasVersion);
136
+
137
+        $this->previewManager->method('isMimeSupported')
138
+            ->with($this->equalTo('myMimeType'))
139
+            ->willReturn(true);
140
+
141
+        $this->previewMapper->method('getAvailablePreviews')
142
+            ->with($this->equalTo([42]))
143
+            ->willReturn([42 => []]);
144
+
145
+        $this->config->method('getSystemValueString')
146
+            ->willReturnCallback(function ($key, $default) {
147
+                return $default;
148
+            });
149
+
150
+        $this->config->method('getSystemValueInt')
151
+            ->willReturnCallback(function ($key, $default) {
152
+                return $default;
153
+            });
154
+
155
+        $invalidProvider = $this->createMock(IProviderV2::class);
156
+        $invalidProvider->method('isAvailable')
157
+            ->willReturn(true);
158
+        $unavailableProvider = $this->createMock(IProviderV2::class);
159
+        $unavailableProvider->method('isAvailable')
160
+            ->willReturn(false);
161
+        $validProvider = $this->createMock(IProviderV2::class);
162
+        $validProvider->method('isAvailable')
163
+            ->with($file)
164
+            ->willReturn(true);
165
+
166
+        $this->previewManager->method('getProviders')
167
+            ->willReturn([
168
+                '/image\/png/' => ['wrongProvider'],
169
+                '/myMimeType/' => ['brokenProvider', 'invalidProvider', 'unavailableProvider', 'validProvider'],
170
+            ]);
171
+
172
+        $this->helper->method('getProvider')
173
+            ->willReturnCallback(function ($provider) use ($invalidProvider, $validProvider, $unavailableProvider) {
174
+                if ($provider === 'wrongProvider') {
175
+                    $this->fail('Wrongprovider should not be constructed!');
176
+                } elseif ($provider === 'brokenProvider') {
177
+                    return false;
178
+                } elseif ($provider === 'invalidProvider') {
179
+                    return $invalidProvider;
180
+                } elseif ($provider === 'validProvider') {
181
+                    return $validProvider;
182
+                } elseif ($provider === 'unavailableProvider') {
183
+                    return $unavailableProvider;
184
+                }
185
+                $this->fail('Unexpected provider requested');
186
+            });
187
+
188
+        $image = $this->createMock(IImage::class);
189
+        $image->method('width')->willReturn(2048);
190
+        $image->method('height')->willReturn(2048);
191
+        $image->method('valid')->willReturn(true);
192
+        $image->method('dataMimeType')->willReturn('image/png');
193
+
194
+        $this->helper->method('getThumbnail')
195
+            ->willReturnCallback(function ($provider, $file, $x, $y) use ($invalidProvider, $validProvider, $image): false|IImage {
196
+                if ($provider === $validProvider) {
197
+                    return $image;
198
+                } else {
199
+                    return false;
200
+                }
201
+            });
202
+
203
+        $image->method('data')
204
+            ->willReturn('my data');
205
+
206
+        $this->previewMapper->method('insert')
207
+            ->willReturnCallback(fn (Preview $preview): Preview => $preview);
208
+
209
+        $this->previewMapper->method('update')
210
+            ->willReturnCallback(fn (Preview $preview): Preview => $preview);
211
+
212
+        $this->storageFactory->method('writePreview')
213
+            ->willReturnCallback(function (Preview $preview, mixed $data) use ($hasVersion): int {
214
+                $data = stream_get_contents($data);
215
+                if ($hasVersion) {
216
+                    switch ($preview->getName()) {
217
+                        case 'abc-2048-2048-max.png':
218
+                            $this->assertSame('my data', $data);
219
+                            return 1000;
220
+                        case 'abc-256-256.png':
221
+                            $this->assertSame('my resized data', $data);
222
+                            return 1000;
223
+                    }
224
+                } else {
225
+                    switch ($preview->getName()) {
226
+                        case '2048-2048-max.png':
227
+                            $this->assertSame('my data', $data);
228
+                            return 1000;
229
+                        case '256-256.png':
230
+                            $this->assertSame('my resized data', $data);
231
+                            return 1000;
232
+                    }
233
+                }
234
+                $this->fail('file name is wrong:' . $preview->getName());
235
+            });
236
+
237
+        $image = $this->getMockImage(2048, 2048, 'my resized data');
238
+        $this->helper->method('getImage')
239
+            ->willReturn($image);
240
+
241
+        $this->eventDispatcher->expects($this->once())
242
+            ->method('dispatchTyped')
243
+            ->with(new BeforePreviewFetchedEvent($file, 100, 100, false, IPreview::MODE_FILL, null));
244
+
245
+        $result = $this->generator->getPreview($file, 100, 100);
246
+        $this->assertSame($hasVersion ? 'abc-256-256.png' : '256-256.png', $result->getName());
247
+        $this->assertSame(1000, $result->getSize());
248
+    }
249
+
250
+    public function testInvalidMimeType(): void {
251
+        $this->expectException(NotFoundException::class);
252
+
253
+        $file = $this->getFile(42, 'invalidType');
254
+
255
+        $this->previewManager->method('isMimeSupported')
256
+            ->with('invalidType')
257
+            ->willReturn(false);
258
+
259
+        $maxPreview = new Preview();
260
+        $maxPreview->setWidth(2048);
261
+        $maxPreview->setHeight(2048);
262
+        $maxPreview->setMax(true);
263
+        $maxPreview->setSize(1000);
264
+        $maxPreview->setVersion(null);
265
+        $maxPreview->setMimetype('image/png');
266
+
267
+        $this->previewMapper->method('getAvailablePreviews')
268
+            ->with($this->equalTo([42]))
269
+            ->willReturn([42 => [
270
+                $maxPreview,
271
+            ]]);
272
+
273
+        $this->eventDispatcher->expects($this->once())
274
+            ->method('dispatchTyped')
275
+            ->with(new BeforePreviewFetchedEvent($file, 1024, 512, true, IPreview::MODE_COVER, 'invalidType'));
276
+
277
+        $this->generator->getPreview($file, 1024, 512, true, IPreview::MODE_COVER, 'invalidType');
278
+    }
279
+
280
+    public function testReturnCachedPreviewsWithoutCheckingSupportedMimetype(): void {
281
+        $file = $this->getFile(42, 'myMimeType');
282
+
283
+        $maxPreview = new Preview();
284
+        $maxPreview->setWidth(2048);
285
+        $maxPreview->setHeight(2048);
286
+        $maxPreview->setMax(true);
287
+        $maxPreview->setSize(1000);
288
+        $maxPreview->setVersion(null);
289
+        $maxPreview->setMimeType('image/png');
290
+
291
+        $previewFile = new Preview();
292
+        $previewFile->setWidth(1024);
293
+        $previewFile->setHeight(512);
294
+        $previewFile->setMax(false);
295
+        $previewFile->setSize(1000);
296
+        $previewFile->setCropped(true);
297
+        $previewFile->setVersion(null);
298
+        $previewFile->setMimeType('image/png');
299
+
300
+        $this->previewMapper->method('getAvailablePreviews')
301
+            ->with($this->equalTo([42]))
302
+            ->willReturn([42 => [
303
+                $maxPreview,
304
+                $previewFile,
305
+            ]]);
306
+
307
+        $this->previewManager->expects($this->never())
308
+            ->method('isMimeSupported');
309
+
310
+        $this->eventDispatcher->expects($this->once())
311
+            ->method('dispatchTyped')
312
+            ->with(new BeforePreviewFetchedEvent($file, 1024, 512, true, IPreview::MODE_COVER, 'invalidType'));
313
+
314
+        $result = $this->generator->getPreview($file, 1024, 512, true, IPreview::MODE_COVER, 'invalidType');
315
+        $this->assertSame('1024-512-crop.png', $result->getName());
316
+    }
317
+
318
+    public function testNoProvider(): void {
319
+        $file = $this->getFile(42, 'myMimeType');
320
+
321
+        $this->previewMapper->method('getAvailablePreviews')
322
+            ->with($this->equalTo([42]))
323
+            ->willReturn([42 => []]);
324
+
325
+        $this->previewManager->method('getProviders')
326
+            ->willReturn([]);
327
+
328
+        $this->eventDispatcher->expects($this->once())
329
+            ->method('dispatchTyped')
330
+            ->with(new BeforePreviewFetchedEvent($file, 100, 100, false, IPreview::MODE_FILL, null));
331
+
332
+        $this->expectException(NotFoundException::class);
333
+        $this->generator->getPreview($file, 100, 100);
334
+    }
335
+
336
+    private function getMockImage(int $width, int $height, string $data = '') {
337
+        $image = $this->createMock(IImage::class);
338
+        $image->method('height')->willReturn($width);
339
+        $image->method('width')->willReturn($height);
340
+        $image->method('valid')->willReturn(true);
341
+        $image->method('dataMimeType')->willReturn('image/png');
342
+        $image->method('data')->willReturn($data);
343
+
344
+        $image->method('resizeCopy')->willReturnCallback(function ($size) use ($data) {
345
+            return $this->getMockImage($size, $size, $data);
346
+        });
347
+        $image->method('preciseResizeCopy')->willReturnCallback(function ($width, $height) use ($data) {
348
+            return $this->getMockImage($width, $height, $data);
349
+        });
350
+        $image->method('cropCopy')->willReturnCallback(function ($x, $y, $width, $height) use ($data) {
351
+            return $this->getMockImage($width, $height, $data);
352
+        });
353
+
354
+        return $image;
355
+    }
356
+
357
+    public static function dataSize(): array {
358
+        return [
359
+            [1024, 2048, 512, 512, false, IPreview::MODE_FILL, 256, 512],
360
+            [1024, 2048, 512, 512, false, IPreview::MODE_COVER, 512, 1024],
361
+            [1024, 2048, 512, 512, true, IPreview::MODE_FILL, 1024, 1024],
362
+            [1024, 2048, 512, 512, true, IPreview::MODE_COVER, 1024, 1024],
363
+
364
+            [1024, 2048, -1, 512, false, IPreview::MODE_COVER, 256, 512],
365
+            [1024, 2048, 512, -1, false, IPreview::MODE_FILL, 512, 1024],
366
+
367
+            [1024, 2048, 250, 1100, true, IPreview::MODE_COVER, 256, 1126],
368
+            [1024, 1100, 250, 1100, true, IPreview::MODE_COVER, 250, 1100],
369
+
370
+            [1024, 2048, 4096, 2048, false, IPreview::MODE_FILL, 1024, 2048],
371
+            [1024, 2048, 4096, 2048, false, IPreview::MODE_COVER, 1024, 2048],
372
+
373
+
374
+            [2048, 1024, 512, 512, false, IPreview::MODE_FILL, 512, 256],
375
+            [2048, 1024, 512, 512, false, IPreview::MODE_COVER, 1024, 512],
376
+            [2048, 1024, 512, 512, true, IPreview::MODE_FILL, 1024, 1024],
377
+            [2048, 1024, 512, 512, true, IPreview::MODE_COVER, 1024, 1024],
378
+
379
+            [2048, 1024, -1, 512, false, IPreview::MODE_FILL, 1024, 512],
380
+            [2048, 1024, 512, -1, false, IPreview::MODE_COVER, 512, 256],
381
+
382
+            [2048, 1024, 4096, 1024, true, IPreview::MODE_FILL, 2048, 512],
383
+            [2048, 1024, 4096, 1024, true, IPreview::MODE_COVER, 2048, 512],
384
+
385
+            //Test minimum size
386
+            [2048, 1024, 32, 32, false, IPreview::MODE_FILL, 64, 32],
387
+            [2048, 1024, 32, 32, false, IPreview::MODE_COVER, 64, 32],
388
+            [2048, 1024, 32, 32, true, IPreview::MODE_FILL, 64, 64],
389
+            [2048, 1024, 32, 32, true, IPreview::MODE_COVER, 64, 64],
390
+        ];
391
+    }
392
+
393
+    #[DataProvider('dataSize')]
394
+    public function testCorrectSize(int $maxX, int $maxY, int $reqX, int $reqY, bool $crop, string $mode, int $expectedX, int $expectedY): void {
395
+        $file = $this->getFile(42, 'myMimeType');
396
+
397
+        $this->previewManager->method('isMimeSupported')
398
+            ->with($this->equalTo('myMimeType'))
399
+            ->willReturn(true);
400
+
401
+        $maxPreview = new Preview();
402
+        $maxPreview->setWidth($maxX);
403
+        $maxPreview->setHeight($maxY);
404
+        $maxPreview->setMax(true);
405
+        $maxPreview->setSize(1000);
406
+        $maxPreview->setVersion(null);
407
+        $maxPreview->setMimeType('image/png');
408
+
409
+        $this->assertSame($maxPreview->getName(), $maxX . '-' . $maxY . '-max.png');
410
+        $this->assertSame($maxPreview->getMimeType(), 'image/png');
411
+
412
+        $this->previewMapper->method('getAvailablePreviews')
413
+            ->with($this->equalTo([42]))
414
+            ->willReturn([42 => [
415
+                $maxPreview,
416
+            ]]);
417
+
418
+        $filename = $expectedX . '-' . $expectedY;
419
+        if ($crop) {
420
+            $filename .= '-crop';
421
+        }
422
+        $filename .= '.png';
423
+
424
+        $image = $this->getMockImage($maxX, $maxY);
425
+        $this->helper->method('getImage')
426
+            ->willReturn($image);
427
+
428
+        $this->previewMapper->method('insert')
429
+            ->willReturnCallback(function (Preview $preview) use ($filename): Preview {
430
+                $this->assertSame($preview->getName(), $filename);
431
+                return $preview;
432
+            });
433
+
434
+        $this->previewMapper->method('update')
435
+            ->willReturnCallback(fn (Preview $preview): Preview => $preview);
436
+
437
+        $this->storageFactory->method('writePreview')
438
+            ->willReturn(1000);
439
+
440
+        $this->eventDispatcher->expects($this->once())
441
+            ->method('dispatchTyped')
442
+            ->with(new BeforePreviewFetchedEvent($file, $reqX, $reqY, $crop, $mode, null));
443
+
444
+        $result = $this->generator->getPreview($file, $reqX, $reqY, $crop, $mode);
445
+        if ($expectedX === $maxX && $expectedY === $maxY) {
446
+            $this->assertSame($maxPreview->getName(), $result->getName());
447
+        } else {
448
+            $this->assertSame($filename, $result->getName());
449
+        }
450
+    }
451
+
452
+    public function testUnreadbleFile(): void {
453
+        $file = $this->createMock(File::class);
454
+        $file->method('isReadable')
455
+            ->willReturn(false);
456
+
457
+        $this->expectException(NotFoundException::class);
458
+
459
+        $this->generator->getPreview($file, 100, 100, false);
460
+    }
461 461
 }
Please login to merge, or discard this patch.
tests/lib/Preview/MovePreviewJobTest.php 1 patch
Indentation   +188 added lines, -188 removed lines patch added patch discarded remove patch
@@ -31,192 +31,192 @@
 block discarded – undo
31 31
 
32 32
 #[\PHPUnit\Framework\Attributes\Group('DB')]
33 33
 class MovePreviewJobTest extends TestCase {
34
-	private IAppData $previewAppData;
35
-	private PreviewMapper $previewMapper;
36
-	private IAppConfig&MockObject $appConfig;
37
-	private IConfig $config;
38
-	private StorageFactory $storageFactory;
39
-	private PreviewService $previewService;
40
-	private IDBConnection $db;
41
-	private IMimeTypeLoader&MockObject $mimeTypeLoader;
42
-	private IMimeTypeDetector&MockObject $mimeTypeDetector;
43
-	private LoggerInterface&MockObject $logger;
44
-
45
-	public function setUp(): void {
46
-		parent::setUp();
47
-		$this->previewAppData = Server::get(IAppDataFactory::class)->get('preview');
48
-		$this->previewMapper = Server::get(PreviewMapper::class);
49
-		$this->config = Server::get(IConfig::class);
50
-		$this->appConfig = $this->createMock(IAppConfig::class);
51
-		$this->appConfig->expects($this->any())
52
-			->method('getValueBool')
53
-			->willReturn(false);
54
-		$this->appConfig->expects($this->any())
55
-			->method('setValueBool')
56
-			->willReturn(true);
57
-		$this->storageFactory = Server::get(StorageFactory::class);
58
-		$this->previewService = Server::get(PreviewService::class);
59
-		$this->db = Server::get(IDBConnection::class);
60
-
61
-		$qb = $this->db->getQueryBuilder();
62
-		$qb->delete('filecache')
63
-			->where($qb->expr()->eq('fileid', $qb->createNamedParameter(5)))
64
-			->executeStatement();
65
-
66
-		$qb = $this->db->getQueryBuilder();
67
-		$qb->insert('filecache')
68
-			->values([
69
-				'fileid' => $qb->createNamedParameter(5),
70
-				'storage' => $qb->createNamedParameter(1),
71
-				'path' => $qb->createNamedParameter('test/abc'),
72
-				'path_hash' => $qb->createNamedParameter(md5('test')),
73
-				'parent' => $qb->createNamedParameter(0),
74
-				'name' => $qb->createNamedParameter('abc'),
75
-				'mimetype' => $qb->createNamedParameter(42),
76
-				'size' => $qb->createNamedParameter(1000),
77
-				'mtime' => $qb->createNamedParameter(1000),
78
-				'storage_mtime' => $qb->createNamedParameter(1000),
79
-				'encrypted' => $qb->createNamedParameter(0),
80
-				'unencrypted_size' => $qb->createNamedParameter(0),
81
-				'etag' => $qb->createNamedParameter('abcdefg'),
82
-				'permissions' => $qb->createNamedParameter(0),
83
-				'checksum' => $qb->createNamedParameter('abcdefg'),
84
-			])->executeStatement();
85
-
86
-		$this->mimeTypeDetector = $this->createMock(IMimeTypeDetector::class);
87
-		$this->mimeTypeDetector->method('detectPath')->willReturn('image/png');
88
-		$this->mimeTypeLoader = $this->createMock(IMimeTypeLoader::class);
89
-		$this->mimeTypeLoader->method('getId')->with('image/png')->willReturn(42);
90
-		$this->mimeTypeLoader->method('getMimetypeById')->with(42)->willReturn('image/png');
91
-		$this->logger = $this->createMock(LoggerInterface::class);
92
-	}
93
-
94
-	public function tearDown(): void {
95
-		foreach ($this->previewAppData->getDirectoryListing() as $folder) {
96
-			$folder->delete();
97
-		}
98
-		$this->previewService->deleteAll();
99
-
100
-		$qb = $this->db->getQueryBuilder();
101
-		$qb->delete('filecache')
102
-			->where($qb->expr()->eq('fileid', $qb->createNamedParameter(5)))
103
-			->executeStatement();
104
-	}
105
-
106
-	#[TestDox('Test the migration from the legacy flat hierarchy to the new database format')]
107
-	public function testMigrationLegacyPath(): void {
108
-		$folder = $this->previewAppData->newFolder('5');
109
-		$folder->newFile('64-64-crop.jpg', 'abcdefg');
110
-		$folder->newFile('128-128-crop.png', 'abcdefg');
111
-		$this->assertEquals(1, count($this->previewAppData->getDirectoryListing()));
112
-		$this->assertEquals(2, count($folder->getDirectoryListing()));
113
-		$this->assertEquals(0, count(iterator_to_array($this->previewMapper->getAvailablePreviewsForFile(5))));
114
-
115
-		$job = new MovePreviewJob(
116
-			Server::get(ITimeFactory::class),
117
-			$this->appConfig,
118
-			$this->config,
119
-			$this->previewMapper,
120
-			$this->storageFactory,
121
-			Server::get(IDBConnection::class),
122
-			Server::get(IRootFolder::class),
123
-			$this->mimeTypeDetector,
124
-			$this->mimeTypeLoader,
125
-			$this->logger,
126
-			Server::get(IAppDataFactory::class),
127
-		);
128
-		$this->invokePrivate($job, 'run', [[]]);
129
-		$this->assertEquals(0, count($this->previewAppData->getDirectoryListing()));
130
-		$this->assertEquals(2, count(iterator_to_array($this->previewMapper->getAvailablePreviewsForFile(5))));
131
-	}
132
-
133
-	private static function getInternalFolder(string $name): string {
134
-		return implode('/', str_split(substr(md5($name), 0, 7))) . '/' . $name;
135
-	}
136
-
137
-	#[TestDox("Test the migration from the 'new' nested hierarchy to the database format")]
138
-	public function testMigrationPath(): void {
139
-		$folder = $this->previewAppData->newFolder(self::getInternalFolder((string)5));
140
-		$folder->newFile('64-64-crop.jpg', 'abcdefg');
141
-		$folder->newFile('128-128-crop.png', 'abcdefg');
142
-
143
-		$folder = $this->previewAppData->getFolder(self::getInternalFolder((string)5));
144
-		$this->assertEquals(2, count($folder->getDirectoryListing()));
145
-		$this->assertEquals(0, count(iterator_to_array($this->previewMapper->getAvailablePreviewsForFile(5))));
146
-
147
-		$job = new MovePreviewJob(
148
-			Server::get(ITimeFactory::class),
149
-			$this->appConfig,
150
-			$this->config,
151
-			$this->previewMapper,
152
-			$this->storageFactory,
153
-			Server::get(IDBConnection::class),
154
-			Server::get(IRootFolder::class),
155
-			$this->mimeTypeDetector,
156
-			$this->mimeTypeLoader,
157
-			$this->logger,
158
-			Server::get(IAppDataFactory::class)
159
-		);
160
-		$this->invokePrivate($job, 'run', [[]]);
161
-		$this->assertEquals(0, count($this->previewAppData->getDirectoryListing()));
162
-		$this->assertEquals(2, count(iterator_to_array($this->previewMapper->getAvailablePreviewsForFile(5))));
163
-	}
164
-
165
-	#[TestDox("Test the migration from the 'new' nested hierarchy to the database format")]
166
-	public function testMigrationPathWithVersion(): void {
167
-		$folder = $this->previewAppData->newFolder(self::getInternalFolder((string)5));
168
-		// No version
169
-		$folder->newFile('128-128-crop.png', 'abcdefg');
170
-		$folder->newFile('256-256-max.png', 'abcdefg');
171
-		$folder->newFile('128-128.png', 'abcdefg');
172
-
173
-		// Version 1000
174
-		$folder->newFile('1000-128-128-crop.png', 'abcdefg');
175
-		$folder->newFile('1000-256-256-max.png', 'abcdefg');
176
-		$folder->newFile('1000-128-128.png', 'abcdefg');
177
-
178
-		// Version 1001
179
-		$folder->newFile('1001-128-128-crop.png', 'abcdefg');
180
-		$folder->newFile('1001-256-256-max.png', 'abcdefg');
181
-		$folder->newFile('1001-128-128.png', 'abcdefg');
182
-
183
-		$folder = $this->previewAppData->getFolder(self::getInternalFolder((string)5));
184
-		$this->assertEquals(9, count($folder->getDirectoryListing()));
185
-		$this->assertEquals(0, count(iterator_to_array($this->previewMapper->getAvailablePreviewsForFile(5))));
186
-
187
-		$job = new MovePreviewJob(
188
-			Server::get(ITimeFactory::class),
189
-			$this->appConfig,
190
-			$this->config,
191
-			$this->previewMapper,
192
-			$this->storageFactory,
193
-			Server::get(IDBConnection::class),
194
-			Server::get(IRootFolder::class),
195
-			$this->mimeTypeDetector,
196
-			$this->mimeTypeLoader,
197
-			$this->logger,
198
-			Server::get(IAppDataFactory::class)
199
-		);
200
-		$this->invokePrivate($job, 'run', [[]]);
201
-		$previews = iterator_to_array($this->previewMapper->getAvailablePreviewsForFile(5));
202
-		$this->assertEquals(9, count($previews));
203
-		$this->assertEquals(0, count($this->previewAppData->getDirectoryListing()));
204
-
205
-		$nameVersionMapping = [];
206
-		foreach ($previews as $preview) {
207
-			$nameVersionMapping[$preview->getName($this->mimeTypeLoader)] = $preview->getVersion();
208
-		}
209
-
210
-		$this->assertEquals([
211
-			'1000-128-128-crop.png' => 1000,
212
-			'1000-128-128.png' => 1000,
213
-			'1000-256-256-max.png' => 1000,
214
-			'1001-128-128-crop.png' => 1001,
215
-			'1001-128-128.png' => 1001,
216
-			'1001-256-256-max.png' => 1001,
217
-			'128-128-crop.png' => null,
218
-			'128-128.png' => null,
219
-			'256-256-max.png' => null,
220
-		], $nameVersionMapping);
221
-	}
34
+    private IAppData $previewAppData;
35
+    private PreviewMapper $previewMapper;
36
+    private IAppConfig&MockObject $appConfig;
37
+    private IConfig $config;
38
+    private StorageFactory $storageFactory;
39
+    private PreviewService $previewService;
40
+    private IDBConnection $db;
41
+    private IMimeTypeLoader&MockObject $mimeTypeLoader;
42
+    private IMimeTypeDetector&MockObject $mimeTypeDetector;
43
+    private LoggerInterface&MockObject $logger;
44
+
45
+    public function setUp(): void {
46
+        parent::setUp();
47
+        $this->previewAppData = Server::get(IAppDataFactory::class)->get('preview');
48
+        $this->previewMapper = Server::get(PreviewMapper::class);
49
+        $this->config = Server::get(IConfig::class);
50
+        $this->appConfig = $this->createMock(IAppConfig::class);
51
+        $this->appConfig->expects($this->any())
52
+            ->method('getValueBool')
53
+            ->willReturn(false);
54
+        $this->appConfig->expects($this->any())
55
+            ->method('setValueBool')
56
+            ->willReturn(true);
57
+        $this->storageFactory = Server::get(StorageFactory::class);
58
+        $this->previewService = Server::get(PreviewService::class);
59
+        $this->db = Server::get(IDBConnection::class);
60
+
61
+        $qb = $this->db->getQueryBuilder();
62
+        $qb->delete('filecache')
63
+            ->where($qb->expr()->eq('fileid', $qb->createNamedParameter(5)))
64
+            ->executeStatement();
65
+
66
+        $qb = $this->db->getQueryBuilder();
67
+        $qb->insert('filecache')
68
+            ->values([
69
+                'fileid' => $qb->createNamedParameter(5),
70
+                'storage' => $qb->createNamedParameter(1),
71
+                'path' => $qb->createNamedParameter('test/abc'),
72
+                'path_hash' => $qb->createNamedParameter(md5('test')),
73
+                'parent' => $qb->createNamedParameter(0),
74
+                'name' => $qb->createNamedParameter('abc'),
75
+                'mimetype' => $qb->createNamedParameter(42),
76
+                'size' => $qb->createNamedParameter(1000),
77
+                'mtime' => $qb->createNamedParameter(1000),
78
+                'storage_mtime' => $qb->createNamedParameter(1000),
79
+                'encrypted' => $qb->createNamedParameter(0),
80
+                'unencrypted_size' => $qb->createNamedParameter(0),
81
+                'etag' => $qb->createNamedParameter('abcdefg'),
82
+                'permissions' => $qb->createNamedParameter(0),
83
+                'checksum' => $qb->createNamedParameter('abcdefg'),
84
+            ])->executeStatement();
85
+
86
+        $this->mimeTypeDetector = $this->createMock(IMimeTypeDetector::class);
87
+        $this->mimeTypeDetector->method('detectPath')->willReturn('image/png');
88
+        $this->mimeTypeLoader = $this->createMock(IMimeTypeLoader::class);
89
+        $this->mimeTypeLoader->method('getId')->with('image/png')->willReturn(42);
90
+        $this->mimeTypeLoader->method('getMimetypeById')->with(42)->willReturn('image/png');
91
+        $this->logger = $this->createMock(LoggerInterface::class);
92
+    }
93
+
94
+    public function tearDown(): void {
95
+        foreach ($this->previewAppData->getDirectoryListing() as $folder) {
96
+            $folder->delete();
97
+        }
98
+        $this->previewService->deleteAll();
99
+
100
+        $qb = $this->db->getQueryBuilder();
101
+        $qb->delete('filecache')
102
+            ->where($qb->expr()->eq('fileid', $qb->createNamedParameter(5)))
103
+            ->executeStatement();
104
+    }
105
+
106
+    #[TestDox('Test the migration from the legacy flat hierarchy to the new database format')]
107
+    public function testMigrationLegacyPath(): void {
108
+        $folder = $this->previewAppData->newFolder('5');
109
+        $folder->newFile('64-64-crop.jpg', 'abcdefg');
110
+        $folder->newFile('128-128-crop.png', 'abcdefg');
111
+        $this->assertEquals(1, count($this->previewAppData->getDirectoryListing()));
112
+        $this->assertEquals(2, count($folder->getDirectoryListing()));
113
+        $this->assertEquals(0, count(iterator_to_array($this->previewMapper->getAvailablePreviewsForFile(5))));
114
+
115
+        $job = new MovePreviewJob(
116
+            Server::get(ITimeFactory::class),
117
+            $this->appConfig,
118
+            $this->config,
119
+            $this->previewMapper,
120
+            $this->storageFactory,
121
+            Server::get(IDBConnection::class),
122
+            Server::get(IRootFolder::class),
123
+            $this->mimeTypeDetector,
124
+            $this->mimeTypeLoader,
125
+            $this->logger,
126
+            Server::get(IAppDataFactory::class),
127
+        );
128
+        $this->invokePrivate($job, 'run', [[]]);
129
+        $this->assertEquals(0, count($this->previewAppData->getDirectoryListing()));
130
+        $this->assertEquals(2, count(iterator_to_array($this->previewMapper->getAvailablePreviewsForFile(5))));
131
+    }
132
+
133
+    private static function getInternalFolder(string $name): string {
134
+        return implode('/', str_split(substr(md5($name), 0, 7))) . '/' . $name;
135
+    }
136
+
137
+    #[TestDox("Test the migration from the 'new' nested hierarchy to the database format")]
138
+    public function testMigrationPath(): void {
139
+        $folder = $this->previewAppData->newFolder(self::getInternalFolder((string)5));
140
+        $folder->newFile('64-64-crop.jpg', 'abcdefg');
141
+        $folder->newFile('128-128-crop.png', 'abcdefg');
142
+
143
+        $folder = $this->previewAppData->getFolder(self::getInternalFolder((string)5));
144
+        $this->assertEquals(2, count($folder->getDirectoryListing()));
145
+        $this->assertEquals(0, count(iterator_to_array($this->previewMapper->getAvailablePreviewsForFile(5))));
146
+
147
+        $job = new MovePreviewJob(
148
+            Server::get(ITimeFactory::class),
149
+            $this->appConfig,
150
+            $this->config,
151
+            $this->previewMapper,
152
+            $this->storageFactory,
153
+            Server::get(IDBConnection::class),
154
+            Server::get(IRootFolder::class),
155
+            $this->mimeTypeDetector,
156
+            $this->mimeTypeLoader,
157
+            $this->logger,
158
+            Server::get(IAppDataFactory::class)
159
+        );
160
+        $this->invokePrivate($job, 'run', [[]]);
161
+        $this->assertEquals(0, count($this->previewAppData->getDirectoryListing()));
162
+        $this->assertEquals(2, count(iterator_to_array($this->previewMapper->getAvailablePreviewsForFile(5))));
163
+    }
164
+
165
+    #[TestDox("Test the migration from the 'new' nested hierarchy to the database format")]
166
+    public function testMigrationPathWithVersion(): void {
167
+        $folder = $this->previewAppData->newFolder(self::getInternalFolder((string)5));
168
+        // No version
169
+        $folder->newFile('128-128-crop.png', 'abcdefg');
170
+        $folder->newFile('256-256-max.png', 'abcdefg');
171
+        $folder->newFile('128-128.png', 'abcdefg');
172
+
173
+        // Version 1000
174
+        $folder->newFile('1000-128-128-crop.png', 'abcdefg');
175
+        $folder->newFile('1000-256-256-max.png', 'abcdefg');
176
+        $folder->newFile('1000-128-128.png', 'abcdefg');
177
+
178
+        // Version 1001
179
+        $folder->newFile('1001-128-128-crop.png', 'abcdefg');
180
+        $folder->newFile('1001-256-256-max.png', 'abcdefg');
181
+        $folder->newFile('1001-128-128.png', 'abcdefg');
182
+
183
+        $folder = $this->previewAppData->getFolder(self::getInternalFolder((string)5));
184
+        $this->assertEquals(9, count($folder->getDirectoryListing()));
185
+        $this->assertEquals(0, count(iterator_to_array($this->previewMapper->getAvailablePreviewsForFile(5))));
186
+
187
+        $job = new MovePreviewJob(
188
+            Server::get(ITimeFactory::class),
189
+            $this->appConfig,
190
+            $this->config,
191
+            $this->previewMapper,
192
+            $this->storageFactory,
193
+            Server::get(IDBConnection::class),
194
+            Server::get(IRootFolder::class),
195
+            $this->mimeTypeDetector,
196
+            $this->mimeTypeLoader,
197
+            $this->logger,
198
+            Server::get(IAppDataFactory::class)
199
+        );
200
+        $this->invokePrivate($job, 'run', [[]]);
201
+        $previews = iterator_to_array($this->previewMapper->getAvailablePreviewsForFile(5));
202
+        $this->assertEquals(9, count($previews));
203
+        $this->assertEquals(0, count($this->previewAppData->getDirectoryListing()));
204
+
205
+        $nameVersionMapping = [];
206
+        foreach ($previews as $preview) {
207
+            $nameVersionMapping[$preview->getName($this->mimeTypeLoader)] = $preview->getVersion();
208
+        }
209
+
210
+        $this->assertEquals([
211
+            '1000-128-128-crop.png' => 1000,
212
+            '1000-128-128.png' => 1000,
213
+            '1000-256-256-max.png' => 1000,
214
+            '1001-128-128-crop.png' => 1001,
215
+            '1001-128-128.png' => 1001,
216
+            '1001-256-256-max.png' => 1001,
217
+            '128-128-crop.png' => null,
218
+            '128-128.png' => null,
219
+            '256-256-max.png' => null,
220
+        ], $nameVersionMapping);
221
+    }
222 222
 }
Please login to merge, or discard this patch.
lib/public/AppFramework/Db/Entity.php 2 patches
Indentation   +287 added lines, -287 removed lines patch added patch discarded remove patch
@@ -19,291 +19,291 @@
 block discarded – undo
19 19
  * @psalm-consistent-constructor
20 20
  */
21 21
 abstract class Entity {
22
-	public int|string|null $id = null;
23
-	private array $_updatedFields = [];
24
-	/** @psalm-param $_fieldTypes array<string, Types::*> */
25
-	private array $_fieldTypes = ['id' => 'integer'];
26
-
27
-	/**
28
-	 * Simple alternative constructor for building entities from a request
29
-	 * @param array $params the array which was obtained via $this->params('key')
30
-	 *                      in the controller
31
-	 * @since 7.0.0
32
-	 */
33
-	public static function fromParams(array $params): static {
34
-		$instance = new static();
35
-
36
-		foreach ($params as $key => $value) {
37
-			$method = 'set' . ucfirst($key);
38
-			$instance->$method($value);
39
-		}
40
-
41
-		return $instance;
42
-	}
43
-
44
-	/**
45
-	 * Maps the keys of the row array to the attributes
46
-	 * @param array $row the row to map onto the entity
47
-	 * @since 7.0.0
48
-	 */
49
-	public static function fromRow(array $row): static {
50
-		$instance = new static();
51
-
52
-		foreach ($row as $key => $value) {
53
-			$prop = $instance->columnToProperty($key);
54
-			$instance->setter($prop, [$value]);
55
-		}
56
-
57
-		$instance->resetUpdatedFields();
58
-
59
-		return $instance;
60
-	}
61
-
62
-
63
-	/**
64
-	 * @return array<string, Types::*> with attribute and type
65
-	 * @since 7.0.0
66
-	 */
67
-	public function getFieldTypes(): array {
68
-		return $this->_fieldTypes;
69
-	}
70
-
71
-
72
-	/**
73
-	 * Marks the entity as clean needed for setting the id after the insertion
74
-	 * @since 7.0.0
75
-	 */
76
-	public function resetUpdatedFields(): void {
77
-		$this->_updatedFields = [];
78
-	}
79
-
80
-	/**
81
-	 * Generic setter for properties
82
-	 *
83
-	 * @throws \InvalidArgumentException
84
-	 * @since 7.0.0
85
-	 *
86
-	 */
87
-	protected function setter(string $name, array $args): void {
88
-		// setters should only work for existing attributes
89
-		if (!property_exists($this, $name)) {
90
-			throw new \BadFunctionCallException($name . ' is not a valid attribute');
91
-		}
92
-
93
-		if ($args[0] === $this->$name) {
94
-			return;
95
-		}
96
-		$this->markFieldUpdated($name);
97
-
98
-		// if type definition exists, cast to correct type
99
-		if ($args[0] !== null && array_key_exists($name, $this->_fieldTypes)) {
100
-			$type = $this->_fieldTypes[$name];
101
-			if ($type === Types::BLOB) {
102
-				// (B)LOB is treated as string when we read from the DB
103
-				if (is_resource($args[0])) {
104
-					$args[0] = stream_get_contents($args[0]);
105
-				}
106
-				$type = Types::STRING;
107
-			}
108
-
109
-			switch ($type) {
110
-				case Types::BIGINT:
111
-				case Types::SMALLINT:
112
-					settype($args[0], Types::INTEGER);
113
-					break;
114
-				case Types::BINARY:
115
-				case Types::DECIMAL:
116
-				case Types::TEXT:
117
-					settype($args[0], Types::STRING);
118
-					break;
119
-				case Types::TIME:
120
-				case Types::DATE:
121
-				case Types::DATETIME:
122
-				case Types::DATETIME_TZ:
123
-					if (!$args[0] instanceof \DateTime) {
124
-						$args[0] = new \DateTime($args[0]);
125
-					}
126
-					break;
127
-				case Types::TIME_IMMUTABLE:
128
-				case Types::DATE_IMMUTABLE:
129
-				case Types::DATETIME_IMMUTABLE:
130
-				case Types::DATETIME_TZ_IMMUTABLE:
131
-					if (!$args[0] instanceof \DateTimeImmutable) {
132
-						$args[0] = new \DateTimeImmutable($args[0]);
133
-					}
134
-					break;
135
-				case Types::JSON:
136
-					if (!is_array($args[0])) {
137
-						$args[0] = json_decode($args[0], true);
138
-					}
139
-					break;
140
-				default:
141
-					settype($args[0], $type);
142
-			}
143
-		}
144
-		$this->$name = $args[0];
145
-
146
-	}
147
-
148
-	/**
149
-	 * Generic getter for properties
150
-	 * @since 7.0.0
151
-	 */
152
-	protected function getter(string $name): mixed {
153
-		// getters should only work for existing attributes
154
-		if (property_exists($this, $name)) {
155
-			return $this->$name;
156
-		} else {
157
-			throw new \BadFunctionCallException($name
158
-				. ' is not a valid attribute');
159
-		}
160
-	}
161
-
162
-
163
-	/**
164
-	 * Each time a setter is called, push the part after set
165
-	 * into an array: for instance setId will save Id in the
166
-	 * updated fields array so it can be easily used to create the
167
-	 * getter method
168
-	 * @since 7.0.0
169
-	 */
170
-	public function __call(string $methodName, array $args) {
171
-		if (str_starts_with($methodName, 'set')) {
172
-			$this->setter(lcfirst(substr($methodName, 3)), $args);
173
-		} elseif (str_starts_with($methodName, 'get')) {
174
-			return $this->getter(lcfirst(substr($methodName, 3)));
175
-		} elseif ($this->isGetterForBoolProperty($methodName)) {
176
-			return $this->getter(lcfirst(substr($methodName, 2)));
177
-		} else {
178
-			throw new \BadFunctionCallException($methodName
179
-				. ' does not exist');
180
-		}
181
-	}
182
-
183
-	/**
184
-	 * @param string $methodName
185
-	 * @return bool
186
-	 * @since 18.0.0
187
-	 */
188
-	protected function isGetterForBoolProperty(string $methodName): bool {
189
-		if (str_starts_with($methodName, 'is')) {
190
-			$fieldName = lcfirst(substr($methodName, 2));
191
-			return isset($this->_fieldTypes[$fieldName]) && str_starts_with($this->_fieldTypes[$fieldName], 'bool');
192
-		}
193
-		return false;
194
-	}
195
-
196
-	/**
197
-	 * Mark am attribute as updated
198
-	 * @param string $attribute the name of the attribute
199
-	 * @since 7.0.0
200
-	 */
201
-	protected function markFieldUpdated(string $attribute): void {
202
-		$this->_updatedFields[$attribute] = true;
203
-	}
204
-
205
-
206
-	/**
207
-	 * Transform a database columnname to a property
208
-	 *
209
-	 * @param string $columnName the name of the column
210
-	 * @return string the property name
211
-	 * @since 7.0.0
212
-	 */
213
-	public function columnToProperty(string $columnName) {
214
-		$parts = explode('_', $columnName);
215
-		$property = '';
216
-
217
-		foreach ($parts as $part) {
218
-			if ($property === '') {
219
-				$property = $part;
220
-			} else {
221
-				$property .= ucfirst($part);
222
-			}
223
-		}
224
-
225
-		return $property;
226
-	}
227
-
228
-
229
-	/**
230
-	 * Transform a property to a database column name
231
-	 *
232
-	 * @param string $property the name of the property
233
-	 * @return string the column name
234
-	 * @since 7.0.0
235
-	 */
236
-	public function propertyToColumn(string $property): string {
237
-		$parts = preg_split('/(?=[A-Z])/', $property);
238
-
239
-		$column = '';
240
-		foreach ($parts as $part) {
241
-			if ($column === '') {
242
-				$column = $part;
243
-			} else {
244
-				$column .= '_' . lcfirst($part);
245
-			}
246
-		}
247
-
248
-		return $column;
249
-	}
250
-
251
-
252
-	/**
253
-	 * @return array array of updated fields for update query
254
-	 * @since 7.0.0
255
-	 */
256
-	public function getUpdatedFields(): array {
257
-		return $this->_updatedFields;
258
-	}
259
-
260
-
261
-	/**
262
-	 * Adds type information for a field so that it's automatically cast to
263
-	 * that value once its being returned from the database
264
-	 *
265
-	 * @param string $fieldName the name of the attribute
266
-	 * @param Types::* $type the type which will be used to match a cast
267
-	 * @since 31.0.0 Parameter $type is now restricted to {@see Types} constants. The formerly accidentally supported types 'int'|'bool'|'double' are mapped to Types::INTEGER|Types::BOOLEAN|Types::FLOAT accordingly.
268
-	 * @since 7.0.0
269
-	 */
270
-	protected function addType(string $fieldName, string $type): void {
271
-		/** @psalm-suppress TypeDoesNotContainType */
272
-		if (in_array($type, ['bool', 'double', 'int', 'array', 'object'], true)) {
273
-			// Mapping legacy strings to the actual types
274
-			$type = match ($type) {
275
-				'int' => Types::INTEGER,
276
-				'bool' => Types::BOOLEAN,
277
-				'double' => Types::FLOAT,
278
-				'array',
279
-				'object' => Types::STRING,
280
-			};
281
-		}
282
-
283
-		$this->_fieldTypes[$fieldName] = $type;
284
-	}
285
-
286
-
287
-	/**
288
-	 * Slugify the value of a given attribute
289
-	 * Warning: This doesn't result in a unique value
290
-	 *
291
-	 * @param string $attributeName the name of the attribute, which value should be slugified
292
-	 * @return string slugified value
293
-	 * @since 7.0.0
294
-	 * @deprecated 24.0.0
295
-	 */
296
-	public function slugify(string $attributeName): string {
297
-		// toSlug should only work for existing attributes
298
-		if (property_exists($this, $attributeName)) {
299
-			$value = $this->$attributeName;
300
-			// replace everything except alphanumeric with a single '-'
301
-			$value = preg_replace('/[^A-Za-z0-9]+/', '-', $value);
302
-			$value = strtolower($value);
303
-			// trim '-'
304
-			return trim($value, '-');
305
-		}
306
-
307
-		throw new \BadFunctionCallException($attributeName . ' is not a valid attribute');
308
-	}
22
+    public int|string|null $id = null;
23
+    private array $_updatedFields = [];
24
+    /** @psalm-param $_fieldTypes array<string, Types::*> */
25
+    private array $_fieldTypes = ['id' => 'integer'];
26
+
27
+    /**
28
+     * Simple alternative constructor for building entities from a request
29
+     * @param array $params the array which was obtained via $this->params('key')
30
+     *                      in the controller
31
+     * @since 7.0.0
32
+     */
33
+    public static function fromParams(array $params): static {
34
+        $instance = new static();
35
+
36
+        foreach ($params as $key => $value) {
37
+            $method = 'set' . ucfirst($key);
38
+            $instance->$method($value);
39
+        }
40
+
41
+        return $instance;
42
+    }
43
+
44
+    /**
45
+     * Maps the keys of the row array to the attributes
46
+     * @param array $row the row to map onto the entity
47
+     * @since 7.0.0
48
+     */
49
+    public static function fromRow(array $row): static {
50
+        $instance = new static();
51
+
52
+        foreach ($row as $key => $value) {
53
+            $prop = $instance->columnToProperty($key);
54
+            $instance->setter($prop, [$value]);
55
+        }
56
+
57
+        $instance->resetUpdatedFields();
58
+
59
+        return $instance;
60
+    }
61
+
62
+
63
+    /**
64
+     * @return array<string, Types::*> with attribute and type
65
+     * @since 7.0.0
66
+     */
67
+    public function getFieldTypes(): array {
68
+        return $this->_fieldTypes;
69
+    }
70
+
71
+
72
+    /**
73
+     * Marks the entity as clean needed for setting the id after the insertion
74
+     * @since 7.0.0
75
+     */
76
+    public function resetUpdatedFields(): void {
77
+        $this->_updatedFields = [];
78
+    }
79
+
80
+    /**
81
+     * Generic setter for properties
82
+     *
83
+     * @throws \InvalidArgumentException
84
+     * @since 7.0.0
85
+     *
86
+     */
87
+    protected function setter(string $name, array $args): void {
88
+        // setters should only work for existing attributes
89
+        if (!property_exists($this, $name)) {
90
+            throw new \BadFunctionCallException($name . ' is not a valid attribute');
91
+        }
92
+
93
+        if ($args[0] === $this->$name) {
94
+            return;
95
+        }
96
+        $this->markFieldUpdated($name);
97
+
98
+        // if type definition exists, cast to correct type
99
+        if ($args[0] !== null && array_key_exists($name, $this->_fieldTypes)) {
100
+            $type = $this->_fieldTypes[$name];
101
+            if ($type === Types::BLOB) {
102
+                // (B)LOB is treated as string when we read from the DB
103
+                if (is_resource($args[0])) {
104
+                    $args[0] = stream_get_contents($args[0]);
105
+                }
106
+                $type = Types::STRING;
107
+            }
108
+
109
+            switch ($type) {
110
+                case Types::BIGINT:
111
+                case Types::SMALLINT:
112
+                    settype($args[0], Types::INTEGER);
113
+                    break;
114
+                case Types::BINARY:
115
+                case Types::DECIMAL:
116
+                case Types::TEXT:
117
+                    settype($args[0], Types::STRING);
118
+                    break;
119
+                case Types::TIME:
120
+                case Types::DATE:
121
+                case Types::DATETIME:
122
+                case Types::DATETIME_TZ:
123
+                    if (!$args[0] instanceof \DateTime) {
124
+                        $args[0] = new \DateTime($args[0]);
125
+                    }
126
+                    break;
127
+                case Types::TIME_IMMUTABLE:
128
+                case Types::DATE_IMMUTABLE:
129
+                case Types::DATETIME_IMMUTABLE:
130
+                case Types::DATETIME_TZ_IMMUTABLE:
131
+                    if (!$args[0] instanceof \DateTimeImmutable) {
132
+                        $args[0] = new \DateTimeImmutable($args[0]);
133
+                    }
134
+                    break;
135
+                case Types::JSON:
136
+                    if (!is_array($args[0])) {
137
+                        $args[0] = json_decode($args[0], true);
138
+                    }
139
+                    break;
140
+                default:
141
+                    settype($args[0], $type);
142
+            }
143
+        }
144
+        $this->$name = $args[0];
145
+
146
+    }
147
+
148
+    /**
149
+     * Generic getter for properties
150
+     * @since 7.0.0
151
+     */
152
+    protected function getter(string $name): mixed {
153
+        // getters should only work for existing attributes
154
+        if (property_exists($this, $name)) {
155
+            return $this->$name;
156
+        } else {
157
+            throw new \BadFunctionCallException($name
158
+                . ' is not a valid attribute');
159
+        }
160
+    }
161
+
162
+
163
+    /**
164
+     * Each time a setter is called, push the part after set
165
+     * into an array: for instance setId will save Id in the
166
+     * updated fields array so it can be easily used to create the
167
+     * getter method
168
+     * @since 7.0.0
169
+     */
170
+    public function __call(string $methodName, array $args) {
171
+        if (str_starts_with($methodName, 'set')) {
172
+            $this->setter(lcfirst(substr($methodName, 3)), $args);
173
+        } elseif (str_starts_with($methodName, 'get')) {
174
+            return $this->getter(lcfirst(substr($methodName, 3)));
175
+        } elseif ($this->isGetterForBoolProperty($methodName)) {
176
+            return $this->getter(lcfirst(substr($methodName, 2)));
177
+        } else {
178
+            throw new \BadFunctionCallException($methodName
179
+                . ' does not exist');
180
+        }
181
+    }
182
+
183
+    /**
184
+     * @param string $methodName
185
+     * @return bool
186
+     * @since 18.0.0
187
+     */
188
+    protected function isGetterForBoolProperty(string $methodName): bool {
189
+        if (str_starts_with($methodName, 'is')) {
190
+            $fieldName = lcfirst(substr($methodName, 2));
191
+            return isset($this->_fieldTypes[$fieldName]) && str_starts_with($this->_fieldTypes[$fieldName], 'bool');
192
+        }
193
+        return false;
194
+    }
195
+
196
+    /**
197
+     * Mark am attribute as updated
198
+     * @param string $attribute the name of the attribute
199
+     * @since 7.0.0
200
+     */
201
+    protected function markFieldUpdated(string $attribute): void {
202
+        $this->_updatedFields[$attribute] = true;
203
+    }
204
+
205
+
206
+    /**
207
+     * Transform a database columnname to a property
208
+     *
209
+     * @param string $columnName the name of the column
210
+     * @return string the property name
211
+     * @since 7.0.0
212
+     */
213
+    public function columnToProperty(string $columnName) {
214
+        $parts = explode('_', $columnName);
215
+        $property = '';
216
+
217
+        foreach ($parts as $part) {
218
+            if ($property === '') {
219
+                $property = $part;
220
+            } else {
221
+                $property .= ucfirst($part);
222
+            }
223
+        }
224
+
225
+        return $property;
226
+    }
227
+
228
+
229
+    /**
230
+     * Transform a property to a database column name
231
+     *
232
+     * @param string $property the name of the property
233
+     * @return string the column name
234
+     * @since 7.0.0
235
+     */
236
+    public function propertyToColumn(string $property): string {
237
+        $parts = preg_split('/(?=[A-Z])/', $property);
238
+
239
+        $column = '';
240
+        foreach ($parts as $part) {
241
+            if ($column === '') {
242
+                $column = $part;
243
+            } else {
244
+                $column .= '_' . lcfirst($part);
245
+            }
246
+        }
247
+
248
+        return $column;
249
+    }
250
+
251
+
252
+    /**
253
+     * @return array array of updated fields for update query
254
+     * @since 7.0.0
255
+     */
256
+    public function getUpdatedFields(): array {
257
+        return $this->_updatedFields;
258
+    }
259
+
260
+
261
+    /**
262
+     * Adds type information for a field so that it's automatically cast to
263
+     * that value once its being returned from the database
264
+     *
265
+     * @param string $fieldName the name of the attribute
266
+     * @param Types::* $type the type which will be used to match a cast
267
+     * @since 31.0.0 Parameter $type is now restricted to {@see Types} constants. The formerly accidentally supported types 'int'|'bool'|'double' are mapped to Types::INTEGER|Types::BOOLEAN|Types::FLOAT accordingly.
268
+     * @since 7.0.0
269
+     */
270
+    protected function addType(string $fieldName, string $type): void {
271
+        /** @psalm-suppress TypeDoesNotContainType */
272
+        if (in_array($type, ['bool', 'double', 'int', 'array', 'object'], true)) {
273
+            // Mapping legacy strings to the actual types
274
+            $type = match ($type) {
275
+                'int' => Types::INTEGER,
276
+                'bool' => Types::BOOLEAN,
277
+                'double' => Types::FLOAT,
278
+                'array',
279
+                'object' => Types::STRING,
280
+            };
281
+        }
282
+
283
+        $this->_fieldTypes[$fieldName] = $type;
284
+    }
285
+
286
+
287
+    /**
288
+     * Slugify the value of a given attribute
289
+     * Warning: This doesn't result in a unique value
290
+     *
291
+     * @param string $attributeName the name of the attribute, which value should be slugified
292
+     * @return string slugified value
293
+     * @since 7.0.0
294
+     * @deprecated 24.0.0
295
+     */
296
+    public function slugify(string $attributeName): string {
297
+        // toSlug should only work for existing attributes
298
+        if (property_exists($this, $attributeName)) {
299
+            $value = $this->$attributeName;
300
+            // replace everything except alphanumeric with a single '-'
301
+            $value = preg_replace('/[^A-Za-z0-9]+/', '-', $value);
302
+            $value = strtolower($value);
303
+            // trim '-'
304
+            return trim($value, '-');
305
+        }
306
+
307
+        throw new \BadFunctionCallException($attributeName . ' is not a valid attribute');
308
+    }
309 309
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -19,7 +19,7 @@  discard block
 block discarded – undo
19 19
  * @psalm-consistent-constructor
20 20
  */
21 21
 abstract class Entity {
22
-	public int|string|null $id = null;
22
+	public int | string | null $id = null;
23 23
 	private array $_updatedFields = [];
24 24
 	/** @psalm-param $_fieldTypes array<string, Types::*> */
25 25
 	private array $_fieldTypes = ['id' => 'integer'];
@@ -34,7 +34,7 @@  discard block
 block discarded – undo
34 34
 		$instance = new static();
35 35
 
36 36
 		foreach ($params as $key => $value) {
37
-			$method = 'set' . ucfirst($key);
37
+			$method = 'set'.ucfirst($key);
38 38
 			$instance->$method($value);
39 39
 		}
40 40
 
@@ -87,7 +87,7 @@  discard block
 block discarded – undo
87 87
 	protected function setter(string $name, array $args): void {
88 88
 		// setters should only work for existing attributes
89 89
 		if (!property_exists($this, $name)) {
90
-			throw new \BadFunctionCallException($name . ' is not a valid attribute');
90
+			throw new \BadFunctionCallException($name.' is not a valid attribute');
91 91
 		}
92 92
 
93 93
 		if ($args[0] === $this->$name) {
@@ -241,7 +241,7 @@  discard block
 block discarded – undo
241 241
 			if ($column === '') {
242 242
 				$column = $part;
243 243
 			} else {
244
-				$column .= '_' . lcfirst($part);
244
+				$column .= '_'.lcfirst($part);
245 245
 			}
246 246
 		}
247 247
 
@@ -304,6 +304,6 @@  discard block
 block discarded – undo
304 304
 			return trim($value, '-');
305 305
 		}
306 306
 
307
-		throw new \BadFunctionCallException($attributeName . ' is not a valid attribute');
307
+		throw new \BadFunctionCallException($attributeName.' is not a valid attribute');
308 308
 	}
309 309
 }
Please login to merge, or discard this patch.
lib/public/AppFramework/Db/SnowflakeAwareEntity.php 1 patch
Indentation   +34 added lines, -34 removed lines patch added patch discarded remove patch
@@ -21,38 +21,38 @@
 block discarded – undo
21 21
  */
22 22
 #[Consumable(since: '33.0.0')]
23 23
 abstract class SnowflakeAwareEntity extends Entity {
24
-	protected ?Snowflake $snowflake = null;
25
-
26
-	/** @psalm-param $_fieldTypes array<string, Types::*> */
27
-	private array $_fieldTypes = ['id' => Types::STRING];
28
-
29
-	public function setId($id): void {
30
-		throw new \LogicException('Use generated id to set a new id to the Snowflake aware entity.');
31
-	}
32
-
33
-	/**
34
-	 * Automatically creates a snowflake ID
35
-	 */
36
-	public function generateId(): void {
37
-		if ($this->id === null) {
38
-			$this->id = Server::get(ISnowflakeGenerator::class)->nextId();
39
-			$this->markFieldUpdated('id');
40
-		}
41
-	}
42
-
43
-	public function getCreatedAt(): ?\DateTimeImmutable {
44
-		return $this->getSnowflake()?->getCreatedAt();
45
-	}
46
-
47
-	public function getSnowflake(): ?Snowflake {
48
-		if ($this->id === null) {
49
-			return null;
50
-		}
51
-
52
-		if ($this->snowflake === null) {
53
-			$this->snowflake = Server::get(ISnowflakeDecoder::class)->decode($this->id);
54
-		}
55
-
56
-		return $this->snowflake;
57
-	}
24
+    protected ?Snowflake $snowflake = null;
25
+
26
+    /** @psalm-param $_fieldTypes array<string, Types::*> */
27
+    private array $_fieldTypes = ['id' => Types::STRING];
28
+
29
+    public function setId($id): void {
30
+        throw new \LogicException('Use generated id to set a new id to the Snowflake aware entity.');
31
+    }
32
+
33
+    /**
34
+     * Automatically creates a snowflake ID
35
+     */
36
+    public function generateId(): void {
37
+        if ($this->id === null) {
38
+            $this->id = Server::get(ISnowflakeGenerator::class)->nextId();
39
+            $this->markFieldUpdated('id');
40
+        }
41
+    }
42
+
43
+    public function getCreatedAt(): ?\DateTimeImmutable {
44
+        return $this->getSnowflake()?->getCreatedAt();
45
+    }
46
+
47
+    public function getSnowflake(): ?Snowflake {
48
+        if ($this->id === null) {
49
+            return null;
50
+        }
51
+
52
+        if ($this->snowflake === null) {
53
+            $this->snowflake = Server::get(ISnowflakeDecoder::class)->decode($this->id);
54
+        }
55
+
56
+        return $this->snowflake;
57
+    }
58 58
 }
Please login to merge, or discard this patch.
lib/public/AppFramework/Db/QBMapper.php 2 patches
Indentation   +358 added lines, -358 removed lines patch added patch discarded remove patch
@@ -22,362 +22,362 @@
 block discarded – undo
22 22
  * @template T of Entity
23 23
  */
24 24
 abstract class QBMapper {
25
-	/** @var string */
26
-	protected $tableName;
27
-
28
-	/** @var string|class-string<T> */
29
-	protected $entityClass;
30
-
31
-	/** @var IDBConnection */
32
-	protected $db;
33
-
34
-	/**
35
-	 * @param IDBConnection $db Instance of the Db abstraction layer
36
-	 * @param string $tableName the name of the table. set this to allow entity
37
-	 * @param class-string<T>|null $entityClass the name of the entity that the sql should be
38
-	 *                                          mapped to queries without using sql
39
-	 * @since 14.0.0
40
-	 */
41
-	public function __construct(IDBConnection $db, string $tableName, ?string $entityClass = null) {
42
-		$this->db = $db;
43
-		$this->tableName = $tableName;
44
-
45
-		// if not given set the entity name to the class without the mapper part
46
-		// cache it here for later use since reflection is slow
47
-		if ($entityClass === null) {
48
-			$this->entityClass = str_replace('Mapper', '', \get_class($this));
49
-		} else {
50
-			$this->entityClass = $entityClass;
51
-		}
52
-	}
53
-
54
-
55
-	/**
56
-	 * @return string the table name
57
-	 * @since 14.0.0
58
-	 */
59
-	public function getTableName(): string {
60
-		return $this->tableName;
61
-	}
62
-
63
-
64
-	/**
65
-	 * Deletes an entity from the table
66
-	 *
67
-	 * @param Entity $entity the entity that should be deleted
68
-	 * @psalm-param T $entity the entity that should be deleted
69
-	 * @return Entity the deleted entity
70
-	 * @psalm-return T the deleted entity
71
-	 * @throws Exception
72
-	 * @since 14.0.0
73
-	 */
74
-	public function delete(Entity $entity): Entity {
75
-		$qb = $this->db->getQueryBuilder();
76
-
77
-		$idType = $this->getParameterTypeForProperty($entity, 'id');
78
-
79
-		$qb->delete($this->tableName)
80
-			->where(
81
-				$qb->expr()->eq('id', $qb->createNamedParameter($entity->getId(), $idType))
82
-			);
83
-		$qb->executeStatement();
84
-		return $entity;
85
-	}
86
-
87
-	/**
88
-	 * Creates a new entry in the db from an entity
89
-	 *
90
-	 * @param Entity $entity the entity that should be created
91
-	 * @psalm-param T $entity the entity that should be created
92
-	 * @return Entity the saved entity with the set id
93
-	 * @psalm-return T the saved entity with the set id
94
-	 * @throws Exception
95
-	 * @since 14.0.0
96
-	 */
97
-	public function insert(Entity $entity): Entity {
98
-		// get updated fields to save, fields have to be set using a setter to
99
-		// be saved
100
-		$properties = $entity->getUpdatedFields();
101
-
102
-		$qb = $this->db->getQueryBuilder();
103
-		$qb->insert($this->tableName);
104
-
105
-		// build the fields
106
-		foreach ($properties as $property => $updated) {
107
-			$column = $entity->propertyToColumn($property);
108
-			$getter = 'get' . ucfirst($property);
109
-			$value = $entity->$getter();
110
-
111
-			if ($property === 'id' && $entity->id === null) {
112
-				continue;
113
-			}
114
-			$type = $this->getParameterTypeForProperty($entity, $property);
115
-			$qb->setValue($column, $qb->createNamedParameter($value, $type));
116
-		}
117
-
118
-		if ($entity instanceof SnowflakeAwareEntity) {
119
-			/** @psalm-suppress DocblockTypeContradiction */
120
-			$entity->generateId();
121
-			$qb->executeStatement();
122
-		} elseif ($entity->id === null) {
123
-			$qb->executeStatement();
124
-			// When autoincrement is used id is always an int
125
-			$entity->setId($qb->getLastInsertId());
126
-		} else {
127
-			$qb->executeStatement();
128
-		}
129
-		return $entity;
130
-	}
131
-
132
-	/**
133
-	 * Tries to creates a new entry in the db from an entity and
134
-	 * updates an existing entry if duplicate keys are detected
135
-	 * by the database
136
-	 *
137
-	 * @param Entity $entity the entity that should be created/updated
138
-	 * @psalm-param T $entity the entity that should be created/updated
139
-	 * @return Entity the saved entity with the (new) id
140
-	 * @psalm-return T the saved entity with the (new) id
141
-	 * @throws Exception
142
-	 * @throws \InvalidArgumentException if entity has no id
143
-	 * @since 15.0.0
144
-	 */
145
-	public function insertOrUpdate(Entity $entity): Entity {
146
-		try {
147
-			return $this->insert($entity);
148
-		} catch (Exception $ex) {
149
-			if ($ex->getReason() === Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
150
-				return $this->update($entity);
151
-			}
152
-			throw $ex;
153
-		}
154
-	}
155
-
156
-	/**
157
-	 * Updates an entry in the db from an entity
158
-	 *
159
-	 * @param Entity $entity the entity that should be created
160
-	 * @psalm-param T $entity the entity that should be created
161
-	 * @return Entity the saved entity with the set id
162
-	 * @psalm-return T the saved entity with the set id
163
-	 * @throws Exception
164
-	 * @throws \InvalidArgumentException if entity has no id
165
-	 * @since 14.0.0
166
-	 */
167
-	public function update(Entity $entity): Entity {
168
-		// if entity wasn't changed it makes no sense to run a db query
169
-		$properties = $entity->getUpdatedFields();
170
-		if (\count($properties) === 0) {
171
-			return $entity;
172
-		}
173
-
174
-		// entity needs an id
175
-		$id = $entity->getId();
176
-		if ($id === null) {
177
-			throw new \InvalidArgumentException(
178
-				'Entity which should be updated has no id');
179
-		}
180
-
181
-		// get updated fields to save, fields have to be set using a setter to
182
-		// be saved
183
-		// do not update the id field
184
-		unset($properties['id']);
185
-
186
-		$qb = $this->db->getQueryBuilder();
187
-		$qb->update($this->tableName);
188
-
189
-		// build the fields
190
-		foreach ($properties as $property => $updated) {
191
-			$column = $entity->propertyToColumn($property);
192
-			$getter = 'get' . ucfirst($property);
193
-			$value = $entity->$getter();
194
-
195
-			$type = $this->getParameterTypeForProperty($entity, $property);
196
-			$qb->set($column, $qb->createNamedParameter($value, $type));
197
-		}
198
-
199
-		$idType = $this->getParameterTypeForProperty($entity, 'id');
200
-
201
-		$qb->where(
202
-			$qb->expr()->eq('id', $qb->createNamedParameter($id, $idType))
203
-		);
204
-		$qb->executeStatement();
205
-
206
-		return $entity;
207
-	}
208
-
209
-	/**
210
-	 * Returns the type parameter for the QueryBuilder for a specific property
211
-	 * of the $entity
212
-	 *
213
-	 * @param Entity $entity The entity to get the types from
214
-	 * @psalm-param T $entity
215
-	 * @param string $property The property of $entity to get the type for
216
-	 * @return int|string
217
-	 * @since 16.0.0
218
-	 */
219
-	protected function getParameterTypeForProperty(Entity $entity, string $property) {
220
-		$types = $entity->getFieldTypes();
221
-
222
-		if (!isset($types[ $property ])) {
223
-			return IQueryBuilder::PARAM_STR;
224
-		}
225
-
226
-		switch ($types[ $property ]) {
227
-			case 'int':
228
-			case Types::INTEGER:
229
-			case Types::SMALLINT:
230
-				return IQueryBuilder::PARAM_INT;
231
-			case Types::STRING:
232
-				return IQueryBuilder::PARAM_STR;
233
-			case 'bool':
234
-			case Types::BOOLEAN:
235
-				return IQueryBuilder::PARAM_BOOL;
236
-			case Types::BLOB:
237
-				return IQueryBuilder::PARAM_LOB;
238
-			case Types::DATE:
239
-				return IQueryBuilder::PARAM_DATETIME_MUTABLE;
240
-			case Types::DATETIME:
241
-				return IQueryBuilder::PARAM_DATETIME_MUTABLE;
242
-			case Types::DATETIME_TZ:
243
-				return IQueryBuilder::PARAM_DATETIME_TZ_MUTABLE;
244
-			case Types::DATE_IMMUTABLE:
245
-				return IQueryBuilder::PARAM_DATE_IMMUTABLE;
246
-			case Types::DATETIME_IMMUTABLE:
247
-				return IQueryBuilder::PARAM_DATETIME_IMMUTABLE;
248
-			case Types::DATETIME_TZ_IMMUTABLE:
249
-				return IQueryBuilder::PARAM_DATETIME_TZ_IMMUTABLE;
250
-			case Types::TIME:
251
-				return IQueryBuilder::PARAM_TIME_MUTABLE;
252
-			case Types::TIME_IMMUTABLE:
253
-				return IQueryBuilder::PARAM_TIME_IMMUTABLE;
254
-			case Types::JSON:
255
-				return IQueryBuilder::PARAM_JSON;
256
-		}
257
-
258
-		return IQueryBuilder::PARAM_STR;
259
-	}
260
-
261
-	/**
262
-	 * Returns an db result and throws exceptions when there are more or less
263
-	 * results
264
-	 *
265
-	 * @param IQueryBuilder $query
266
-	 * @return array the result as row
267
-	 * @throws Exception
268
-	 * @throws MultipleObjectsReturnedException if more than one item exist
269
-	 * @throws DoesNotExistException if the item does not exist
270
-	 * @see findEntity
271
-	 *
272
-	 * @since 14.0.0
273
-	 */
274
-	protected function findOneQuery(IQueryBuilder $query): array {
275
-		$result = $query->executeQuery();
276
-
277
-		$row = $result->fetch();
278
-		if ($row === false) {
279
-			$result->closeCursor();
280
-			$msg = $this->buildDebugMessage(
281
-				'Did expect one result but found none when executing', $query
282
-			);
283
-			throw new DoesNotExistException($msg);
284
-		}
285
-
286
-		$row2 = $result->fetch();
287
-		$result->closeCursor();
288
-		if ($row2 !== false) {
289
-			$msg = $this->buildDebugMessage(
290
-				'Did not expect more than one result when executing', $query
291
-			);
292
-			throw new MultipleObjectsReturnedException($msg);
293
-		}
294
-
295
-		return $row;
296
-	}
297
-
298
-	/**
299
-	 * @param string $msg
300
-	 * @param IQueryBuilder $sql
301
-	 * @return string
302
-	 * @since 14.0.0
303
-	 */
304
-	private function buildDebugMessage(string $msg, IQueryBuilder $sql): string {
305
-		return $msg
306
-			. ': query "' . $sql->getSQL() . '"; ';
307
-	}
308
-
309
-
310
-	/**
311
-	 * Creates an entity from a row. Automatically determines the entity class
312
-	 * from the current mapper name (MyEntityMapper -> MyEntity)
313
-	 *
314
-	 * @param array $row the row which should be converted to an entity
315
-	 * @return Entity the entity
316
-	 * @psalm-return T the entity
317
-	 * @since 14.0.0
318
-	 */
319
-	protected function mapRowToEntity(array $row): Entity {
320
-		unset($row['DOCTRINE_ROWNUM']); // remove doctrine/dbal helper column
321
-		return \call_user_func($this->entityClass . '::fromRow', $row);
322
-	}
323
-
324
-
325
-	/**
326
-	 * Runs a sql query and returns an array of entities
327
-	 *
328
-	 * @param IQueryBuilder $query
329
-	 * @return list<Entity> all fetched entities
330
-	 * @psalm-return list<T> all fetched entities
331
-	 * @throws Exception
332
-	 * @since 14.0.0
333
-	 */
334
-	protected function findEntities(IQueryBuilder $query): array {
335
-		$result = $query->executeQuery();
336
-		try {
337
-			$entities = [];
338
-			while ($row = $result->fetch()) {
339
-				$entities[] = $this->mapRowToEntity($row);
340
-			}
341
-			return $entities;
342
-		} finally {
343
-			$result->closeCursor();
344
-		}
345
-	}
346
-
347
-	/**
348
-	 * Runs a sql query and yields each resulting entity to obtain database entries in a memory-efficient way
349
-	 *
350
-	 * @param IQueryBuilder $query
351
-	 * @return Generator Generator of fetched entities
352
-	 * @psalm-return Generator<T> Generator of fetched entities
353
-	 * @throws Exception
354
-	 * @since 30.0.0
355
-	 */
356
-	protected function yieldEntities(IQueryBuilder $query): Generator {
357
-		$result = $query->executeQuery();
358
-		try {
359
-			while ($row = $result->fetch()) {
360
-				yield $this->mapRowToEntity($row);
361
-			}
362
-		} finally {
363
-			$result->closeCursor();
364
-		}
365
-	}
366
-
367
-
368
-	/**
369
-	 * Returns an db result and throws exceptions when there are more or less
370
-	 * results
371
-	 *
372
-	 * @param IQueryBuilder $query
373
-	 * @return Entity the entity
374
-	 * @psalm-return T the entity
375
-	 * @throws Exception
376
-	 * @throws MultipleObjectsReturnedException if more than one item exist
377
-	 * @throws DoesNotExistException if the item does not exist
378
-	 * @since 14.0.0
379
-	 */
380
-	protected function findEntity(IQueryBuilder $query): Entity {
381
-		return $this->mapRowToEntity($this->findOneQuery($query));
382
-	}
25
+    /** @var string */
26
+    protected $tableName;
27
+
28
+    /** @var string|class-string<T> */
29
+    protected $entityClass;
30
+
31
+    /** @var IDBConnection */
32
+    protected $db;
33
+
34
+    /**
35
+     * @param IDBConnection $db Instance of the Db abstraction layer
36
+     * @param string $tableName the name of the table. set this to allow entity
37
+     * @param class-string<T>|null $entityClass the name of the entity that the sql should be
38
+     *                                          mapped to queries without using sql
39
+     * @since 14.0.0
40
+     */
41
+    public function __construct(IDBConnection $db, string $tableName, ?string $entityClass = null) {
42
+        $this->db = $db;
43
+        $this->tableName = $tableName;
44
+
45
+        // if not given set the entity name to the class without the mapper part
46
+        // cache it here for later use since reflection is slow
47
+        if ($entityClass === null) {
48
+            $this->entityClass = str_replace('Mapper', '', \get_class($this));
49
+        } else {
50
+            $this->entityClass = $entityClass;
51
+        }
52
+    }
53
+
54
+
55
+    /**
56
+     * @return string the table name
57
+     * @since 14.0.0
58
+     */
59
+    public function getTableName(): string {
60
+        return $this->tableName;
61
+    }
62
+
63
+
64
+    /**
65
+     * Deletes an entity from the table
66
+     *
67
+     * @param Entity $entity the entity that should be deleted
68
+     * @psalm-param T $entity the entity that should be deleted
69
+     * @return Entity the deleted entity
70
+     * @psalm-return T the deleted entity
71
+     * @throws Exception
72
+     * @since 14.0.0
73
+     */
74
+    public function delete(Entity $entity): Entity {
75
+        $qb = $this->db->getQueryBuilder();
76
+
77
+        $idType = $this->getParameterTypeForProperty($entity, 'id');
78
+
79
+        $qb->delete($this->tableName)
80
+            ->where(
81
+                $qb->expr()->eq('id', $qb->createNamedParameter($entity->getId(), $idType))
82
+            );
83
+        $qb->executeStatement();
84
+        return $entity;
85
+    }
86
+
87
+    /**
88
+     * Creates a new entry in the db from an entity
89
+     *
90
+     * @param Entity $entity the entity that should be created
91
+     * @psalm-param T $entity the entity that should be created
92
+     * @return Entity the saved entity with the set id
93
+     * @psalm-return T the saved entity with the set id
94
+     * @throws Exception
95
+     * @since 14.0.0
96
+     */
97
+    public function insert(Entity $entity): Entity {
98
+        // get updated fields to save, fields have to be set using a setter to
99
+        // be saved
100
+        $properties = $entity->getUpdatedFields();
101
+
102
+        $qb = $this->db->getQueryBuilder();
103
+        $qb->insert($this->tableName);
104
+
105
+        // build the fields
106
+        foreach ($properties as $property => $updated) {
107
+            $column = $entity->propertyToColumn($property);
108
+            $getter = 'get' . ucfirst($property);
109
+            $value = $entity->$getter();
110
+
111
+            if ($property === 'id' && $entity->id === null) {
112
+                continue;
113
+            }
114
+            $type = $this->getParameterTypeForProperty($entity, $property);
115
+            $qb->setValue($column, $qb->createNamedParameter($value, $type));
116
+        }
117
+
118
+        if ($entity instanceof SnowflakeAwareEntity) {
119
+            /** @psalm-suppress DocblockTypeContradiction */
120
+            $entity->generateId();
121
+            $qb->executeStatement();
122
+        } elseif ($entity->id === null) {
123
+            $qb->executeStatement();
124
+            // When autoincrement is used id is always an int
125
+            $entity->setId($qb->getLastInsertId());
126
+        } else {
127
+            $qb->executeStatement();
128
+        }
129
+        return $entity;
130
+    }
131
+
132
+    /**
133
+     * Tries to creates a new entry in the db from an entity and
134
+     * updates an existing entry if duplicate keys are detected
135
+     * by the database
136
+     *
137
+     * @param Entity $entity the entity that should be created/updated
138
+     * @psalm-param T $entity the entity that should be created/updated
139
+     * @return Entity the saved entity with the (new) id
140
+     * @psalm-return T the saved entity with the (new) id
141
+     * @throws Exception
142
+     * @throws \InvalidArgumentException if entity has no id
143
+     * @since 15.0.0
144
+     */
145
+    public function insertOrUpdate(Entity $entity): Entity {
146
+        try {
147
+            return $this->insert($entity);
148
+        } catch (Exception $ex) {
149
+            if ($ex->getReason() === Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
150
+                return $this->update($entity);
151
+            }
152
+            throw $ex;
153
+        }
154
+    }
155
+
156
+    /**
157
+     * Updates an entry in the db from an entity
158
+     *
159
+     * @param Entity $entity the entity that should be created
160
+     * @psalm-param T $entity the entity that should be created
161
+     * @return Entity the saved entity with the set id
162
+     * @psalm-return T the saved entity with the set id
163
+     * @throws Exception
164
+     * @throws \InvalidArgumentException if entity has no id
165
+     * @since 14.0.0
166
+     */
167
+    public function update(Entity $entity): Entity {
168
+        // if entity wasn't changed it makes no sense to run a db query
169
+        $properties = $entity->getUpdatedFields();
170
+        if (\count($properties) === 0) {
171
+            return $entity;
172
+        }
173
+
174
+        // entity needs an id
175
+        $id = $entity->getId();
176
+        if ($id === null) {
177
+            throw new \InvalidArgumentException(
178
+                'Entity which should be updated has no id');
179
+        }
180
+
181
+        // get updated fields to save, fields have to be set using a setter to
182
+        // be saved
183
+        // do not update the id field
184
+        unset($properties['id']);
185
+
186
+        $qb = $this->db->getQueryBuilder();
187
+        $qb->update($this->tableName);
188
+
189
+        // build the fields
190
+        foreach ($properties as $property => $updated) {
191
+            $column = $entity->propertyToColumn($property);
192
+            $getter = 'get' . ucfirst($property);
193
+            $value = $entity->$getter();
194
+
195
+            $type = $this->getParameterTypeForProperty($entity, $property);
196
+            $qb->set($column, $qb->createNamedParameter($value, $type));
197
+        }
198
+
199
+        $idType = $this->getParameterTypeForProperty($entity, 'id');
200
+
201
+        $qb->where(
202
+            $qb->expr()->eq('id', $qb->createNamedParameter($id, $idType))
203
+        );
204
+        $qb->executeStatement();
205
+
206
+        return $entity;
207
+    }
208
+
209
+    /**
210
+     * Returns the type parameter for the QueryBuilder for a specific property
211
+     * of the $entity
212
+     *
213
+     * @param Entity $entity The entity to get the types from
214
+     * @psalm-param T $entity
215
+     * @param string $property The property of $entity to get the type for
216
+     * @return int|string
217
+     * @since 16.0.0
218
+     */
219
+    protected function getParameterTypeForProperty(Entity $entity, string $property) {
220
+        $types = $entity->getFieldTypes();
221
+
222
+        if (!isset($types[ $property ])) {
223
+            return IQueryBuilder::PARAM_STR;
224
+        }
225
+
226
+        switch ($types[ $property ]) {
227
+            case 'int':
228
+            case Types::INTEGER:
229
+            case Types::SMALLINT:
230
+                return IQueryBuilder::PARAM_INT;
231
+            case Types::STRING:
232
+                return IQueryBuilder::PARAM_STR;
233
+            case 'bool':
234
+            case Types::BOOLEAN:
235
+                return IQueryBuilder::PARAM_BOOL;
236
+            case Types::BLOB:
237
+                return IQueryBuilder::PARAM_LOB;
238
+            case Types::DATE:
239
+                return IQueryBuilder::PARAM_DATETIME_MUTABLE;
240
+            case Types::DATETIME:
241
+                return IQueryBuilder::PARAM_DATETIME_MUTABLE;
242
+            case Types::DATETIME_TZ:
243
+                return IQueryBuilder::PARAM_DATETIME_TZ_MUTABLE;
244
+            case Types::DATE_IMMUTABLE:
245
+                return IQueryBuilder::PARAM_DATE_IMMUTABLE;
246
+            case Types::DATETIME_IMMUTABLE:
247
+                return IQueryBuilder::PARAM_DATETIME_IMMUTABLE;
248
+            case Types::DATETIME_TZ_IMMUTABLE:
249
+                return IQueryBuilder::PARAM_DATETIME_TZ_IMMUTABLE;
250
+            case Types::TIME:
251
+                return IQueryBuilder::PARAM_TIME_MUTABLE;
252
+            case Types::TIME_IMMUTABLE:
253
+                return IQueryBuilder::PARAM_TIME_IMMUTABLE;
254
+            case Types::JSON:
255
+                return IQueryBuilder::PARAM_JSON;
256
+        }
257
+
258
+        return IQueryBuilder::PARAM_STR;
259
+    }
260
+
261
+    /**
262
+     * Returns an db result and throws exceptions when there are more or less
263
+     * results
264
+     *
265
+     * @param IQueryBuilder $query
266
+     * @return array the result as row
267
+     * @throws Exception
268
+     * @throws MultipleObjectsReturnedException if more than one item exist
269
+     * @throws DoesNotExistException if the item does not exist
270
+     * @see findEntity
271
+     *
272
+     * @since 14.0.0
273
+     */
274
+    protected function findOneQuery(IQueryBuilder $query): array {
275
+        $result = $query->executeQuery();
276
+
277
+        $row = $result->fetch();
278
+        if ($row === false) {
279
+            $result->closeCursor();
280
+            $msg = $this->buildDebugMessage(
281
+                'Did expect one result but found none when executing', $query
282
+            );
283
+            throw new DoesNotExistException($msg);
284
+        }
285
+
286
+        $row2 = $result->fetch();
287
+        $result->closeCursor();
288
+        if ($row2 !== false) {
289
+            $msg = $this->buildDebugMessage(
290
+                'Did not expect more than one result when executing', $query
291
+            );
292
+            throw new MultipleObjectsReturnedException($msg);
293
+        }
294
+
295
+        return $row;
296
+    }
297
+
298
+    /**
299
+     * @param string $msg
300
+     * @param IQueryBuilder $sql
301
+     * @return string
302
+     * @since 14.0.0
303
+     */
304
+    private function buildDebugMessage(string $msg, IQueryBuilder $sql): string {
305
+        return $msg
306
+            . ': query "' . $sql->getSQL() . '"; ';
307
+    }
308
+
309
+
310
+    /**
311
+     * Creates an entity from a row. Automatically determines the entity class
312
+     * from the current mapper name (MyEntityMapper -> MyEntity)
313
+     *
314
+     * @param array $row the row which should be converted to an entity
315
+     * @return Entity the entity
316
+     * @psalm-return T the entity
317
+     * @since 14.0.0
318
+     */
319
+    protected function mapRowToEntity(array $row): Entity {
320
+        unset($row['DOCTRINE_ROWNUM']); // remove doctrine/dbal helper column
321
+        return \call_user_func($this->entityClass . '::fromRow', $row);
322
+    }
323
+
324
+
325
+    /**
326
+     * Runs a sql query and returns an array of entities
327
+     *
328
+     * @param IQueryBuilder $query
329
+     * @return list<Entity> all fetched entities
330
+     * @psalm-return list<T> all fetched entities
331
+     * @throws Exception
332
+     * @since 14.0.0
333
+     */
334
+    protected function findEntities(IQueryBuilder $query): array {
335
+        $result = $query->executeQuery();
336
+        try {
337
+            $entities = [];
338
+            while ($row = $result->fetch()) {
339
+                $entities[] = $this->mapRowToEntity($row);
340
+            }
341
+            return $entities;
342
+        } finally {
343
+            $result->closeCursor();
344
+        }
345
+    }
346
+
347
+    /**
348
+     * Runs a sql query and yields each resulting entity to obtain database entries in a memory-efficient way
349
+     *
350
+     * @param IQueryBuilder $query
351
+     * @return Generator Generator of fetched entities
352
+     * @psalm-return Generator<T> Generator of fetched entities
353
+     * @throws Exception
354
+     * @since 30.0.0
355
+     */
356
+    protected function yieldEntities(IQueryBuilder $query): Generator {
357
+        $result = $query->executeQuery();
358
+        try {
359
+            while ($row = $result->fetch()) {
360
+                yield $this->mapRowToEntity($row);
361
+            }
362
+        } finally {
363
+            $result->closeCursor();
364
+        }
365
+    }
366
+
367
+
368
+    /**
369
+     * Returns an db result and throws exceptions when there are more or less
370
+     * results
371
+     *
372
+     * @param IQueryBuilder $query
373
+     * @return Entity the entity
374
+     * @psalm-return T the entity
375
+     * @throws Exception
376
+     * @throws MultipleObjectsReturnedException if more than one item exist
377
+     * @throws DoesNotExistException if the item does not exist
378
+     * @since 14.0.0
379
+     */
380
+    protected function findEntity(IQueryBuilder $query): Entity {
381
+        return $this->mapRowToEntity($this->findOneQuery($query));
382
+    }
383 383
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -105,7 +105,7 @@  discard block
 block discarded – undo
105 105
 		// build the fields
106 106
 		foreach ($properties as $property => $updated) {
107 107
 			$column = $entity->propertyToColumn($property);
108
-			$getter = 'get' . ucfirst($property);
108
+			$getter = 'get'.ucfirst($property);
109 109
 			$value = $entity->$getter();
110 110
 
111 111
 			if ($property === 'id' && $entity->id === null) {
@@ -189,7 +189,7 @@  discard block
 block discarded – undo
189 189
 		// build the fields
190 190
 		foreach ($properties as $property => $updated) {
191 191
 			$column = $entity->propertyToColumn($property);
192
-			$getter = 'get' . ucfirst($property);
192
+			$getter = 'get'.ucfirst($property);
193 193
 			$value = $entity->$getter();
194 194
 
195 195
 			$type = $this->getParameterTypeForProperty($entity, $property);
@@ -219,11 +219,11 @@  discard block
 block discarded – undo
219 219
 	protected function getParameterTypeForProperty(Entity $entity, string $property) {
220 220
 		$types = $entity->getFieldTypes();
221 221
 
222
-		if (!isset($types[ $property ])) {
222
+		if (!isset($types[$property])) {
223 223
 			return IQueryBuilder::PARAM_STR;
224 224
 		}
225 225
 
226
-		switch ($types[ $property ]) {
226
+		switch ($types[$property]) {
227 227
 			case 'int':
228 228
 			case Types::INTEGER:
229 229
 			case Types::SMALLINT:
@@ -303,7 +303,7 @@  discard block
 block discarded – undo
303 303
 	 */
304 304
 	private function buildDebugMessage(string $msg, IQueryBuilder $sql): string {
305 305
 		return $msg
306
-			. ': query "' . $sql->getSQL() . '"; ';
306
+			. ': query "'.$sql->getSQL().'"; ';
307 307
 	}
308 308
 
309 309
 
@@ -318,7 +318,7 @@  discard block
 block discarded – undo
318 318
 	 */
319 319
 	protected function mapRowToEntity(array $row): Entity {
320 320
 		unset($row['DOCTRINE_ROWNUM']); // remove doctrine/dbal helper column
321
-		return \call_user_func($this->entityClass . '::fromRow', $row);
321
+		return \call_user_func($this->entityClass.'::fromRow', $row);
322 322
 	}
323 323
 
324 324
 
Please login to merge, or discard this patch.
lib/public/Snowflake/Snowflake.php 1 patch
Indentation   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -18,55 +18,55 @@
 block discarded – undo
18 18
  */
19 19
 #[Consumable(since: '33.0.0')]
20 20
 final readonly class Snowflake {
21
-	/**
22
-	 * @psalm-param int<0,1023> $serverId
23
-	 * @psalm-param int<0,4095> $sequenceId
24
-	 * @psalm-param non-negative-int $seconds
25
-	 * @psalm-param int<0,999> $milliseconds
26
-	 */
27
-	public function __construct(
28
-		private int $serverId,
29
-		private int $sequenceId,
30
-		private bool $isCli,
31
-		private int $seconds,
32
-		private int $milliseconds,
33
-		private \DateTimeImmutable $createdAt,
34
-	) {
35
-	}
21
+    /**
22
+     * @psalm-param int<0,1023> $serverId
23
+     * @psalm-param int<0,4095> $sequenceId
24
+     * @psalm-param non-negative-int $seconds
25
+     * @psalm-param int<0,999> $milliseconds
26
+     */
27
+    public function __construct(
28
+        private int $serverId,
29
+        private int $sequenceId,
30
+        private bool $isCli,
31
+        private int $seconds,
32
+        private int $milliseconds,
33
+        private \DateTimeImmutable $createdAt,
34
+    ) {
35
+    }
36 36
 
37
-	/**
38
-	 * @psalm-return int<0,1023>
39
-	 */
40
-	public function getServerId(): int {
41
-		return $this->serverId;
42
-	}
37
+    /**
38
+     * @psalm-return int<0,1023>
39
+     */
40
+    public function getServerId(): int {
41
+        return $this->serverId;
42
+    }
43 43
 
44
-	/**
45
-	 * @psalm-return int<0,4095>
46
-	 */
47
-	public function getSequenceId(): int {
48
-		return $this->sequenceId;
49
-	}
44
+    /**
45
+     * @psalm-return int<0,4095>
46
+     */
47
+    public function getSequenceId(): int {
48
+        return $this->sequenceId;
49
+    }
50 50
 
51
-	public function isCli(): bool {
52
-		return $this->isCli;
53
-	}
51
+    public function isCli(): bool {
52
+        return $this->isCli;
53
+    }
54 54
 
55
-	/**
56
-	 * @psalm-return non-negative-int
57
-	 */
58
-	public function getSeconds(): int {
59
-		return $this->seconds;
60
-	}
55
+    /**
56
+     * @psalm-return non-negative-int
57
+     */
58
+    public function getSeconds(): int {
59
+        return $this->seconds;
60
+    }
61 61
 
62
-	/**
63
-	 * @psalm-return  int<0,999>
64
-	 */
65
-	public function getMilliseconds(): int {
66
-		return $this->milliseconds;
67
-	}
62
+    /**
63
+     * @psalm-return  int<0,999>
64
+     */
65
+    public function getMilliseconds(): int {
66
+        return $this->milliseconds;
67
+    }
68 68
 
69
-	public function getCreatedAt(): \DateTimeImmutable {
70
-		return $this->createdAt;
71
-	}
69
+    public function getCreatedAt(): \DateTimeImmutable {
70
+        return $this->createdAt;
71
+    }
72 72
 }
Please login to merge, or discard this patch.
lib/private/Server.php 2 patches
Indentation   +1392 added lines, -1392 removed lines patch added patch discarded remove patch
@@ -260,1436 +260,1436 @@
 block discarded – undo
260 260
  * TODO: hookup all manager classes
261 261
  */
262 262
 class Server extends ServerContainer implements IServerContainer {
263
-	/** @var string */
264
-	private $webRoot;
265
-
266
-	/**
267
-	 * @param string $webRoot
268
-	 * @param \OC\Config $config
269
-	 */
270
-	public function __construct($webRoot, \OC\Config $config) {
271
-		parent::__construct();
272
-		$this->webRoot = $webRoot;
273
-
274
-		// To find out if we are running from CLI or not
275
-		$this->registerParameter('isCLI', \OC::$CLI);
276
-		$this->registerParameter('serverRoot', \OC::$SERVERROOT);
277
-
278
-		$this->registerService(ContainerInterface::class, function (ContainerInterface $c) {
279
-			return $c;
280
-		});
281
-		$this->registerDeprecatedAlias(\OCP\IServerContainer::class, ContainerInterface::class);
282
-
283
-		$this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
284
-
285
-		$this->registerAlias(\OCP\Calendar\Resource\IManager::class, \OC\Calendar\Resource\Manager::class);
286
-
287
-		$this->registerAlias(\OCP\Calendar\Room\IManager::class, \OC\Calendar\Room\Manager::class);
288
-
289
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
290
-
291
-		$this->registerAlias(\OCP\ContextChat\IContentManager::class, \OC\ContextChat\ContentManager::class);
292
-
293
-		$this->registerAlias(\OCP\DirectEditing\IManager::class, \OC\DirectEditing\Manager::class);
294
-		$this->registerAlias(ITemplateManager::class, TemplateManager::class);
295
-		$this->registerAlias(\OCP\Template\ITemplateManager::class, \OC\Template\TemplateManager::class);
296
-
297
-		$this->registerAlias(IActionFactory::class, ActionFactory::class);
298
-
299
-		$this->registerService(View::class, function (Server $c) {
300
-			return new View();
301
-		}, false);
302
-
303
-		$this->registerService(IPreview::class, function (ContainerInterface $c) {
304
-			return new PreviewManager(
305
-				$c->get(\OCP\IConfig::class),
306
-				$c->get(IRootFolder::class),
307
-				$c->get(IEventDispatcher::class),
308
-				$c->get(GeneratorHelper::class),
309
-				$c->get(ISession::class)->get('user_id'),
310
-				$c->get(Coordinator::class),
311
-				$c->get(IServerContainer::class),
312
-				$c->get(IBinaryFinder::class),
313
-				$c->get(IMagickSupport::class)
314
-			);
315
-		});
316
-		$this->registerAlias(IMimeIconProvider::class, MimeIconProvider::class);
317
-
318
-		$this->registerService(Watcher::class, function (ContainerInterface $c): Watcher {
319
-			return new Watcher(
320
-				$c->get(\OC\Preview\Storage\StorageFactory::class),
321
-				$c->get(PreviewMapper::class),
322
-				$c->get(IDBConnection::class),
323
-			);
324
-		});
325
-
326
-		$this->registerService(IProfiler::class, function (Server $c) {
327
-			return new Profiler($c->get(SystemConfig::class));
328
-		});
329
-
330
-		$this->registerService(Encryption\Manager::class, function (Server $c): Encryption\Manager {
331
-			$view = new View();
332
-			$util = new Encryption\Util(
333
-				$view,
334
-				$c->get(IUserManager::class),
335
-				$c->get(IGroupManager::class),
336
-				$c->get(\OCP\IConfig::class)
337
-			);
338
-			return new Encryption\Manager(
339
-				$c->get(\OCP\IConfig::class),
340
-				$c->get(LoggerInterface::class),
341
-				$c->getL10N('core'),
342
-				new View(),
343
-				$util,
344
-				new ArrayCache()
345
-			);
346
-		});
347
-		$this->registerAlias(\OCP\Encryption\IManager::class, Encryption\Manager::class);
348
-
349
-		$this->registerService(IFile::class, function (ContainerInterface $c) {
350
-			$util = new Encryption\Util(
351
-				new View(),
352
-				$c->get(IUserManager::class),
353
-				$c->get(IGroupManager::class),
354
-				$c->get(\OCP\IConfig::class)
355
-			);
356
-			return new Encryption\File(
357
-				$util,
358
-				$c->get(IRootFolder::class),
359
-				$c->get(\OCP\Share\IManager::class)
360
-			);
361
-		});
362
-
363
-		$this->registerService(IStorage::class, function (ContainerInterface $c) {
364
-			$view = new View();
365
-			$util = new Encryption\Util(
366
-				$view,
367
-				$c->get(IUserManager::class),
368
-				$c->get(IGroupManager::class),
369
-				$c->get(\OCP\IConfig::class)
370
-			);
371
-
372
-			return new Encryption\Keys\Storage(
373
-				$view,
374
-				$util,
375
-				$c->get(ICrypto::class),
376
-				$c->get(\OCP\IConfig::class)
377
-			);
378
-		});
379
-
380
-		$this->registerAlias(\OCP\ITagManager::class, TagManager::class);
381
-
382
-		$this->registerService('SystemTagManagerFactory', function (ContainerInterface $c) {
383
-			/** @var \OCP\IConfig $config */
384
-			$config = $c->get(\OCP\IConfig::class);
385
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
386
-			return new $factoryClass($this);
387
-		});
388
-		$this->registerService(ISystemTagManager::class, function (ContainerInterface $c) {
389
-			return $c->get('SystemTagManagerFactory')->getManager();
390
-		});
391
-		/** @deprecated 19.0.0 */
392
-		$this->registerDeprecatedAlias('SystemTagManager', ISystemTagManager::class);
393
-
394
-		$this->registerService(ISystemTagObjectMapper::class, function (ContainerInterface $c) {
395
-			return $c->get('SystemTagManagerFactory')->getObjectMapper();
396
-		});
397
-		$this->registerAlias(IFileAccess::class, FileAccess::class);
398
-		$this->registerService('RootFolder', function (ContainerInterface $c) {
399
-			$manager = \OC\Files\Filesystem::getMountManager();
400
-			$view = new View();
401
-			/** @var IUserSession $userSession */
402
-			$userSession = $c->get(IUserSession::class);
403
-			$root = new Root(
404
-				$manager,
405
-				$view,
406
-				$userSession->getUser(),
407
-				$c->get(IUserMountCache::class),
408
-				$this->get(LoggerInterface::class),
409
-				$this->get(IUserManager::class),
410
-				$this->get(IEventDispatcher::class),
411
-				$this->get(ICacheFactory::class),
412
-				$this->get(IAppConfig::class),
413
-			);
414
-
415
-			$previewConnector = new \OC\Preview\WatcherConnector(
416
-				$root,
417
-				$c->get(SystemConfig::class),
418
-				$this->get(IEventDispatcher::class)
419
-			);
420
-			$previewConnector->connectWatcher();
421
-
422
-			return $root;
423
-		});
424
-		$this->registerService(HookConnector::class, function (ContainerInterface $c) {
425
-			return new HookConnector(
426
-				$c->get(IRootFolder::class),
427
-				new View(),
428
-				$c->get(IEventDispatcher::class),
429
-				$c->get(LoggerInterface::class)
430
-			);
431
-		});
432
-
433
-		$this->registerService(IRootFolder::class, function (ContainerInterface $c) {
434
-			return new LazyRoot(function () use ($c) {
435
-				return $c->get('RootFolder');
436
-			});
437
-		});
438
-
439
-		$this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
440
-
441
-		$this->registerService(DisplayNameCache::class, function (ContainerInterface $c) {
442
-			return $c->get(\OC\User\Manager::class)->getDisplayNameCache();
443
-		});
444
-
445
-		$this->registerService(\OCP\IGroupManager::class, function (ContainerInterface $c) {
446
-			$groupManager = new \OC\Group\Manager(
447
-				$this->get(IUserManager::class),
448
-				$this->get(IEventDispatcher::class),
449
-				$this->get(LoggerInterface::class),
450
-				$this->get(ICacheFactory::class),
451
-				$this->get(IRemoteAddress::class),
452
-			);
453
-			return $groupManager;
454
-		});
455
-
456
-		$this->registerService(Store::class, function (ContainerInterface $c) {
457
-			$session = $c->get(ISession::class);
458
-			if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
459
-				$tokenProvider = $c->get(IProvider::class);
460
-			} else {
461
-				$tokenProvider = null;
462
-			}
463
-			$logger = $c->get(LoggerInterface::class);
464
-			$crypto = $c->get(ICrypto::class);
465
-			return new Store($session, $logger, $crypto, $tokenProvider);
466
-		});
467
-		$this->registerAlias(IStore::class, Store::class);
468
-		$this->registerAlias(IProvider::class, Authentication\Token\Manager::class);
469
-		$this->registerAlias(OCPIProvider::class, Authentication\Token\Manager::class);
470
-
471
-		$this->registerService(\OC\User\Session::class, function (Server $c) {
472
-			$manager = $c->get(IUserManager::class);
473
-			$session = new \OC\Session\Memory();
474
-			$timeFactory = new TimeFactory();
475
-			// Token providers might require a working database. This code
476
-			// might however be called when Nextcloud is not yet setup.
477
-			if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
478
-				$provider = $c->get(IProvider::class);
479
-			} else {
480
-				$provider = null;
481
-			}
482
-
483
-			$userSession = new \OC\User\Session(
484
-				$manager,
485
-				$session,
486
-				$timeFactory,
487
-				$provider,
488
-				$c->get(\OCP\IConfig::class),
489
-				$c->get(ISecureRandom::class),
490
-				$c->get('LockdownManager'),
491
-				$c->get(LoggerInterface::class),
492
-				$c->get(IEventDispatcher::class),
493
-			);
494
-			/** @deprecated 21.0.0 use BeforeUserCreatedEvent event with the IEventDispatcher instead */
495
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
496
-				\OC_Hook::emit('OC_User', 'pre_createUser', ['run' => true, 'uid' => $uid, 'password' => $password]);
497
-			});
498
-			/** @deprecated 21.0.0 use UserCreatedEvent event with the IEventDispatcher instead */
499
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
500
-				/** @var \OC\User\User $user */
501
-				\OC_Hook::emit('OC_User', 'post_createUser', ['uid' => $user->getUID(), 'password' => $password]);
502
-			});
503
-			/** @deprecated 21.0.0 use BeforeUserDeletedEvent event with the IEventDispatcher instead */
504
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
505
-				/** @var \OC\User\User $user */
506
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', ['run' => true, 'uid' => $user->getUID()]);
507
-			});
508
-			/** @deprecated 21.0.0 use UserDeletedEvent event with the IEventDispatcher instead */
509
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
510
-				/** @var \OC\User\User $user */
511
-				\OC_Hook::emit('OC_User', 'post_deleteUser', ['uid' => $user->getUID()]);
512
-			});
513
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
514
-				/** @var \OC\User\User $user */
515
-				\OC_Hook::emit('OC_User', 'pre_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
516
-			});
517
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
518
-				/** @var \OC\User\User $user */
519
-				\OC_Hook::emit('OC_User', 'post_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
520
-			});
521
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
522
-				\OC_Hook::emit('OC_User', 'pre_login', ['run' => true, 'uid' => $uid, 'password' => $password]);
523
-
524
-				/** @var IEventDispatcher $dispatcher */
525
-				$dispatcher = $this->get(IEventDispatcher::class);
526
-				$dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password));
527
-			});
528
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $loginName, $password, $isTokenLogin) {
529
-				/** @var \OC\User\User $user */
530
-				\OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'loginName' => $loginName, 'password' => $password, 'isTokenLogin' => $isTokenLogin]);
531
-
532
-				/** @var IEventDispatcher $dispatcher */
533
-				$dispatcher = $this->get(IEventDispatcher::class);
534
-				$dispatcher->dispatchTyped(new UserLoggedInEvent($user, $loginName, $password, $isTokenLogin));
535
-			});
536
-			$userSession->listen('\OC\User', 'preRememberedLogin', function ($uid) {
537
-				/** @var IEventDispatcher $dispatcher */
538
-				$dispatcher = $this->get(IEventDispatcher::class);
539
-				$dispatcher->dispatchTyped(new BeforeUserLoggedInWithCookieEvent($uid));
540
-			});
541
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
542
-				/** @var \OC\User\User $user */
543
-				\OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password]);
544
-
545
-				/** @var IEventDispatcher $dispatcher */
546
-				$dispatcher = $this->get(IEventDispatcher::class);
547
-				$dispatcher->dispatchTyped(new UserLoggedInWithCookieEvent($user, $password));
548
-			});
549
-			$userSession->listen('\OC\User', 'logout', function ($user) {
550
-				\OC_Hook::emit('OC_User', 'logout', []);
551
-
552
-				/** @var IEventDispatcher $dispatcher */
553
-				$dispatcher = $this->get(IEventDispatcher::class);
554
-				$dispatcher->dispatchTyped(new BeforeUserLoggedOutEvent($user));
555
-			});
556
-			$userSession->listen('\OC\User', 'postLogout', function ($user) {
557
-				/** @var IEventDispatcher $dispatcher */
558
-				$dispatcher = $this->get(IEventDispatcher::class);
559
-				$dispatcher->dispatchTyped(new UserLoggedOutEvent($user));
560
-			});
561
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
562
-				/** @var \OC\User\User $user */
563
-				\OC_Hook::emit('OC_User', 'changeUser', ['run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue]);
564
-			});
565
-			return $userSession;
566
-		});
567
-		$this->registerAlias(\OCP\IUserSession::class, \OC\User\Session::class);
568
-
569
-		$this->registerAlias(\OCP\Authentication\TwoFactorAuth\IRegistry::class, \OC\Authentication\TwoFactorAuth\Registry::class);
570
-
571
-		$this->registerAlias(INavigationManager::class, \OC\NavigationManager::class);
572
-
573
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
574
-
575
-		$this->registerService(\OC\SystemConfig::class, function ($c) use ($config) {
576
-			return new \OC\SystemConfig($config);
577
-		});
578
-
579
-		$this->registerAlias(IAppConfig::class, \OC\AppConfig::class);
580
-		$this->registerAlias(IUserConfig::class, \OC\Config\UserConfig::class);
581
-		$this->registerAlias(IAppManager::class, AppManager::class);
582
-
583
-		$this->registerService(IFactory::class, function (Server $c) {
584
-			return new \OC\L10N\Factory(
585
-				$c->get(\OCP\IConfig::class),
586
-				$c->getRequest(),
587
-				$c->get(IUserSession::class),
588
-				$c->get(ICacheFactory::class),
589
-				\OC::$SERVERROOT,
590
-				$c->get(IAppManager::class),
591
-			);
592
-		});
593
-
594
-		$this->registerAlias(IURLGenerator::class, URLGenerator::class);
595
-
596
-		$this->registerAlias(ICache::class, Cache\File::class);
597
-		$this->registerService(Factory::class, function (Server $c) {
598
-			$profiler = $c->get(IProfiler::class);
599
-			$logger = $c->get(LoggerInterface::class);
600
-			$serverVersion = $c->get(ServerVersion::class);
601
-			/** @var SystemConfig $config */
602
-			$config = $c->get(SystemConfig::class);
603
-			if (!$config->getValue('installed', false) || (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
604
-				return new \OC\Memcache\Factory(
605
-					$logger,
606
-					$profiler,
607
-					$serverVersion,
608
-					ArrayCache::class,
609
-					ArrayCache::class,
610
-					ArrayCache::class
611
-				);
612
-			}
613
-
614
-			return new \OC\Memcache\Factory(
615
-				$logger,
616
-				$profiler,
617
-				$serverVersion,
618
-				/** @psalm-taint-escape callable */
619
-				$config->getValue('memcache.local', null),
620
-				/** @psalm-taint-escape callable */
621
-				$config->getValue('memcache.distributed', null),
622
-				/** @psalm-taint-escape callable */
623
-				$config->getValue('memcache.locking', null),
624
-				/** @psalm-taint-escape callable */
625
-				$config->getValue('redis_log_file')
626
-			);
627
-		});
628
-		$this->registerAlias(ICacheFactory::class, Factory::class);
629
-
630
-		$this->registerService('RedisFactory', function (Server $c) {
631
-			$systemConfig = $c->get(SystemConfig::class);
632
-			return new RedisFactory($systemConfig, $c->get(IEventLogger::class));
633
-		});
634
-
635
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
636
-			$l10n = $this->get(IFactory::class)->get('lib');
637
-			return new \OC\Activity\Manager(
638
-				$c->getRequest(),
639
-				$c->get(IUserSession::class),
640
-				$c->get(\OCP\IConfig::class),
641
-				$c->get(IValidator::class),
642
-				$c->get(IRichTextFormatter::class),
643
-				$l10n,
644
-				$c->get(ITimeFactory::class),
645
-			);
646
-		});
647
-
648
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
649
-			return new \OC\Activity\EventMerger(
650
-				$c->getL10N('lib')
651
-			);
652
-		});
653
-		$this->registerAlias(IValidator::class, Validator::class);
654
-
655
-		$this->registerService(AvatarManager::class, function (Server $c) {
656
-			return new AvatarManager(
657
-				$c->get(IUserSession::class),
658
-				$c->get(\OC\User\Manager::class),
659
-				$c->getAppDataDir('avatar'),
660
-				$c->getL10N('lib'),
661
-				$c->get(LoggerInterface::class),
662
-				$c->get(\OCP\IConfig::class),
663
-				$c->get(IAccountManager::class),
664
-				$c->get(KnownUserService::class)
665
-			);
666
-		});
667
-
668
-		$this->registerAlias(IAvatarManager::class, AvatarManager::class);
669
-
670
-		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
671
-		$this->registerAlias(\OCP\Support\Subscription\IRegistry::class, \OC\Support\Subscription\Registry::class);
672
-		$this->registerAlias(\OCP\Support\Subscription\IAssertion::class, \OC\Support\Subscription\Assertion::class);
673
-
674
-		/** Only used by the PsrLoggerAdapter should not be used by apps */
675
-		$this->registerService(\OC\Log::class, function (Server $c) {
676
-			$logType = $c->get(AllConfig::class)->getSystemValue('log_type', 'file');
677
-			$factory = new LogFactory($c, $this->get(SystemConfig::class));
678
-			$logger = $factory->get($logType);
679
-			$registry = $c->get(\OCP\Support\CrashReport\IRegistry::class);
680
-
681
-			return new Log($logger, $this->get(SystemConfig::class), crashReporters: $registry);
682
-		});
683
-		// PSR-3 logger
684
-		$this->registerAlias(LoggerInterface::class, PsrLoggerAdapter::class);
685
-
686
-		$this->registerService(ILogFactory::class, function (Server $c) {
687
-			return new LogFactory($c, $this->get(SystemConfig::class));
688
-		});
689
-
690
-		$this->registerAlias(IJobList::class, \OC\BackgroundJob\JobList::class);
691
-
692
-		$this->registerService(Router::class, function (Server $c) {
693
-			$cacheFactory = $c->get(ICacheFactory::class);
694
-			if ($cacheFactory->isLocalCacheAvailable()) {
695
-				$router = $c->resolve(CachingRouter::class);
696
-			} else {
697
-				$router = $c->resolve(Router::class);
698
-			}
699
-			return $router;
700
-		});
701
-		$this->registerAlias(IRouter::class, Router::class);
702
-
703
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
704
-			$config = $c->get(\OCP\IConfig::class);
705
-			if (ltrim($config->getSystemValueString('memcache.distributed', ''), '\\') === \OC\Memcache\Redis::class) {
706
-				$backend = new \OC\Security\RateLimiting\Backend\MemoryCacheBackend(
707
-					$c->get(AllConfig::class),
708
-					$this->get(ICacheFactory::class),
709
-					new \OC\AppFramework\Utility\TimeFactory()
710
-				);
711
-			} else {
712
-				$backend = new \OC\Security\RateLimiting\Backend\DatabaseBackend(
713
-					$c->get(AllConfig::class),
714
-					$c->get(IDBConnection::class),
715
-					new \OC\AppFramework\Utility\TimeFactory()
716
-				);
717
-			}
718
-
719
-			return $backend;
720
-		});
721
-
722
-		$this->registerAlias(\OCP\Security\ISecureRandom::class, SecureRandom::class);
723
-		$this->registerAlias(\OCP\Security\IRemoteHostValidator::class, \OC\Security\RemoteHostValidator::class);
724
-		$this->registerAlias(IVerificationToken::class, VerificationToken::class);
725
-
726
-		$this->registerAlias(ICrypto::class, Crypto::class);
727
-
728
-		$this->registerAlias(IHasher::class, Hasher::class);
729
-
730
-		$this->registerAlias(ICredentialsManager::class, CredentialsManager::class);
731
-
732
-		$this->registerAlias(IDBConnection::class, ConnectionAdapter::class);
733
-		$this->registerService(Connection::class, function (Server $c) {
734
-			$systemConfig = $c->get(SystemConfig::class);
735
-			$factory = new \OC\DB\ConnectionFactory($systemConfig, $c->get(ICacheFactory::class));
736
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
737
-			if (!$factory->isValidType($type)) {
738
-				throw new \OC\DatabaseException('Invalid database type');
739
-			}
740
-			$connection = $factory->getConnection($type, []);
741
-			return $connection;
742
-		});
743
-
744
-		$this->registerAlias(ICertificateManager::class, CertificateManager::class);
745
-		$this->registerAlias(IClientService::class, ClientService::class);
746
-		$this->registerService(NegativeDnsCache::class, function (ContainerInterface $c) {
747
-			return new NegativeDnsCache(
748
-				$c->get(ICacheFactory::class),
749
-			);
750
-		});
751
-		$this->registerDeprecatedAlias('HttpClientService', IClientService::class);
752
-		$this->registerService(IEventLogger::class, function (ContainerInterface $c) {
753
-			return new EventLogger($c->get(SystemConfig::class), $c->get(LoggerInterface::class), $c->get(Log::class));
754
-		});
755
-
756
-		$this->registerService(IQueryLogger::class, function (ContainerInterface $c) {
757
-			$queryLogger = new QueryLogger();
758
-			if ($c->get(SystemConfig::class)->getValue('debug', false)) {
759
-				// In debug mode, module is being activated by default
760
-				$queryLogger->activate();
761
-			}
762
-			return $queryLogger;
763
-		});
764
-
765
-		$this->registerAlias(ITempManager::class, TempManager::class);
766
-		$this->registerAlias(IDateTimeZone::class, DateTimeZone::class);
767
-
768
-		$this->registerService(IDateTimeFormatter::class, function (Server $c) {
769
-			$language = $c->get(\OCP\IConfig::class)->getUserValue($c->get(ISession::class)->get('user_id'), 'core', 'lang', null);
770
-
771
-			return new DateTimeFormatter(
772
-				$c->get(IDateTimeZone::class)->getTimeZone(),
773
-				$c->getL10N('lib', $language)
774
-			);
775
-		});
776
-
777
-		$this->registerService(IUserMountCache::class, function (ContainerInterface $c) {
778
-			$mountCache = $c->get(UserMountCache::class);
779
-			$listener = new UserMountCacheListener($mountCache);
780
-			$listener->listen($c->get(IUserManager::class));
781
-			return $mountCache;
782
-		});
783
-
784
-		$this->registerService(IMountProviderCollection::class, function (ContainerInterface $c) {
785
-			$loader = $c->get(IStorageFactory::class);
786
-			$mountCache = $c->get(IUserMountCache::class);
787
-			$eventLogger = $c->get(IEventLogger::class);
788
-			$manager = new MountProviderCollection($loader, $mountCache, $eventLogger);
789
-
790
-			// builtin providers
791
-
792
-			$config = $c->get(\OCP\IConfig::class);
793
-			$logger = $c->get(LoggerInterface::class);
794
-			$objectStoreConfig = $c->get(PrimaryObjectStoreConfig::class);
795
-			$manager->registerProvider(new CacheMountProvider($config));
796
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
797
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($objectStoreConfig));
798
-			$manager->registerRootProvider(new RootMountProvider($objectStoreConfig, $config));
799
-
800
-			return $manager;
801
-		});
802
-
803
-		$this->registerService(IBus::class, function (ContainerInterface $c) {
804
-			$busClass = $c->get(\OCP\IConfig::class)->getSystemValueString('commandbus');
805
-			if ($busClass) {
806
-				[$app, $class] = explode('::', $busClass, 2);
807
-				if ($c->get(IAppManager::class)->isEnabledForUser($app)) {
808
-					$c->get(IAppManager::class)->loadApp($app);
809
-					return $c->get($class);
810
-				} else {
811
-					throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
812
-				}
813
-			} else {
814
-				$jobList = $c->get(IJobList::class);
815
-				return new CronBus($jobList);
816
-			}
817
-		});
818
-		$this->registerDeprecatedAlias('AsyncCommandBus', IBus::class);
819
-		$this->registerAlias(ITrustedDomainHelper::class, TrustedDomainHelper::class);
820
-		$this->registerAlias(IThrottler::class, Throttler::class);
821
-
822
-		$this->registerService(\OC\Security\Bruteforce\Backend\IBackend::class, function ($c) {
823
-			$config = $c->get(\OCP\IConfig::class);
824
-			if (!$config->getSystemValueBool('auth.bruteforce.protection.force.database', false)
825
-				&& ltrim($config->getSystemValueString('memcache.distributed', ''), '\\') === \OC\Memcache\Redis::class) {
826
-				$backend = $c->get(\OC\Security\Bruteforce\Backend\MemoryCacheBackend::class);
827
-			} else {
828
-				$backend = $c->get(\OC\Security\Bruteforce\Backend\DatabaseBackend::class);
829
-			}
830
-
831
-			return $backend;
832
-		});
833
-
834
-		$this->registerDeprecatedAlias('IntegrityCodeChecker', Checker::class);
835
-		$this->registerService(Checker::class, function (ContainerInterface $c) {
836
-			// IConfig requires a working database. This code
837
-			// might however be called when Nextcloud is not yet setup.
838
-			if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
839
-				$config = $c->get(\OCP\IConfig::class);
840
-				$appConfig = $c->get(\OCP\IAppConfig::class);
841
-			} else {
842
-				$config = null;
843
-				$appConfig = null;
844
-			}
845
-
846
-			return new Checker(
847
-				$c->get(ServerVersion::class),
848
-				$c->get(EnvironmentHelper::class),
849
-				new FileAccessHelper(),
850
-				$config,
851
-				$appConfig,
852
-				$c->get(ICacheFactory::class),
853
-				$c->get(IAppManager::class),
854
-				$c->get(IMimeTypeDetector::class)
855
-			);
856
-		});
857
-		$this->registerService(Request::class, function (ContainerInterface $c) {
858
-			if (isset($this['urlParams'])) {
859
-				$urlParams = $this['urlParams'];
860
-			} else {
861
-				$urlParams = [];
862
-			}
863
-
864
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
865
-				&& in_array('fakeinput', stream_get_wrappers())
866
-			) {
867
-				$stream = 'fakeinput://data';
868
-			} else {
869
-				$stream = 'php://input';
870
-			}
871
-
872
-			return new Request(
873
-				[
874
-					'get' => $_GET,
875
-					'post' => $_POST,
876
-					'files' => $_FILES,
877
-					'server' => $_SERVER,
878
-					'env' => $_ENV,
879
-					'cookies' => $_COOKIE,
880
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
881
-						? $_SERVER['REQUEST_METHOD']
882
-						: '',
883
-					'urlParams' => $urlParams,
884
-				],
885
-				$this->get(IRequestId::class),
886
-				$this->get(\OCP\IConfig::class),
887
-				$this->get(CsrfTokenManager::class),
888
-				$stream
889
-			);
890
-		});
891
-		$this->registerAlias(\OCP\IRequest::class, Request::class);
892
-
893
-		$this->registerService(IRequestId::class, function (ContainerInterface $c): IRequestId {
894
-			return new RequestId(
895
-				$_SERVER['UNIQUE_ID'] ?? '',
896
-				$this->get(ISecureRandom::class)
897
-			);
898
-		});
899
-
900
-		/** @since 32.0.0 */
901
-		$this->registerAlias(IEmailValidator::class, EmailValidator::class);
902
-
903
-		$this->registerService(IMailer::class, function (Server $c) {
904
-			return new Mailer(
905
-				$c->get(\OCP\IConfig::class),
906
-				$c->get(LoggerInterface::class),
907
-				$c->get(Defaults::class),
908
-				$c->get(IURLGenerator::class),
909
-				$c->getL10N('lib'),
910
-				$c->get(IEventDispatcher::class),
911
-				$c->get(IFactory::class),
912
-				$c->get(IEmailValidator::class),
913
-			);
914
-		});
915
-
916
-		/** @since 30.0.0 */
917
-		$this->registerAlias(\OCP\Mail\Provider\IManager::class, \OC\Mail\Provider\Manager::class);
918
-
919
-		$this->registerService(ILDAPProviderFactory::class, function (ContainerInterface $c) {
920
-			$config = $c->get(\OCP\IConfig::class);
921
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
922
-			if (is_null($factoryClass) || !class_exists($factoryClass)) {
923
-				return new NullLDAPProviderFactory($this);
924
-			}
925
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
926
-			return new $factoryClass($this);
927
-		});
928
-		$this->registerService(ILDAPProvider::class, function (ContainerInterface $c) {
929
-			$factory = $c->get(ILDAPProviderFactory::class);
930
-			return $factory->getLDAPProvider();
931
-		});
932
-		$this->registerService(ILockingProvider::class, function (ContainerInterface $c) {
933
-			$ini = $c->get(IniGetWrapper::class);
934
-			$config = $c->get(\OCP\IConfig::class);
935
-			$ttl = $config->getSystemValueInt('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
936
-			if ($config->getSystemValueBool('filelocking.enabled', true) || (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
937
-				/** @var \OC\Memcache\Factory $memcacheFactory */
938
-				$memcacheFactory = $c->get(ICacheFactory::class);
939
-				$memcache = $memcacheFactory->createLocking('lock');
940
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
941
-					$timeFactory = $c->get(ITimeFactory::class);
942
-					return new MemcacheLockingProvider($memcache, $timeFactory, $ttl);
943
-				}
944
-				return new DBLockingProvider(
945
-					$c->get(IDBConnection::class),
946
-					new TimeFactory(),
947
-					$ttl,
948
-					!\OC::$CLI
949
-				);
950
-			}
951
-			return new NoopLockingProvider();
952
-		});
953
-
954
-		$this->registerService(ILockManager::class, function (Server $c): LockManager {
955
-			return new LockManager();
956
-		});
957
-
958
-		$this->registerAlias(ILockdownManager::class, 'LockdownManager');
959
-		$this->registerService(SetupManager::class, function ($c) {
960
-			// create the setupmanager through the mount manager to resolve the cyclic dependency
961
-			return $c->get(\OC\Files\Mount\Manager::class)->getSetupManager();
962
-		});
963
-		$this->registerAlias(IMountManager::class, \OC\Files\Mount\Manager::class);
964
-
965
-		$this->registerService(IMimeTypeDetector::class, function (ContainerInterface $c) {
966
-			return new \OC\Files\Type\Detection(
967
-				$c->get(IURLGenerator::class),
968
-				$c->get(LoggerInterface::class),
969
-				\OC::$configDir,
970
-				\OC::$SERVERROOT . '/resources/config/'
971
-			);
972
-		});
973
-
974
-		$this->registerAlias(IMimeTypeLoader::class, Loader::class);
975
-		$this->registerService(BundleFetcher::class, function () {
976
-			return new BundleFetcher($this->getL10N('lib'));
977
-		});
978
-		$this->registerAlias(\OCP\Notification\IManager::class, Manager::class);
979
-
980
-		$this->registerService(CapabilitiesManager::class, function (ContainerInterface $c) {
981
-			$manager = new CapabilitiesManager($c->get(LoggerInterface::class));
982
-			$manager->registerCapability(function () use ($c) {
983
-				return new \OC\OCS\CoreCapabilities($c->get(\OCP\IConfig::class));
984
-			});
985
-			$manager->registerCapability(function () use ($c) {
986
-				return $c->get(\OC\Security\Bruteforce\Capabilities::class);
987
-			});
988
-			return $manager;
989
-		});
990
-
991
-		$this->registerService(ICommentsManager::class, function (Server $c) {
992
-			$config = $c->get(\OCP\IConfig::class);
993
-			$factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
994
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
995
-			$factory = new $factoryClass($this);
996
-			$manager = $factory->getManager();
997
-
998
-			$manager->registerDisplayNameResolver('user', function ($id) use ($c) {
999
-				$manager = $c->get(IUserManager::class);
1000
-				$userDisplayName = $manager->getDisplayName($id);
1001
-				if ($userDisplayName === null) {
1002
-					$l = $c->get(IFactory::class)->get('core');
1003
-					return $l->t('Unknown account');
1004
-				}
1005
-				return $userDisplayName;
1006
-			});
1007
-
1008
-			return $manager;
1009
-		});
1010
-
1011
-		$this->registerAlias(\OC_Defaults::class, 'ThemingDefaults');
1012
-		$this->registerService('ThemingDefaults', function (Server $c) {
1013
-			try {
1014
-				$classExists = class_exists('OCA\Theming\ThemingDefaults');
1015
-			} catch (\OCP\AutoloadNotAllowedException $e) {
1016
-				// App disabled or in maintenance mode
1017
-				$classExists = false;
1018
-			}
1019
-
1020
-			if ($classExists && $c->get(\OCP\IConfig::class)->getSystemValueBool('installed', false) && $c->get(IAppManager::class)->isEnabledForAnyone('theming') && $c->get(TrustedDomainHelper::class)->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
1021
-				$backgroundService = new BackgroundService(
1022
-					$c->get(IRootFolder::class),
1023
-					$c->get(IAppDataFactory::class)->get('theming'),
1024
-					$c->get(IAppConfig::class),
1025
-					$c->get(\OCP\IConfig::class),
1026
-					$c->get(ISession::class)->get('user_id'),
1027
-				);
1028
-				$imageManager = new ImageManager(
1029
-					$c->get(\OCP\IConfig::class),
1030
-					$c->get(IAppDataFactory::class)->get('theming'),
1031
-					$c->get(IURLGenerator::class),
1032
-					$c->get(ICacheFactory::class),
1033
-					$c->get(LoggerInterface::class),
1034
-					$c->get(ITempManager::class),
1035
-					$backgroundService,
1036
-				);
1037
-				return new ThemingDefaults(
1038
-					new AppConfig(
1039
-						$c->get(\OCP\IConfig::class),
1040
-						$c->get(\OCP\IAppConfig::class),
1041
-						'theming',
1042
-					),
1043
-					$c->get(IUserConfig::class),
1044
-					$c->get(IFactory::class)->get('theming'),
1045
-					$c->get(IUserSession::class),
1046
-					$c->get(IURLGenerator::class),
1047
-					$c->get(ICacheFactory::class),
1048
-					new Util(
1049
-						$c->get(ServerVersion::class),
1050
-						$c->get(\OCP\IConfig::class),
1051
-						$this->get(IAppManager::class),
1052
-						$c->get(IAppDataFactory::class)->get('theming'),
1053
-						$imageManager,
1054
-					),
1055
-					$imageManager,
1056
-					$c->get(IAppManager::class),
1057
-					$c->get(INavigationManager::class),
1058
-					$backgroundService,
1059
-				);
1060
-			}
1061
-			return new \OC_Defaults();
1062
-		});
1063
-		$this->registerService(JSCombiner::class, function (Server $c) {
1064
-			return new JSCombiner(
1065
-				$c->getAppDataDir('js'),
1066
-				$c->get(IURLGenerator::class),
1067
-				$this->get(ICacheFactory::class),
1068
-				$c->get(\OCP\IConfig::class),
1069
-				$c->get(LoggerInterface::class)
1070
-			);
1071
-		});
1072
-		$this->registerAlias(\OCP\EventDispatcher\IEventDispatcher::class, \OC\EventDispatcher\EventDispatcher::class);
1073
-
1074
-		$this->registerService('CryptoWrapper', function (ContainerInterface $c) {
1075
-			// FIXME: Instantiated here due to cyclic dependency
1076
-			$request = new Request(
1077
-				[
1078
-					'get' => $_GET,
1079
-					'post' => $_POST,
1080
-					'files' => $_FILES,
1081
-					'server' => $_SERVER,
1082
-					'env' => $_ENV,
1083
-					'cookies' => $_COOKIE,
1084
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
1085
-						? $_SERVER['REQUEST_METHOD']
1086
-						: null,
1087
-				],
1088
-				$c->get(IRequestId::class),
1089
-				$c->get(\OCP\IConfig::class)
1090
-			);
1091
-
1092
-			return new CryptoWrapper(
1093
-				$c->get(ICrypto::class),
1094
-				$c->get(ISecureRandom::class),
1095
-				$request
1096
-			);
1097
-		});
1098
-		$this->registerService(SessionStorage::class, function (ContainerInterface $c) {
1099
-			return new SessionStorage($c->get(ISession::class));
1100
-		});
1101
-		$this->registerAlias(\OCP\Security\IContentSecurityPolicyManager::class, ContentSecurityPolicyManager::class);
1102
-
1103
-		$this->registerService(IProviderFactory::class, function (ContainerInterface $c) {
1104
-			$config = $c->get(\OCP\IConfig::class);
1105
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1106
-			/** @var \OCP\Share\IProviderFactory $factory */
1107
-			return $c->get($factoryClass);
1108
-		});
1109
-
1110
-		$this->registerAlias(\OCP\Share\IManager::class, \OC\Share20\Manager::class);
1111
-
1112
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function (Server $c) {
1113
-			$instance = new Collaboration\Collaborators\Search($c);
1114
-
1115
-			// register default plugins
1116
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1117
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserByMailPlugin::class]);
1118
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1119
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailByMailPlugin::class]);
1120
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1121
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE_GROUP', 'class' => RemoteGroupPlugin::class]);
1122
-
1123
-			return $instance;
1124
-		});
1125
-		$this->registerAlias(\OCP\Collaboration\Collaborators\ISearchResult::class, \OC\Collaboration\Collaborators\SearchResult::class);
1126
-
1127
-		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1128
-
1129
-		$this->registerAlias(\OCP\Collaboration\Resources\IProviderManager::class, \OC\Collaboration\Resources\ProviderManager::class);
1130
-		$this->registerAlias(\OCP\Collaboration\Resources\IManager::class, \OC\Collaboration\Resources\Manager::class);
1131
-
1132
-		$this->registerAlias(IReferenceManager::class, ReferenceManager::class);
1133
-		$this->registerAlias(ITeamManager::class, TeamManager::class);
1134
-
1135
-		$this->registerDeprecatedAlias('SettingsManager', \OC\Settings\Manager::class);
1136
-		$this->registerAlias(\OCP\Settings\IManager::class, \OC\Settings\Manager::class);
1137
-		$this->registerService(\OC\Files\AppData\Factory::class, function (ContainerInterface $c) {
1138
-			return new \OC\Files\AppData\Factory(
1139
-				$c->get(IRootFolder::class),
1140
-				$c->get(SystemConfig::class)
1141
-			);
1142
-		});
1143
-
1144
-		$this->registerService('LockdownManager', function (ContainerInterface $c) {
1145
-			return new LockdownManager(function () use ($c) {
1146
-				return $c->get(ISession::class);
1147
-			});
1148
-		});
1149
-
1150
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (ContainerInterface $c) {
1151
-			return new DiscoveryService(
1152
-				$c->get(ICacheFactory::class),
1153
-				$c->get(IClientService::class)
1154
-			);
1155
-		});
1156
-		$this->registerAlias(IOCMDiscoveryService::class, OCMDiscoveryService::class);
1157
-
1158
-		$this->registerService(ICloudIdManager::class, function (ContainerInterface $c) {
1159
-			return new CloudIdManager(
1160
-				$c->get(ICacheFactory::class),
1161
-				$c->get(IEventDispatcher::class),
1162
-				$c->get(\OCP\Contacts\IManager::class),
1163
-				$c->get(IURLGenerator::class),
1164
-				$c->get(IUserManager::class),
1165
-			);
1166
-		});
263
+    /** @var string */
264
+    private $webRoot;
265
+
266
+    /**
267
+     * @param string $webRoot
268
+     * @param \OC\Config $config
269
+     */
270
+    public function __construct($webRoot, \OC\Config $config) {
271
+        parent::__construct();
272
+        $this->webRoot = $webRoot;
273
+
274
+        // To find out if we are running from CLI or not
275
+        $this->registerParameter('isCLI', \OC::$CLI);
276
+        $this->registerParameter('serverRoot', \OC::$SERVERROOT);
277
+
278
+        $this->registerService(ContainerInterface::class, function (ContainerInterface $c) {
279
+            return $c;
280
+        });
281
+        $this->registerDeprecatedAlias(\OCP\IServerContainer::class, ContainerInterface::class);
282
+
283
+        $this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
284
+
285
+        $this->registerAlias(\OCP\Calendar\Resource\IManager::class, \OC\Calendar\Resource\Manager::class);
286
+
287
+        $this->registerAlias(\OCP\Calendar\Room\IManager::class, \OC\Calendar\Room\Manager::class);
288
+
289
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
290
+
291
+        $this->registerAlias(\OCP\ContextChat\IContentManager::class, \OC\ContextChat\ContentManager::class);
292
+
293
+        $this->registerAlias(\OCP\DirectEditing\IManager::class, \OC\DirectEditing\Manager::class);
294
+        $this->registerAlias(ITemplateManager::class, TemplateManager::class);
295
+        $this->registerAlias(\OCP\Template\ITemplateManager::class, \OC\Template\TemplateManager::class);
296
+
297
+        $this->registerAlias(IActionFactory::class, ActionFactory::class);
298
+
299
+        $this->registerService(View::class, function (Server $c) {
300
+            return new View();
301
+        }, false);
302
+
303
+        $this->registerService(IPreview::class, function (ContainerInterface $c) {
304
+            return new PreviewManager(
305
+                $c->get(\OCP\IConfig::class),
306
+                $c->get(IRootFolder::class),
307
+                $c->get(IEventDispatcher::class),
308
+                $c->get(GeneratorHelper::class),
309
+                $c->get(ISession::class)->get('user_id'),
310
+                $c->get(Coordinator::class),
311
+                $c->get(IServerContainer::class),
312
+                $c->get(IBinaryFinder::class),
313
+                $c->get(IMagickSupport::class)
314
+            );
315
+        });
316
+        $this->registerAlias(IMimeIconProvider::class, MimeIconProvider::class);
317
+
318
+        $this->registerService(Watcher::class, function (ContainerInterface $c): Watcher {
319
+            return new Watcher(
320
+                $c->get(\OC\Preview\Storage\StorageFactory::class),
321
+                $c->get(PreviewMapper::class),
322
+                $c->get(IDBConnection::class),
323
+            );
324
+        });
325
+
326
+        $this->registerService(IProfiler::class, function (Server $c) {
327
+            return new Profiler($c->get(SystemConfig::class));
328
+        });
329
+
330
+        $this->registerService(Encryption\Manager::class, function (Server $c): Encryption\Manager {
331
+            $view = new View();
332
+            $util = new Encryption\Util(
333
+                $view,
334
+                $c->get(IUserManager::class),
335
+                $c->get(IGroupManager::class),
336
+                $c->get(\OCP\IConfig::class)
337
+            );
338
+            return new Encryption\Manager(
339
+                $c->get(\OCP\IConfig::class),
340
+                $c->get(LoggerInterface::class),
341
+                $c->getL10N('core'),
342
+                new View(),
343
+                $util,
344
+                new ArrayCache()
345
+            );
346
+        });
347
+        $this->registerAlias(\OCP\Encryption\IManager::class, Encryption\Manager::class);
348
+
349
+        $this->registerService(IFile::class, function (ContainerInterface $c) {
350
+            $util = new Encryption\Util(
351
+                new View(),
352
+                $c->get(IUserManager::class),
353
+                $c->get(IGroupManager::class),
354
+                $c->get(\OCP\IConfig::class)
355
+            );
356
+            return new Encryption\File(
357
+                $util,
358
+                $c->get(IRootFolder::class),
359
+                $c->get(\OCP\Share\IManager::class)
360
+            );
361
+        });
362
+
363
+        $this->registerService(IStorage::class, function (ContainerInterface $c) {
364
+            $view = new View();
365
+            $util = new Encryption\Util(
366
+                $view,
367
+                $c->get(IUserManager::class),
368
+                $c->get(IGroupManager::class),
369
+                $c->get(\OCP\IConfig::class)
370
+            );
371
+
372
+            return new Encryption\Keys\Storage(
373
+                $view,
374
+                $util,
375
+                $c->get(ICrypto::class),
376
+                $c->get(\OCP\IConfig::class)
377
+            );
378
+        });
379
+
380
+        $this->registerAlias(\OCP\ITagManager::class, TagManager::class);
381
+
382
+        $this->registerService('SystemTagManagerFactory', function (ContainerInterface $c) {
383
+            /** @var \OCP\IConfig $config */
384
+            $config = $c->get(\OCP\IConfig::class);
385
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
386
+            return new $factoryClass($this);
387
+        });
388
+        $this->registerService(ISystemTagManager::class, function (ContainerInterface $c) {
389
+            return $c->get('SystemTagManagerFactory')->getManager();
390
+        });
391
+        /** @deprecated 19.0.0 */
392
+        $this->registerDeprecatedAlias('SystemTagManager', ISystemTagManager::class);
393
+
394
+        $this->registerService(ISystemTagObjectMapper::class, function (ContainerInterface $c) {
395
+            return $c->get('SystemTagManagerFactory')->getObjectMapper();
396
+        });
397
+        $this->registerAlias(IFileAccess::class, FileAccess::class);
398
+        $this->registerService('RootFolder', function (ContainerInterface $c) {
399
+            $manager = \OC\Files\Filesystem::getMountManager();
400
+            $view = new View();
401
+            /** @var IUserSession $userSession */
402
+            $userSession = $c->get(IUserSession::class);
403
+            $root = new Root(
404
+                $manager,
405
+                $view,
406
+                $userSession->getUser(),
407
+                $c->get(IUserMountCache::class),
408
+                $this->get(LoggerInterface::class),
409
+                $this->get(IUserManager::class),
410
+                $this->get(IEventDispatcher::class),
411
+                $this->get(ICacheFactory::class),
412
+                $this->get(IAppConfig::class),
413
+            );
414
+
415
+            $previewConnector = new \OC\Preview\WatcherConnector(
416
+                $root,
417
+                $c->get(SystemConfig::class),
418
+                $this->get(IEventDispatcher::class)
419
+            );
420
+            $previewConnector->connectWatcher();
421
+
422
+            return $root;
423
+        });
424
+        $this->registerService(HookConnector::class, function (ContainerInterface $c) {
425
+            return new HookConnector(
426
+                $c->get(IRootFolder::class),
427
+                new View(),
428
+                $c->get(IEventDispatcher::class),
429
+                $c->get(LoggerInterface::class)
430
+            );
431
+        });
432
+
433
+        $this->registerService(IRootFolder::class, function (ContainerInterface $c) {
434
+            return new LazyRoot(function () use ($c) {
435
+                return $c->get('RootFolder');
436
+            });
437
+        });
438
+
439
+        $this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
440
+
441
+        $this->registerService(DisplayNameCache::class, function (ContainerInterface $c) {
442
+            return $c->get(\OC\User\Manager::class)->getDisplayNameCache();
443
+        });
444
+
445
+        $this->registerService(\OCP\IGroupManager::class, function (ContainerInterface $c) {
446
+            $groupManager = new \OC\Group\Manager(
447
+                $this->get(IUserManager::class),
448
+                $this->get(IEventDispatcher::class),
449
+                $this->get(LoggerInterface::class),
450
+                $this->get(ICacheFactory::class),
451
+                $this->get(IRemoteAddress::class),
452
+            );
453
+            return $groupManager;
454
+        });
455
+
456
+        $this->registerService(Store::class, function (ContainerInterface $c) {
457
+            $session = $c->get(ISession::class);
458
+            if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
459
+                $tokenProvider = $c->get(IProvider::class);
460
+            } else {
461
+                $tokenProvider = null;
462
+            }
463
+            $logger = $c->get(LoggerInterface::class);
464
+            $crypto = $c->get(ICrypto::class);
465
+            return new Store($session, $logger, $crypto, $tokenProvider);
466
+        });
467
+        $this->registerAlias(IStore::class, Store::class);
468
+        $this->registerAlias(IProvider::class, Authentication\Token\Manager::class);
469
+        $this->registerAlias(OCPIProvider::class, Authentication\Token\Manager::class);
470
+
471
+        $this->registerService(\OC\User\Session::class, function (Server $c) {
472
+            $manager = $c->get(IUserManager::class);
473
+            $session = new \OC\Session\Memory();
474
+            $timeFactory = new TimeFactory();
475
+            // Token providers might require a working database. This code
476
+            // might however be called when Nextcloud is not yet setup.
477
+            if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
478
+                $provider = $c->get(IProvider::class);
479
+            } else {
480
+                $provider = null;
481
+            }
482
+
483
+            $userSession = new \OC\User\Session(
484
+                $manager,
485
+                $session,
486
+                $timeFactory,
487
+                $provider,
488
+                $c->get(\OCP\IConfig::class),
489
+                $c->get(ISecureRandom::class),
490
+                $c->get('LockdownManager'),
491
+                $c->get(LoggerInterface::class),
492
+                $c->get(IEventDispatcher::class),
493
+            );
494
+            /** @deprecated 21.0.0 use BeforeUserCreatedEvent event with the IEventDispatcher instead */
495
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
496
+                \OC_Hook::emit('OC_User', 'pre_createUser', ['run' => true, 'uid' => $uid, 'password' => $password]);
497
+            });
498
+            /** @deprecated 21.0.0 use UserCreatedEvent event with the IEventDispatcher instead */
499
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
500
+                /** @var \OC\User\User $user */
501
+                \OC_Hook::emit('OC_User', 'post_createUser', ['uid' => $user->getUID(), 'password' => $password]);
502
+            });
503
+            /** @deprecated 21.0.0 use BeforeUserDeletedEvent event with the IEventDispatcher instead */
504
+            $userSession->listen('\OC\User', 'preDelete', function ($user) {
505
+                /** @var \OC\User\User $user */
506
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', ['run' => true, 'uid' => $user->getUID()]);
507
+            });
508
+            /** @deprecated 21.0.0 use UserDeletedEvent event with the IEventDispatcher instead */
509
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
510
+                /** @var \OC\User\User $user */
511
+                \OC_Hook::emit('OC_User', 'post_deleteUser', ['uid' => $user->getUID()]);
512
+            });
513
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
514
+                /** @var \OC\User\User $user */
515
+                \OC_Hook::emit('OC_User', 'pre_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
516
+            });
517
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
518
+                /** @var \OC\User\User $user */
519
+                \OC_Hook::emit('OC_User', 'post_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
520
+            });
521
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
522
+                \OC_Hook::emit('OC_User', 'pre_login', ['run' => true, 'uid' => $uid, 'password' => $password]);
523
+
524
+                /** @var IEventDispatcher $dispatcher */
525
+                $dispatcher = $this->get(IEventDispatcher::class);
526
+                $dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password));
527
+            });
528
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $loginName, $password, $isTokenLogin) {
529
+                /** @var \OC\User\User $user */
530
+                \OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'loginName' => $loginName, 'password' => $password, 'isTokenLogin' => $isTokenLogin]);
531
+
532
+                /** @var IEventDispatcher $dispatcher */
533
+                $dispatcher = $this->get(IEventDispatcher::class);
534
+                $dispatcher->dispatchTyped(new UserLoggedInEvent($user, $loginName, $password, $isTokenLogin));
535
+            });
536
+            $userSession->listen('\OC\User', 'preRememberedLogin', function ($uid) {
537
+                /** @var IEventDispatcher $dispatcher */
538
+                $dispatcher = $this->get(IEventDispatcher::class);
539
+                $dispatcher->dispatchTyped(new BeforeUserLoggedInWithCookieEvent($uid));
540
+            });
541
+            $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
542
+                /** @var \OC\User\User $user */
543
+                \OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password]);
544
+
545
+                /** @var IEventDispatcher $dispatcher */
546
+                $dispatcher = $this->get(IEventDispatcher::class);
547
+                $dispatcher->dispatchTyped(new UserLoggedInWithCookieEvent($user, $password));
548
+            });
549
+            $userSession->listen('\OC\User', 'logout', function ($user) {
550
+                \OC_Hook::emit('OC_User', 'logout', []);
551
+
552
+                /** @var IEventDispatcher $dispatcher */
553
+                $dispatcher = $this->get(IEventDispatcher::class);
554
+                $dispatcher->dispatchTyped(new BeforeUserLoggedOutEvent($user));
555
+            });
556
+            $userSession->listen('\OC\User', 'postLogout', function ($user) {
557
+                /** @var IEventDispatcher $dispatcher */
558
+                $dispatcher = $this->get(IEventDispatcher::class);
559
+                $dispatcher->dispatchTyped(new UserLoggedOutEvent($user));
560
+            });
561
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
562
+                /** @var \OC\User\User $user */
563
+                \OC_Hook::emit('OC_User', 'changeUser', ['run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue]);
564
+            });
565
+            return $userSession;
566
+        });
567
+        $this->registerAlias(\OCP\IUserSession::class, \OC\User\Session::class);
568
+
569
+        $this->registerAlias(\OCP\Authentication\TwoFactorAuth\IRegistry::class, \OC\Authentication\TwoFactorAuth\Registry::class);
570
+
571
+        $this->registerAlias(INavigationManager::class, \OC\NavigationManager::class);
572
+
573
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
574
+
575
+        $this->registerService(\OC\SystemConfig::class, function ($c) use ($config) {
576
+            return new \OC\SystemConfig($config);
577
+        });
578
+
579
+        $this->registerAlias(IAppConfig::class, \OC\AppConfig::class);
580
+        $this->registerAlias(IUserConfig::class, \OC\Config\UserConfig::class);
581
+        $this->registerAlias(IAppManager::class, AppManager::class);
582
+
583
+        $this->registerService(IFactory::class, function (Server $c) {
584
+            return new \OC\L10N\Factory(
585
+                $c->get(\OCP\IConfig::class),
586
+                $c->getRequest(),
587
+                $c->get(IUserSession::class),
588
+                $c->get(ICacheFactory::class),
589
+                \OC::$SERVERROOT,
590
+                $c->get(IAppManager::class),
591
+            );
592
+        });
593
+
594
+        $this->registerAlias(IURLGenerator::class, URLGenerator::class);
595
+
596
+        $this->registerAlias(ICache::class, Cache\File::class);
597
+        $this->registerService(Factory::class, function (Server $c) {
598
+            $profiler = $c->get(IProfiler::class);
599
+            $logger = $c->get(LoggerInterface::class);
600
+            $serverVersion = $c->get(ServerVersion::class);
601
+            /** @var SystemConfig $config */
602
+            $config = $c->get(SystemConfig::class);
603
+            if (!$config->getValue('installed', false) || (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
604
+                return new \OC\Memcache\Factory(
605
+                    $logger,
606
+                    $profiler,
607
+                    $serverVersion,
608
+                    ArrayCache::class,
609
+                    ArrayCache::class,
610
+                    ArrayCache::class
611
+                );
612
+            }
613
+
614
+            return new \OC\Memcache\Factory(
615
+                $logger,
616
+                $profiler,
617
+                $serverVersion,
618
+                /** @psalm-taint-escape callable */
619
+                $config->getValue('memcache.local', null),
620
+                /** @psalm-taint-escape callable */
621
+                $config->getValue('memcache.distributed', null),
622
+                /** @psalm-taint-escape callable */
623
+                $config->getValue('memcache.locking', null),
624
+                /** @psalm-taint-escape callable */
625
+                $config->getValue('redis_log_file')
626
+            );
627
+        });
628
+        $this->registerAlias(ICacheFactory::class, Factory::class);
629
+
630
+        $this->registerService('RedisFactory', function (Server $c) {
631
+            $systemConfig = $c->get(SystemConfig::class);
632
+            return new RedisFactory($systemConfig, $c->get(IEventLogger::class));
633
+        });
634
+
635
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
636
+            $l10n = $this->get(IFactory::class)->get('lib');
637
+            return new \OC\Activity\Manager(
638
+                $c->getRequest(),
639
+                $c->get(IUserSession::class),
640
+                $c->get(\OCP\IConfig::class),
641
+                $c->get(IValidator::class),
642
+                $c->get(IRichTextFormatter::class),
643
+                $l10n,
644
+                $c->get(ITimeFactory::class),
645
+            );
646
+        });
647
+
648
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
649
+            return new \OC\Activity\EventMerger(
650
+                $c->getL10N('lib')
651
+            );
652
+        });
653
+        $this->registerAlias(IValidator::class, Validator::class);
654
+
655
+        $this->registerService(AvatarManager::class, function (Server $c) {
656
+            return new AvatarManager(
657
+                $c->get(IUserSession::class),
658
+                $c->get(\OC\User\Manager::class),
659
+                $c->getAppDataDir('avatar'),
660
+                $c->getL10N('lib'),
661
+                $c->get(LoggerInterface::class),
662
+                $c->get(\OCP\IConfig::class),
663
+                $c->get(IAccountManager::class),
664
+                $c->get(KnownUserService::class)
665
+            );
666
+        });
667
+
668
+        $this->registerAlias(IAvatarManager::class, AvatarManager::class);
669
+
670
+        $this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
671
+        $this->registerAlias(\OCP\Support\Subscription\IRegistry::class, \OC\Support\Subscription\Registry::class);
672
+        $this->registerAlias(\OCP\Support\Subscription\IAssertion::class, \OC\Support\Subscription\Assertion::class);
673
+
674
+        /** Only used by the PsrLoggerAdapter should not be used by apps */
675
+        $this->registerService(\OC\Log::class, function (Server $c) {
676
+            $logType = $c->get(AllConfig::class)->getSystemValue('log_type', 'file');
677
+            $factory = new LogFactory($c, $this->get(SystemConfig::class));
678
+            $logger = $factory->get($logType);
679
+            $registry = $c->get(\OCP\Support\CrashReport\IRegistry::class);
680
+
681
+            return new Log($logger, $this->get(SystemConfig::class), crashReporters: $registry);
682
+        });
683
+        // PSR-3 logger
684
+        $this->registerAlias(LoggerInterface::class, PsrLoggerAdapter::class);
685
+
686
+        $this->registerService(ILogFactory::class, function (Server $c) {
687
+            return new LogFactory($c, $this->get(SystemConfig::class));
688
+        });
689
+
690
+        $this->registerAlias(IJobList::class, \OC\BackgroundJob\JobList::class);
691
+
692
+        $this->registerService(Router::class, function (Server $c) {
693
+            $cacheFactory = $c->get(ICacheFactory::class);
694
+            if ($cacheFactory->isLocalCacheAvailable()) {
695
+                $router = $c->resolve(CachingRouter::class);
696
+            } else {
697
+                $router = $c->resolve(Router::class);
698
+            }
699
+            return $router;
700
+        });
701
+        $this->registerAlias(IRouter::class, Router::class);
702
+
703
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
704
+            $config = $c->get(\OCP\IConfig::class);
705
+            if (ltrim($config->getSystemValueString('memcache.distributed', ''), '\\') === \OC\Memcache\Redis::class) {
706
+                $backend = new \OC\Security\RateLimiting\Backend\MemoryCacheBackend(
707
+                    $c->get(AllConfig::class),
708
+                    $this->get(ICacheFactory::class),
709
+                    new \OC\AppFramework\Utility\TimeFactory()
710
+                );
711
+            } else {
712
+                $backend = new \OC\Security\RateLimiting\Backend\DatabaseBackend(
713
+                    $c->get(AllConfig::class),
714
+                    $c->get(IDBConnection::class),
715
+                    new \OC\AppFramework\Utility\TimeFactory()
716
+                );
717
+            }
718
+
719
+            return $backend;
720
+        });
721
+
722
+        $this->registerAlias(\OCP\Security\ISecureRandom::class, SecureRandom::class);
723
+        $this->registerAlias(\OCP\Security\IRemoteHostValidator::class, \OC\Security\RemoteHostValidator::class);
724
+        $this->registerAlias(IVerificationToken::class, VerificationToken::class);
725
+
726
+        $this->registerAlias(ICrypto::class, Crypto::class);
727
+
728
+        $this->registerAlias(IHasher::class, Hasher::class);
729
+
730
+        $this->registerAlias(ICredentialsManager::class, CredentialsManager::class);
731
+
732
+        $this->registerAlias(IDBConnection::class, ConnectionAdapter::class);
733
+        $this->registerService(Connection::class, function (Server $c) {
734
+            $systemConfig = $c->get(SystemConfig::class);
735
+            $factory = new \OC\DB\ConnectionFactory($systemConfig, $c->get(ICacheFactory::class));
736
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
737
+            if (!$factory->isValidType($type)) {
738
+                throw new \OC\DatabaseException('Invalid database type');
739
+            }
740
+            $connection = $factory->getConnection($type, []);
741
+            return $connection;
742
+        });
743
+
744
+        $this->registerAlias(ICertificateManager::class, CertificateManager::class);
745
+        $this->registerAlias(IClientService::class, ClientService::class);
746
+        $this->registerService(NegativeDnsCache::class, function (ContainerInterface $c) {
747
+            return new NegativeDnsCache(
748
+                $c->get(ICacheFactory::class),
749
+            );
750
+        });
751
+        $this->registerDeprecatedAlias('HttpClientService', IClientService::class);
752
+        $this->registerService(IEventLogger::class, function (ContainerInterface $c) {
753
+            return new EventLogger($c->get(SystemConfig::class), $c->get(LoggerInterface::class), $c->get(Log::class));
754
+        });
755
+
756
+        $this->registerService(IQueryLogger::class, function (ContainerInterface $c) {
757
+            $queryLogger = new QueryLogger();
758
+            if ($c->get(SystemConfig::class)->getValue('debug', false)) {
759
+                // In debug mode, module is being activated by default
760
+                $queryLogger->activate();
761
+            }
762
+            return $queryLogger;
763
+        });
764
+
765
+        $this->registerAlias(ITempManager::class, TempManager::class);
766
+        $this->registerAlias(IDateTimeZone::class, DateTimeZone::class);
767
+
768
+        $this->registerService(IDateTimeFormatter::class, function (Server $c) {
769
+            $language = $c->get(\OCP\IConfig::class)->getUserValue($c->get(ISession::class)->get('user_id'), 'core', 'lang', null);
770
+
771
+            return new DateTimeFormatter(
772
+                $c->get(IDateTimeZone::class)->getTimeZone(),
773
+                $c->getL10N('lib', $language)
774
+            );
775
+        });
776
+
777
+        $this->registerService(IUserMountCache::class, function (ContainerInterface $c) {
778
+            $mountCache = $c->get(UserMountCache::class);
779
+            $listener = new UserMountCacheListener($mountCache);
780
+            $listener->listen($c->get(IUserManager::class));
781
+            return $mountCache;
782
+        });
783
+
784
+        $this->registerService(IMountProviderCollection::class, function (ContainerInterface $c) {
785
+            $loader = $c->get(IStorageFactory::class);
786
+            $mountCache = $c->get(IUserMountCache::class);
787
+            $eventLogger = $c->get(IEventLogger::class);
788
+            $manager = new MountProviderCollection($loader, $mountCache, $eventLogger);
789
+
790
+            // builtin providers
791
+
792
+            $config = $c->get(\OCP\IConfig::class);
793
+            $logger = $c->get(LoggerInterface::class);
794
+            $objectStoreConfig = $c->get(PrimaryObjectStoreConfig::class);
795
+            $manager->registerProvider(new CacheMountProvider($config));
796
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
797
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($objectStoreConfig));
798
+            $manager->registerRootProvider(new RootMountProvider($objectStoreConfig, $config));
799
+
800
+            return $manager;
801
+        });
802
+
803
+        $this->registerService(IBus::class, function (ContainerInterface $c) {
804
+            $busClass = $c->get(\OCP\IConfig::class)->getSystemValueString('commandbus');
805
+            if ($busClass) {
806
+                [$app, $class] = explode('::', $busClass, 2);
807
+                if ($c->get(IAppManager::class)->isEnabledForUser($app)) {
808
+                    $c->get(IAppManager::class)->loadApp($app);
809
+                    return $c->get($class);
810
+                } else {
811
+                    throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
812
+                }
813
+            } else {
814
+                $jobList = $c->get(IJobList::class);
815
+                return new CronBus($jobList);
816
+            }
817
+        });
818
+        $this->registerDeprecatedAlias('AsyncCommandBus', IBus::class);
819
+        $this->registerAlias(ITrustedDomainHelper::class, TrustedDomainHelper::class);
820
+        $this->registerAlias(IThrottler::class, Throttler::class);
821
+
822
+        $this->registerService(\OC\Security\Bruteforce\Backend\IBackend::class, function ($c) {
823
+            $config = $c->get(\OCP\IConfig::class);
824
+            if (!$config->getSystemValueBool('auth.bruteforce.protection.force.database', false)
825
+                && ltrim($config->getSystemValueString('memcache.distributed', ''), '\\') === \OC\Memcache\Redis::class) {
826
+                $backend = $c->get(\OC\Security\Bruteforce\Backend\MemoryCacheBackend::class);
827
+            } else {
828
+                $backend = $c->get(\OC\Security\Bruteforce\Backend\DatabaseBackend::class);
829
+            }
830
+
831
+            return $backend;
832
+        });
833
+
834
+        $this->registerDeprecatedAlias('IntegrityCodeChecker', Checker::class);
835
+        $this->registerService(Checker::class, function (ContainerInterface $c) {
836
+            // IConfig requires a working database. This code
837
+            // might however be called when Nextcloud is not yet setup.
838
+            if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
839
+                $config = $c->get(\OCP\IConfig::class);
840
+                $appConfig = $c->get(\OCP\IAppConfig::class);
841
+            } else {
842
+                $config = null;
843
+                $appConfig = null;
844
+            }
845
+
846
+            return new Checker(
847
+                $c->get(ServerVersion::class),
848
+                $c->get(EnvironmentHelper::class),
849
+                new FileAccessHelper(),
850
+                $config,
851
+                $appConfig,
852
+                $c->get(ICacheFactory::class),
853
+                $c->get(IAppManager::class),
854
+                $c->get(IMimeTypeDetector::class)
855
+            );
856
+        });
857
+        $this->registerService(Request::class, function (ContainerInterface $c) {
858
+            if (isset($this['urlParams'])) {
859
+                $urlParams = $this['urlParams'];
860
+            } else {
861
+                $urlParams = [];
862
+            }
863
+
864
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
865
+                && in_array('fakeinput', stream_get_wrappers())
866
+            ) {
867
+                $stream = 'fakeinput://data';
868
+            } else {
869
+                $stream = 'php://input';
870
+            }
871
+
872
+            return new Request(
873
+                [
874
+                    'get' => $_GET,
875
+                    'post' => $_POST,
876
+                    'files' => $_FILES,
877
+                    'server' => $_SERVER,
878
+                    'env' => $_ENV,
879
+                    'cookies' => $_COOKIE,
880
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
881
+                        ? $_SERVER['REQUEST_METHOD']
882
+                        : '',
883
+                    'urlParams' => $urlParams,
884
+                ],
885
+                $this->get(IRequestId::class),
886
+                $this->get(\OCP\IConfig::class),
887
+                $this->get(CsrfTokenManager::class),
888
+                $stream
889
+            );
890
+        });
891
+        $this->registerAlias(\OCP\IRequest::class, Request::class);
892
+
893
+        $this->registerService(IRequestId::class, function (ContainerInterface $c): IRequestId {
894
+            return new RequestId(
895
+                $_SERVER['UNIQUE_ID'] ?? '',
896
+                $this->get(ISecureRandom::class)
897
+            );
898
+        });
899
+
900
+        /** @since 32.0.0 */
901
+        $this->registerAlias(IEmailValidator::class, EmailValidator::class);
902
+
903
+        $this->registerService(IMailer::class, function (Server $c) {
904
+            return new Mailer(
905
+                $c->get(\OCP\IConfig::class),
906
+                $c->get(LoggerInterface::class),
907
+                $c->get(Defaults::class),
908
+                $c->get(IURLGenerator::class),
909
+                $c->getL10N('lib'),
910
+                $c->get(IEventDispatcher::class),
911
+                $c->get(IFactory::class),
912
+                $c->get(IEmailValidator::class),
913
+            );
914
+        });
915
+
916
+        /** @since 30.0.0 */
917
+        $this->registerAlias(\OCP\Mail\Provider\IManager::class, \OC\Mail\Provider\Manager::class);
918
+
919
+        $this->registerService(ILDAPProviderFactory::class, function (ContainerInterface $c) {
920
+            $config = $c->get(\OCP\IConfig::class);
921
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
922
+            if (is_null($factoryClass) || !class_exists($factoryClass)) {
923
+                return new NullLDAPProviderFactory($this);
924
+            }
925
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
926
+            return new $factoryClass($this);
927
+        });
928
+        $this->registerService(ILDAPProvider::class, function (ContainerInterface $c) {
929
+            $factory = $c->get(ILDAPProviderFactory::class);
930
+            return $factory->getLDAPProvider();
931
+        });
932
+        $this->registerService(ILockingProvider::class, function (ContainerInterface $c) {
933
+            $ini = $c->get(IniGetWrapper::class);
934
+            $config = $c->get(\OCP\IConfig::class);
935
+            $ttl = $config->getSystemValueInt('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
936
+            if ($config->getSystemValueBool('filelocking.enabled', true) || (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
937
+                /** @var \OC\Memcache\Factory $memcacheFactory */
938
+                $memcacheFactory = $c->get(ICacheFactory::class);
939
+                $memcache = $memcacheFactory->createLocking('lock');
940
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
941
+                    $timeFactory = $c->get(ITimeFactory::class);
942
+                    return new MemcacheLockingProvider($memcache, $timeFactory, $ttl);
943
+                }
944
+                return new DBLockingProvider(
945
+                    $c->get(IDBConnection::class),
946
+                    new TimeFactory(),
947
+                    $ttl,
948
+                    !\OC::$CLI
949
+                );
950
+            }
951
+            return new NoopLockingProvider();
952
+        });
953
+
954
+        $this->registerService(ILockManager::class, function (Server $c): LockManager {
955
+            return new LockManager();
956
+        });
957
+
958
+        $this->registerAlias(ILockdownManager::class, 'LockdownManager');
959
+        $this->registerService(SetupManager::class, function ($c) {
960
+            // create the setupmanager through the mount manager to resolve the cyclic dependency
961
+            return $c->get(\OC\Files\Mount\Manager::class)->getSetupManager();
962
+        });
963
+        $this->registerAlias(IMountManager::class, \OC\Files\Mount\Manager::class);
964
+
965
+        $this->registerService(IMimeTypeDetector::class, function (ContainerInterface $c) {
966
+            return new \OC\Files\Type\Detection(
967
+                $c->get(IURLGenerator::class),
968
+                $c->get(LoggerInterface::class),
969
+                \OC::$configDir,
970
+                \OC::$SERVERROOT . '/resources/config/'
971
+            );
972
+        });
973
+
974
+        $this->registerAlias(IMimeTypeLoader::class, Loader::class);
975
+        $this->registerService(BundleFetcher::class, function () {
976
+            return new BundleFetcher($this->getL10N('lib'));
977
+        });
978
+        $this->registerAlias(\OCP\Notification\IManager::class, Manager::class);
979
+
980
+        $this->registerService(CapabilitiesManager::class, function (ContainerInterface $c) {
981
+            $manager = new CapabilitiesManager($c->get(LoggerInterface::class));
982
+            $manager->registerCapability(function () use ($c) {
983
+                return new \OC\OCS\CoreCapabilities($c->get(\OCP\IConfig::class));
984
+            });
985
+            $manager->registerCapability(function () use ($c) {
986
+                return $c->get(\OC\Security\Bruteforce\Capabilities::class);
987
+            });
988
+            return $manager;
989
+        });
990
+
991
+        $this->registerService(ICommentsManager::class, function (Server $c) {
992
+            $config = $c->get(\OCP\IConfig::class);
993
+            $factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
994
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
995
+            $factory = new $factoryClass($this);
996
+            $manager = $factory->getManager();
997
+
998
+            $manager->registerDisplayNameResolver('user', function ($id) use ($c) {
999
+                $manager = $c->get(IUserManager::class);
1000
+                $userDisplayName = $manager->getDisplayName($id);
1001
+                if ($userDisplayName === null) {
1002
+                    $l = $c->get(IFactory::class)->get('core');
1003
+                    return $l->t('Unknown account');
1004
+                }
1005
+                return $userDisplayName;
1006
+            });
1007
+
1008
+            return $manager;
1009
+        });
1010
+
1011
+        $this->registerAlias(\OC_Defaults::class, 'ThemingDefaults');
1012
+        $this->registerService('ThemingDefaults', function (Server $c) {
1013
+            try {
1014
+                $classExists = class_exists('OCA\Theming\ThemingDefaults');
1015
+            } catch (\OCP\AutoloadNotAllowedException $e) {
1016
+                // App disabled or in maintenance mode
1017
+                $classExists = false;
1018
+            }
1019
+
1020
+            if ($classExists && $c->get(\OCP\IConfig::class)->getSystemValueBool('installed', false) && $c->get(IAppManager::class)->isEnabledForAnyone('theming') && $c->get(TrustedDomainHelper::class)->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
1021
+                $backgroundService = new BackgroundService(
1022
+                    $c->get(IRootFolder::class),
1023
+                    $c->get(IAppDataFactory::class)->get('theming'),
1024
+                    $c->get(IAppConfig::class),
1025
+                    $c->get(\OCP\IConfig::class),
1026
+                    $c->get(ISession::class)->get('user_id'),
1027
+                );
1028
+                $imageManager = new ImageManager(
1029
+                    $c->get(\OCP\IConfig::class),
1030
+                    $c->get(IAppDataFactory::class)->get('theming'),
1031
+                    $c->get(IURLGenerator::class),
1032
+                    $c->get(ICacheFactory::class),
1033
+                    $c->get(LoggerInterface::class),
1034
+                    $c->get(ITempManager::class),
1035
+                    $backgroundService,
1036
+                );
1037
+                return new ThemingDefaults(
1038
+                    new AppConfig(
1039
+                        $c->get(\OCP\IConfig::class),
1040
+                        $c->get(\OCP\IAppConfig::class),
1041
+                        'theming',
1042
+                    ),
1043
+                    $c->get(IUserConfig::class),
1044
+                    $c->get(IFactory::class)->get('theming'),
1045
+                    $c->get(IUserSession::class),
1046
+                    $c->get(IURLGenerator::class),
1047
+                    $c->get(ICacheFactory::class),
1048
+                    new Util(
1049
+                        $c->get(ServerVersion::class),
1050
+                        $c->get(\OCP\IConfig::class),
1051
+                        $this->get(IAppManager::class),
1052
+                        $c->get(IAppDataFactory::class)->get('theming'),
1053
+                        $imageManager,
1054
+                    ),
1055
+                    $imageManager,
1056
+                    $c->get(IAppManager::class),
1057
+                    $c->get(INavigationManager::class),
1058
+                    $backgroundService,
1059
+                );
1060
+            }
1061
+            return new \OC_Defaults();
1062
+        });
1063
+        $this->registerService(JSCombiner::class, function (Server $c) {
1064
+            return new JSCombiner(
1065
+                $c->getAppDataDir('js'),
1066
+                $c->get(IURLGenerator::class),
1067
+                $this->get(ICacheFactory::class),
1068
+                $c->get(\OCP\IConfig::class),
1069
+                $c->get(LoggerInterface::class)
1070
+            );
1071
+        });
1072
+        $this->registerAlias(\OCP\EventDispatcher\IEventDispatcher::class, \OC\EventDispatcher\EventDispatcher::class);
1073
+
1074
+        $this->registerService('CryptoWrapper', function (ContainerInterface $c) {
1075
+            // FIXME: Instantiated here due to cyclic dependency
1076
+            $request = new Request(
1077
+                [
1078
+                    'get' => $_GET,
1079
+                    'post' => $_POST,
1080
+                    'files' => $_FILES,
1081
+                    'server' => $_SERVER,
1082
+                    'env' => $_ENV,
1083
+                    'cookies' => $_COOKIE,
1084
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
1085
+                        ? $_SERVER['REQUEST_METHOD']
1086
+                        : null,
1087
+                ],
1088
+                $c->get(IRequestId::class),
1089
+                $c->get(\OCP\IConfig::class)
1090
+            );
1091
+
1092
+            return new CryptoWrapper(
1093
+                $c->get(ICrypto::class),
1094
+                $c->get(ISecureRandom::class),
1095
+                $request
1096
+            );
1097
+        });
1098
+        $this->registerService(SessionStorage::class, function (ContainerInterface $c) {
1099
+            return new SessionStorage($c->get(ISession::class));
1100
+        });
1101
+        $this->registerAlias(\OCP\Security\IContentSecurityPolicyManager::class, ContentSecurityPolicyManager::class);
1102
+
1103
+        $this->registerService(IProviderFactory::class, function (ContainerInterface $c) {
1104
+            $config = $c->get(\OCP\IConfig::class);
1105
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1106
+            /** @var \OCP\Share\IProviderFactory $factory */
1107
+            return $c->get($factoryClass);
1108
+        });
1109
+
1110
+        $this->registerAlias(\OCP\Share\IManager::class, \OC\Share20\Manager::class);
1111
+
1112
+        $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function (Server $c) {
1113
+            $instance = new Collaboration\Collaborators\Search($c);
1114
+
1115
+            // register default plugins
1116
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1117
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserByMailPlugin::class]);
1118
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1119
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailByMailPlugin::class]);
1120
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1121
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE_GROUP', 'class' => RemoteGroupPlugin::class]);
1122
+
1123
+            return $instance;
1124
+        });
1125
+        $this->registerAlias(\OCP\Collaboration\Collaborators\ISearchResult::class, \OC\Collaboration\Collaborators\SearchResult::class);
1126
+
1127
+        $this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1128
+
1129
+        $this->registerAlias(\OCP\Collaboration\Resources\IProviderManager::class, \OC\Collaboration\Resources\ProviderManager::class);
1130
+        $this->registerAlias(\OCP\Collaboration\Resources\IManager::class, \OC\Collaboration\Resources\Manager::class);
1131
+
1132
+        $this->registerAlias(IReferenceManager::class, ReferenceManager::class);
1133
+        $this->registerAlias(ITeamManager::class, TeamManager::class);
1134
+
1135
+        $this->registerDeprecatedAlias('SettingsManager', \OC\Settings\Manager::class);
1136
+        $this->registerAlias(\OCP\Settings\IManager::class, \OC\Settings\Manager::class);
1137
+        $this->registerService(\OC\Files\AppData\Factory::class, function (ContainerInterface $c) {
1138
+            return new \OC\Files\AppData\Factory(
1139
+                $c->get(IRootFolder::class),
1140
+                $c->get(SystemConfig::class)
1141
+            );
1142
+        });
1143
+
1144
+        $this->registerService('LockdownManager', function (ContainerInterface $c) {
1145
+            return new LockdownManager(function () use ($c) {
1146
+                return $c->get(ISession::class);
1147
+            });
1148
+        });
1149
+
1150
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (ContainerInterface $c) {
1151
+            return new DiscoveryService(
1152
+                $c->get(ICacheFactory::class),
1153
+                $c->get(IClientService::class)
1154
+            );
1155
+        });
1156
+        $this->registerAlias(IOCMDiscoveryService::class, OCMDiscoveryService::class);
1157
+
1158
+        $this->registerService(ICloudIdManager::class, function (ContainerInterface $c) {
1159
+            return new CloudIdManager(
1160
+                $c->get(ICacheFactory::class),
1161
+                $c->get(IEventDispatcher::class),
1162
+                $c->get(\OCP\Contacts\IManager::class),
1163
+                $c->get(IURLGenerator::class),
1164
+                $c->get(IUserManager::class),
1165
+            );
1166
+        });
1167 1167
 
1168
-		$this->registerAlias(\OCP\GlobalScale\IConfig::class, \OC\GlobalScale\Config::class);
1169
-		$this->registerAlias(ICloudFederationProviderManager::class, CloudFederationProviderManager::class);
1170
-		$this->registerService(ICloudFederationFactory::class, function (Server $c) {
1171
-			return new CloudFederationFactory();
1172
-		});
1168
+        $this->registerAlias(\OCP\GlobalScale\IConfig::class, \OC\GlobalScale\Config::class);
1169
+        $this->registerAlias(ICloudFederationProviderManager::class, CloudFederationProviderManager::class);
1170
+        $this->registerService(ICloudFederationFactory::class, function (Server $c) {
1171
+            return new CloudFederationFactory();
1172
+        });
1173 1173
 
1174
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1174
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1175 1175
 
1176
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1177
-		$this->registerAlias(\Psr\Clock\ClockInterface::class, \OCP\AppFramework\Utility\ITimeFactory::class);
1176
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1177
+        $this->registerAlias(\Psr\Clock\ClockInterface::class, \OCP\AppFramework\Utility\ITimeFactory::class);
1178 1178
 
1179
-		$this->registerService(Defaults::class, function (Server $c) {
1180
-			return new Defaults(
1181
-				$c->get('ThemingDefaults')
1182
-			);
1183
-		});
1179
+        $this->registerService(Defaults::class, function (Server $c) {
1180
+            return new Defaults(
1181
+                $c->get('ThemingDefaults')
1182
+            );
1183
+        });
1184 1184
 
1185
-		$this->registerService(\OCP\ISession::class, function (ContainerInterface $c) {
1186
-			return $c->get(\OCP\IUserSession::class)->getSession();
1187
-		}, false);
1185
+        $this->registerService(\OCP\ISession::class, function (ContainerInterface $c) {
1186
+            return $c->get(\OCP\IUserSession::class)->getSession();
1187
+        }, false);
1188 1188
 
1189
-		$this->registerService(IShareHelper::class, function (ContainerInterface $c) {
1190
-			return new ShareHelper(
1191
-				$c->get(\OCP\Share\IManager::class)
1192
-			);
1193
-		});
1189
+        $this->registerService(IShareHelper::class, function (ContainerInterface $c) {
1190
+            return new ShareHelper(
1191
+                $c->get(\OCP\Share\IManager::class)
1192
+            );
1193
+        });
1194 1194
 
1195
-		$this->registerService(IApiFactory::class, function (ContainerInterface $c) {
1196
-			return new ApiFactory($c->get(IClientService::class));
1197
-		});
1195
+        $this->registerService(IApiFactory::class, function (ContainerInterface $c) {
1196
+            return new ApiFactory($c->get(IClientService::class));
1197
+        });
1198 1198
 
1199
-		$this->registerService(IInstanceFactory::class, function (ContainerInterface $c) {
1200
-			$memcacheFactory = $c->get(ICacheFactory::class);
1201
-			return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->get(IClientService::class));
1202
-		});
1199
+        $this->registerService(IInstanceFactory::class, function (ContainerInterface $c) {
1200
+            $memcacheFactory = $c->get(ICacheFactory::class);
1201
+            return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->get(IClientService::class));
1202
+        });
1203 1203
 
1204
-		$this->registerAlias(IContactsStore::class, ContactsStore::class);
1205
-		$this->registerAlias(IAccountManager::class, AccountManager::class);
1204
+        $this->registerAlias(IContactsStore::class, ContactsStore::class);
1205
+        $this->registerAlias(IAccountManager::class, AccountManager::class);
1206 1206
 
1207
-		$this->registerAlias(IStorageFactory::class, StorageFactory::class);
1207
+        $this->registerAlias(IStorageFactory::class, StorageFactory::class);
1208 1208
 
1209
-		$this->registerAlias(\OCP\Dashboard\IManager::class, \OC\Dashboard\Manager::class);
1209
+        $this->registerAlias(\OCP\Dashboard\IManager::class, \OC\Dashboard\Manager::class);
1210 1210
 
1211
-		$this->registerAlias(IFullTextSearchManager::class, FullTextSearchManager::class);
1212
-		$this->registerAlias(IFilesMetadataManager::class, FilesMetadataManager::class);
1211
+        $this->registerAlias(IFullTextSearchManager::class, FullTextSearchManager::class);
1212
+        $this->registerAlias(IFilesMetadataManager::class, FilesMetadataManager::class);
1213 1213
 
1214
-		$this->registerAlias(ISubAdmin::class, SubAdmin::class);
1214
+        $this->registerAlias(ISubAdmin::class, SubAdmin::class);
1215 1215
 
1216
-		$this->registerAlias(IInitialStateService::class, InitialStateService::class);
1216
+        $this->registerAlias(IInitialStateService::class, InitialStateService::class);
1217 1217
 
1218
-		$this->registerAlias(\OCP\IEmojiHelper::class, \OC\EmojiHelper::class);
1218
+        $this->registerAlias(\OCP\IEmojiHelper::class, \OC\EmojiHelper::class);
1219 1219
 
1220
-		$this->registerAlias(\OCP\UserStatus\IManager::class, \OC\UserStatus\Manager::class);
1220
+        $this->registerAlias(\OCP\UserStatus\IManager::class, \OC\UserStatus\Manager::class);
1221 1221
 
1222
-		$this->registerAlias(IBroker::class, Broker::class);
1222
+        $this->registerAlias(IBroker::class, Broker::class);
1223 1223
 
1224
-		$this->registerAlias(\OCP\Files\AppData\IAppDataFactory::class, \OC\Files\AppData\Factory::class);
1224
+        $this->registerAlias(\OCP\Files\AppData\IAppDataFactory::class, \OC\Files\AppData\Factory::class);
1225 1225
 
1226
-		$this->registerAlias(\OCP\Files\IFilenameValidator::class, \OC\Files\FilenameValidator::class);
1226
+        $this->registerAlias(\OCP\Files\IFilenameValidator::class, \OC\Files\FilenameValidator::class);
1227 1227
 
1228
-		$this->registerAlias(IBinaryFinder::class, BinaryFinder::class);
1228
+        $this->registerAlias(IBinaryFinder::class, BinaryFinder::class);
1229 1229
 
1230
-		$this->registerAlias(\OCP\Share\IPublicShareTemplateFactory::class, \OC\Share20\PublicShareTemplateFactory::class);
1230
+        $this->registerAlias(\OCP\Share\IPublicShareTemplateFactory::class, \OC\Share20\PublicShareTemplateFactory::class);
1231 1231
 
1232
-		$this->registerAlias(ITranslationManager::class, TranslationManager::class);
1232
+        $this->registerAlias(ITranslationManager::class, TranslationManager::class);
1233 1233
 
1234
-		$this->registerAlias(IConversionManager::class, ConversionManager::class);
1234
+        $this->registerAlias(IConversionManager::class, ConversionManager::class);
1235 1235
 
1236
-		$this->registerAlias(ISpeechToTextManager::class, SpeechToTextManager::class);
1236
+        $this->registerAlias(ISpeechToTextManager::class, SpeechToTextManager::class);
1237 1237
 
1238
-		$this->registerAlias(IEventSourceFactory::class, EventSourceFactory::class);
1238
+        $this->registerAlias(IEventSourceFactory::class, EventSourceFactory::class);
1239 1239
 
1240
-		$this->registerAlias(\OCP\TextProcessing\IManager::class, \OC\TextProcessing\Manager::class);
1240
+        $this->registerAlias(\OCP\TextProcessing\IManager::class, \OC\TextProcessing\Manager::class);
1241 1241
 
1242
-		$this->registerAlias(\OCP\TextToImage\IManager::class, \OC\TextToImage\Manager::class);
1242
+        $this->registerAlias(\OCP\TextToImage\IManager::class, \OC\TextToImage\Manager::class);
1243 1243
 
1244
-		$this->registerAlias(ILimiter::class, Limiter::class);
1244
+        $this->registerAlias(ILimiter::class, Limiter::class);
1245 1245
 
1246
-		$this->registerAlias(IPhoneNumberUtil::class, PhoneNumberUtil::class);
1246
+        $this->registerAlias(IPhoneNumberUtil::class, PhoneNumberUtil::class);
1247 1247
 
1248
-		// there is no reason for having OCMProvider as a Service
1249
-		$this->registerDeprecatedAlias(ICapabilityAwareOCMProvider::class, OCMProvider::class);
1250
-		$this->registerDeprecatedAlias(IOCMProvider::class, OCMProvider::class);
1248
+        // there is no reason for having OCMProvider as a Service
1249
+        $this->registerDeprecatedAlias(ICapabilityAwareOCMProvider::class, OCMProvider::class);
1250
+        $this->registerDeprecatedAlias(IOCMProvider::class, OCMProvider::class);
1251 1251
 
1252
-		$this->registerAlias(ISetupCheckManager::class, SetupCheckManager::class);
1252
+        $this->registerAlias(ISetupCheckManager::class, SetupCheckManager::class);
1253 1253
 
1254
-		$this->registerAlias(IProfileManager::class, ProfileManager::class);
1254
+        $this->registerAlias(IProfileManager::class, ProfileManager::class);
1255 1255
 
1256
-		$this->registerAlias(IAvailabilityCoordinator::class, AvailabilityCoordinator::class);
1256
+        $this->registerAlias(IAvailabilityCoordinator::class, AvailabilityCoordinator::class);
1257 1257
 
1258
-		$this->registerAlias(IDeclarativeManager::class, DeclarativeManager::class);
1258
+        $this->registerAlias(IDeclarativeManager::class, DeclarativeManager::class);
1259 1259
 
1260
-		$this->registerAlias(\OCP\TaskProcessing\IManager::class, \OC\TaskProcessing\Manager::class);
1260
+        $this->registerAlias(\OCP\TaskProcessing\IManager::class, \OC\TaskProcessing\Manager::class);
1261 1261
 
1262
-		$this->registerAlias(IRemoteAddress::class, RemoteAddress::class);
1262
+        $this->registerAlias(IRemoteAddress::class, RemoteAddress::class);
1263 1263
 
1264
-		$this->registerAlias(\OCP\Security\Ip\IFactory::class, \OC\Security\Ip\Factory::class);
1264
+        $this->registerAlias(\OCP\Security\Ip\IFactory::class, \OC\Security\Ip\Factory::class);
1265 1265
 
1266
-		$this->registerAlias(IRichTextFormatter::class, \OC\RichObjectStrings\RichTextFormatter::class);
1266
+        $this->registerAlias(IRichTextFormatter::class, \OC\RichObjectStrings\RichTextFormatter::class);
1267 1267
 
1268
-		$this->registerAlias(ISignatureManager::class, SignatureManager::class);
1268
+        $this->registerAlias(ISignatureManager::class, SignatureManager::class);
1269 1269
 
1270
-		$this->registerAlias(ISnowflakeGenerator::class, SnowflakeGenerator::class);
1271
-		$this->registerService(ISequence::class, function (ContainerInterface $c): ISequence {
1272
-			if (PHP_SAPI !== 'cli') {
1273
-				$sequence = $c->get(APCuSequence::class);
1274
-				if ($sequence->isAvailable()) {
1275
-					return $sequence;
1276
-				}
1277
-			}
1278
-
1279
-			return $c->get(FileSequence::class);
1280
-		}, false);
1281
-		$this->registerAlias(ISnowflakeDecoder::class, SnowflakeDecoder::class);
1282
-
1283
-		$this->connectDispatcher();
1284
-	}
1285
-
1286
-	public function boot() {
1287
-		/** @var HookConnector $hookConnector */
1288
-		$hookConnector = $this->get(HookConnector::class);
1289
-		$hookConnector->viewToNode();
1290
-	}
1291
-
1292
-	private function connectDispatcher(): void {
1293
-		/** @var IEventDispatcher $eventDispatcher */
1294
-		$eventDispatcher = $this->get(IEventDispatcher::class);
1295
-		$eventDispatcher->addServiceListener(LoginFailed::class, LoginFailedListener::class);
1296
-		$eventDispatcher->addServiceListener(PostLoginEvent::class, UserLoggedInListener::class);
1297
-		$eventDispatcher->addServiceListener(UserChangedEvent::class, UserChangedListener::class);
1298
-		$eventDispatcher->addServiceListener(BeforeUserDeletedEvent::class, BeforeUserDeletedListener::class);
1299
-
1300
-		FilesMetadataManager::loadListeners($eventDispatcher);
1301
-		GenerateBlurhashMetadata::loadListeners($eventDispatcher);
1302
-	}
1303
-
1304
-	/**
1305
-	 * @return \OCP\Contacts\IManager
1306
-	 * @deprecated 20.0.0
1307
-	 */
1308
-	public function getContactsManager() {
1309
-		return $this->get(\OCP\Contacts\IManager::class);
1310
-	}
1311
-
1312
-	/**
1313
-	 * @return \OC\Encryption\Manager
1314
-	 * @deprecated 20.0.0
1315
-	 */
1316
-	public function getEncryptionManager() {
1317
-		return $this->get(\OCP\Encryption\IManager::class);
1318
-	}
1319
-
1320
-	/**
1321
-	 * @return \OC\Encryption\File
1322
-	 * @deprecated 20.0.0
1323
-	 */
1324
-	public function getEncryptionFilesHelper() {
1325
-		return $this->get(IFile::class);
1326
-	}
1327
-
1328
-	/**
1329
-	 * The current request object holding all information about the request
1330
-	 * currently being processed is returned from this method.
1331
-	 * In case the current execution was not initiated by a web request null is returned
1332
-	 *
1333
-	 * @return \OCP\IRequest
1334
-	 * @deprecated 20.0.0
1335
-	 */
1336
-	public function getRequest() {
1337
-		return $this->get(IRequest::class);
1338
-	}
1339
-
1340
-	/**
1341
-	 * Returns the root folder of ownCloud's data directory
1342
-	 *
1343
-	 * @return IRootFolder
1344
-	 * @deprecated 20.0.0
1345
-	 */
1346
-	public function getRootFolder() {
1347
-		return $this->get(IRootFolder::class);
1348
-	}
1349
-
1350
-	/**
1351
-	 * Returns the root folder of ownCloud's data directory
1352
-	 * This is the lazy variant so this gets only initialized once it
1353
-	 * is actually used.
1354
-	 *
1355
-	 * @return IRootFolder
1356
-	 * @deprecated 20.0.0
1357
-	 */
1358
-	public function getLazyRootFolder() {
1359
-		return $this->get(IRootFolder::class);
1360
-	}
1361
-
1362
-	/**
1363
-	 * Returns a view to ownCloud's files folder
1364
-	 *
1365
-	 * @param string $userId user ID
1366
-	 * @return \OCP\Files\Folder|null
1367
-	 * @deprecated 20.0.0
1368
-	 */
1369
-	public function getUserFolder($userId = null) {
1370
-		if ($userId === null) {
1371
-			$user = $this->get(IUserSession::class)->getUser();
1372
-			if (!$user) {
1373
-				return null;
1374
-			}
1375
-			$userId = $user->getUID();
1376
-		}
1377
-		$root = $this->get(IRootFolder::class);
1378
-		return $root->getUserFolder($userId);
1379
-	}
1380
-
1381
-	/**
1382
-	 * @return \OC\User\Manager
1383
-	 * @deprecated 20.0.0
1384
-	 */
1385
-	public function getUserManager() {
1386
-		return $this->get(IUserManager::class);
1387
-	}
1388
-
1389
-	/**
1390
-	 * @return \OC\Group\Manager
1391
-	 * @deprecated 20.0.0
1392
-	 */
1393
-	public function getGroupManager() {
1394
-		return $this->get(IGroupManager::class);
1395
-	}
1396
-
1397
-	/**
1398
-	 * @return \OC\User\Session
1399
-	 * @deprecated 20.0.0
1400
-	 */
1401
-	public function getUserSession() {
1402
-		return $this->get(IUserSession::class);
1403
-	}
1404
-
1405
-	/**
1406
-	 * @return \OCP\ISession
1407
-	 * @deprecated 20.0.0
1408
-	 */
1409
-	public function getSession() {
1410
-		return $this->get(Session::class)->getSession();
1411
-	}
1412
-
1413
-	/**
1414
-	 * @param \OCP\ISession $session
1415
-	 * @return void
1416
-	 */
1417
-	public function setSession(\OCP\ISession $session) {
1418
-		$this->get(SessionStorage::class)->setSession($session);
1419
-		$this->get(Session::class)->setSession($session);
1420
-		$this->get(Store::class)->setSession($session);
1421
-	}
1422
-
1423
-	/**
1424
-	 * @return \OCP\IConfig
1425
-	 * @deprecated 20.0.0
1426
-	 */
1427
-	public function getConfig() {
1428
-		return $this->get(AllConfig::class);
1429
-	}
1430
-
1431
-	/**
1432
-	 * @return \OC\SystemConfig
1433
-	 * @deprecated 20.0.0
1434
-	 */
1435
-	public function getSystemConfig() {
1436
-		return $this->get(SystemConfig::class);
1437
-	}
1438
-
1439
-	/**
1440
-	 * @return IFactory
1441
-	 * @deprecated 20.0.0
1442
-	 */
1443
-	public function getL10NFactory() {
1444
-		return $this->get(IFactory::class);
1445
-	}
1446
-
1447
-	/**
1448
-	 * get an L10N instance
1449
-	 *
1450
-	 * @param string $app appid
1451
-	 * @param string $lang
1452
-	 * @return IL10N
1453
-	 * @deprecated 20.0.0 use DI of {@see IL10N} or {@see IFactory} instead, or {@see \OCP\Util::getL10N()} as a last resort
1454
-	 */
1455
-	public function getL10N($app, $lang = null) {
1456
-		return $this->get(IFactory::class)->get($app, $lang);
1457
-	}
1458
-
1459
-	/**
1460
-	 * @return IURLGenerator
1461
-	 * @deprecated 20.0.0
1462
-	 */
1463
-	public function getURLGenerator() {
1464
-		return $this->get(IURLGenerator::class);
1465
-	}
1466
-
1467
-	/**
1468
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1469
-	 * getMemCacheFactory() instead.
1470
-	 *
1471
-	 * @return ICache
1472
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1473
-	 */
1474
-	public function getCache() {
1475
-		return $this->get(ICache::class);
1476
-	}
1477
-
1478
-	/**
1479
-	 * Returns an \OCP\CacheFactory instance
1480
-	 *
1481
-	 * @return \OCP\ICacheFactory
1482
-	 * @deprecated 20.0.0
1483
-	 */
1484
-	public function getMemCacheFactory() {
1485
-		return $this->get(ICacheFactory::class);
1486
-	}
1487
-
1488
-	/**
1489
-	 * Returns the current session
1490
-	 *
1491
-	 * @return \OCP\IDBConnection
1492
-	 * @deprecated 20.0.0
1493
-	 */
1494
-	public function getDatabaseConnection() {
1495
-		return $this->get(IDBConnection::class);
1496
-	}
1497
-
1498
-	/**
1499
-	 * Returns the activity manager
1500
-	 *
1501
-	 * @return \OCP\Activity\IManager
1502
-	 * @deprecated 20.0.0
1503
-	 */
1504
-	public function getActivityManager() {
1505
-		return $this->get(\OCP\Activity\IManager::class);
1506
-	}
1507
-
1508
-	/**
1509
-	 * Returns an job list for controlling background jobs
1510
-	 *
1511
-	 * @return IJobList
1512
-	 * @deprecated 20.0.0
1513
-	 */
1514
-	public function getJobList() {
1515
-		return $this->get(IJobList::class);
1516
-	}
1517
-
1518
-	/**
1519
-	 * Returns a SecureRandom instance
1520
-	 *
1521
-	 * @return \OCP\Security\ISecureRandom
1522
-	 * @deprecated 20.0.0
1523
-	 */
1524
-	public function getSecureRandom() {
1525
-		return $this->get(ISecureRandom::class);
1526
-	}
1527
-
1528
-	/**
1529
-	 * Returns a Crypto instance
1530
-	 *
1531
-	 * @return ICrypto
1532
-	 * @deprecated 20.0.0
1533
-	 */
1534
-	public function getCrypto() {
1535
-		return $this->get(ICrypto::class);
1536
-	}
1537
-
1538
-	/**
1539
-	 * Returns a Hasher instance
1540
-	 *
1541
-	 * @return IHasher
1542
-	 * @deprecated 20.0.0
1543
-	 */
1544
-	public function getHasher() {
1545
-		return $this->get(IHasher::class);
1546
-	}
1547
-
1548
-	/**
1549
-	 * Get the certificate manager
1550
-	 *
1551
-	 * @return \OCP\ICertificateManager
1552
-	 */
1553
-	public function getCertificateManager() {
1554
-		return $this->get(ICertificateManager::class);
1555
-	}
1556
-
1557
-	/**
1558
-	 * Get the manager for temporary files and folders
1559
-	 *
1560
-	 * @return \OCP\ITempManager
1561
-	 * @deprecated 20.0.0
1562
-	 */
1563
-	public function getTempManager() {
1564
-		return $this->get(ITempManager::class);
1565
-	}
1566
-
1567
-	/**
1568
-	 * Get the app manager
1569
-	 *
1570
-	 * @return \OCP\App\IAppManager
1571
-	 * @deprecated 20.0.0
1572
-	 */
1573
-	public function getAppManager() {
1574
-		return $this->get(IAppManager::class);
1575
-	}
1576
-
1577
-	/**
1578
-	 * Creates a new mailer
1579
-	 *
1580
-	 * @return IMailer
1581
-	 * @deprecated 20.0.0
1582
-	 */
1583
-	public function getMailer() {
1584
-		return $this->get(IMailer::class);
1585
-	}
1586
-
1587
-	/**
1588
-	 * Get the webroot
1589
-	 *
1590
-	 * @return string
1591
-	 * @deprecated 20.0.0
1592
-	 */
1593
-	public function getWebRoot() {
1594
-		return $this->webRoot;
1595
-	}
1596
-
1597
-	/**
1598
-	 * Get the locking provider
1599
-	 *
1600
-	 * @return ILockingProvider
1601
-	 * @since 8.1.0
1602
-	 * @deprecated 20.0.0
1603
-	 */
1604
-	public function getLockingProvider() {
1605
-		return $this->get(ILockingProvider::class);
1606
-	}
1607
-
1608
-	/**
1609
-	 * Get the MimeTypeDetector
1610
-	 *
1611
-	 * @return IMimeTypeDetector
1612
-	 * @deprecated 20.0.0
1613
-	 */
1614
-	public function getMimeTypeDetector() {
1615
-		return $this->get(IMimeTypeDetector::class);
1616
-	}
1617
-
1618
-	/**
1619
-	 * Get the MimeTypeLoader
1620
-	 *
1621
-	 * @return IMimeTypeLoader
1622
-	 * @deprecated 20.0.0
1623
-	 */
1624
-	public function getMimeTypeLoader() {
1625
-		return $this->get(IMimeTypeLoader::class);
1626
-	}
1627
-
1628
-	/**
1629
-	 * Get the Notification Manager
1630
-	 *
1631
-	 * @return \OCP\Notification\IManager
1632
-	 * @since 8.2.0
1633
-	 * @deprecated 20.0.0
1634
-	 */
1635
-	public function getNotificationManager() {
1636
-		return $this->get(\OCP\Notification\IManager::class);
1637
-	}
1638
-
1639
-	/**
1640
-	 * @return \OCA\Theming\ThemingDefaults
1641
-	 * @deprecated 20.0.0
1642
-	 */
1643
-	public function getThemingDefaults() {
1644
-		return $this->get('ThemingDefaults');
1645
-	}
1646
-
1647
-	/**
1648
-	 * @return \OC\IntegrityCheck\Checker
1649
-	 * @deprecated 20.0.0
1650
-	 */
1651
-	public function getIntegrityCodeChecker() {
1652
-		return $this->get('IntegrityCodeChecker');
1653
-	}
1654
-
1655
-	/**
1656
-	 * @return CsrfTokenManager
1657
-	 * @deprecated 20.0.0
1658
-	 */
1659
-	public function getCsrfTokenManager() {
1660
-		return $this->get(CsrfTokenManager::class);
1661
-	}
1662
-
1663
-	/**
1664
-	 * @return ContentSecurityPolicyNonceManager
1665
-	 * @deprecated 20.0.0
1666
-	 */
1667
-	public function getContentSecurityPolicyNonceManager() {
1668
-		return $this->get(ContentSecurityPolicyNonceManager::class);
1669
-	}
1670
-
1671
-	/**
1672
-	 * @return \OCP\Settings\IManager
1673
-	 * @deprecated 20.0.0
1674
-	 */
1675
-	public function getSettingsManager() {
1676
-		return $this->get(\OC\Settings\Manager::class);
1677
-	}
1678
-
1679
-	/**
1680
-	 * @return \OCP\Files\IAppData
1681
-	 * @deprecated 20.0.0 Use get(\OCP\Files\AppData\IAppDataFactory::class)->get($app) instead
1682
-	 */
1683
-	public function getAppDataDir($app) {
1684
-		$factory = $this->get(\OC\Files\AppData\Factory::class);
1685
-		return $factory->get($app);
1686
-	}
1687
-
1688
-	/**
1689
-	 * @return \OCP\Federation\ICloudIdManager
1690
-	 * @deprecated 20.0.0
1691
-	 */
1692
-	public function getCloudIdManager() {
1693
-		return $this->get(ICloudIdManager::class);
1694
-	}
1270
+        $this->registerAlias(ISnowflakeGenerator::class, SnowflakeGenerator::class);
1271
+        $this->registerService(ISequence::class, function (ContainerInterface $c): ISequence {
1272
+            if (PHP_SAPI !== 'cli') {
1273
+                $sequence = $c->get(APCuSequence::class);
1274
+                if ($sequence->isAvailable()) {
1275
+                    return $sequence;
1276
+                }
1277
+            }
1278
+
1279
+            return $c->get(FileSequence::class);
1280
+        }, false);
1281
+        $this->registerAlias(ISnowflakeDecoder::class, SnowflakeDecoder::class);
1282
+
1283
+        $this->connectDispatcher();
1284
+    }
1285
+
1286
+    public function boot() {
1287
+        /** @var HookConnector $hookConnector */
1288
+        $hookConnector = $this->get(HookConnector::class);
1289
+        $hookConnector->viewToNode();
1290
+    }
1291
+
1292
+    private function connectDispatcher(): void {
1293
+        /** @var IEventDispatcher $eventDispatcher */
1294
+        $eventDispatcher = $this->get(IEventDispatcher::class);
1295
+        $eventDispatcher->addServiceListener(LoginFailed::class, LoginFailedListener::class);
1296
+        $eventDispatcher->addServiceListener(PostLoginEvent::class, UserLoggedInListener::class);
1297
+        $eventDispatcher->addServiceListener(UserChangedEvent::class, UserChangedListener::class);
1298
+        $eventDispatcher->addServiceListener(BeforeUserDeletedEvent::class, BeforeUserDeletedListener::class);
1299
+
1300
+        FilesMetadataManager::loadListeners($eventDispatcher);
1301
+        GenerateBlurhashMetadata::loadListeners($eventDispatcher);
1302
+    }
1303
+
1304
+    /**
1305
+     * @return \OCP\Contacts\IManager
1306
+     * @deprecated 20.0.0
1307
+     */
1308
+    public function getContactsManager() {
1309
+        return $this->get(\OCP\Contacts\IManager::class);
1310
+    }
1311
+
1312
+    /**
1313
+     * @return \OC\Encryption\Manager
1314
+     * @deprecated 20.0.0
1315
+     */
1316
+    public function getEncryptionManager() {
1317
+        return $this->get(\OCP\Encryption\IManager::class);
1318
+    }
1319
+
1320
+    /**
1321
+     * @return \OC\Encryption\File
1322
+     * @deprecated 20.0.0
1323
+     */
1324
+    public function getEncryptionFilesHelper() {
1325
+        return $this->get(IFile::class);
1326
+    }
1327
+
1328
+    /**
1329
+     * The current request object holding all information about the request
1330
+     * currently being processed is returned from this method.
1331
+     * In case the current execution was not initiated by a web request null is returned
1332
+     *
1333
+     * @return \OCP\IRequest
1334
+     * @deprecated 20.0.0
1335
+     */
1336
+    public function getRequest() {
1337
+        return $this->get(IRequest::class);
1338
+    }
1339
+
1340
+    /**
1341
+     * Returns the root folder of ownCloud's data directory
1342
+     *
1343
+     * @return IRootFolder
1344
+     * @deprecated 20.0.0
1345
+     */
1346
+    public function getRootFolder() {
1347
+        return $this->get(IRootFolder::class);
1348
+    }
1349
+
1350
+    /**
1351
+     * Returns the root folder of ownCloud's data directory
1352
+     * This is the lazy variant so this gets only initialized once it
1353
+     * is actually used.
1354
+     *
1355
+     * @return IRootFolder
1356
+     * @deprecated 20.0.0
1357
+     */
1358
+    public function getLazyRootFolder() {
1359
+        return $this->get(IRootFolder::class);
1360
+    }
1361
+
1362
+    /**
1363
+     * Returns a view to ownCloud's files folder
1364
+     *
1365
+     * @param string $userId user ID
1366
+     * @return \OCP\Files\Folder|null
1367
+     * @deprecated 20.0.0
1368
+     */
1369
+    public function getUserFolder($userId = null) {
1370
+        if ($userId === null) {
1371
+            $user = $this->get(IUserSession::class)->getUser();
1372
+            if (!$user) {
1373
+                return null;
1374
+            }
1375
+            $userId = $user->getUID();
1376
+        }
1377
+        $root = $this->get(IRootFolder::class);
1378
+        return $root->getUserFolder($userId);
1379
+    }
1380
+
1381
+    /**
1382
+     * @return \OC\User\Manager
1383
+     * @deprecated 20.0.0
1384
+     */
1385
+    public function getUserManager() {
1386
+        return $this->get(IUserManager::class);
1387
+    }
1388
+
1389
+    /**
1390
+     * @return \OC\Group\Manager
1391
+     * @deprecated 20.0.0
1392
+     */
1393
+    public function getGroupManager() {
1394
+        return $this->get(IGroupManager::class);
1395
+    }
1396
+
1397
+    /**
1398
+     * @return \OC\User\Session
1399
+     * @deprecated 20.0.0
1400
+     */
1401
+    public function getUserSession() {
1402
+        return $this->get(IUserSession::class);
1403
+    }
1404
+
1405
+    /**
1406
+     * @return \OCP\ISession
1407
+     * @deprecated 20.0.0
1408
+     */
1409
+    public function getSession() {
1410
+        return $this->get(Session::class)->getSession();
1411
+    }
1412
+
1413
+    /**
1414
+     * @param \OCP\ISession $session
1415
+     * @return void
1416
+     */
1417
+    public function setSession(\OCP\ISession $session) {
1418
+        $this->get(SessionStorage::class)->setSession($session);
1419
+        $this->get(Session::class)->setSession($session);
1420
+        $this->get(Store::class)->setSession($session);
1421
+    }
1422
+
1423
+    /**
1424
+     * @return \OCP\IConfig
1425
+     * @deprecated 20.0.0
1426
+     */
1427
+    public function getConfig() {
1428
+        return $this->get(AllConfig::class);
1429
+    }
1430
+
1431
+    /**
1432
+     * @return \OC\SystemConfig
1433
+     * @deprecated 20.0.0
1434
+     */
1435
+    public function getSystemConfig() {
1436
+        return $this->get(SystemConfig::class);
1437
+    }
1438
+
1439
+    /**
1440
+     * @return IFactory
1441
+     * @deprecated 20.0.0
1442
+     */
1443
+    public function getL10NFactory() {
1444
+        return $this->get(IFactory::class);
1445
+    }
1446
+
1447
+    /**
1448
+     * get an L10N instance
1449
+     *
1450
+     * @param string $app appid
1451
+     * @param string $lang
1452
+     * @return IL10N
1453
+     * @deprecated 20.0.0 use DI of {@see IL10N} or {@see IFactory} instead, or {@see \OCP\Util::getL10N()} as a last resort
1454
+     */
1455
+    public function getL10N($app, $lang = null) {
1456
+        return $this->get(IFactory::class)->get($app, $lang);
1457
+    }
1458
+
1459
+    /**
1460
+     * @return IURLGenerator
1461
+     * @deprecated 20.0.0
1462
+     */
1463
+    public function getURLGenerator() {
1464
+        return $this->get(IURLGenerator::class);
1465
+    }
1466
+
1467
+    /**
1468
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1469
+     * getMemCacheFactory() instead.
1470
+     *
1471
+     * @return ICache
1472
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1473
+     */
1474
+    public function getCache() {
1475
+        return $this->get(ICache::class);
1476
+    }
1477
+
1478
+    /**
1479
+     * Returns an \OCP\CacheFactory instance
1480
+     *
1481
+     * @return \OCP\ICacheFactory
1482
+     * @deprecated 20.0.0
1483
+     */
1484
+    public function getMemCacheFactory() {
1485
+        return $this->get(ICacheFactory::class);
1486
+    }
1487
+
1488
+    /**
1489
+     * Returns the current session
1490
+     *
1491
+     * @return \OCP\IDBConnection
1492
+     * @deprecated 20.0.0
1493
+     */
1494
+    public function getDatabaseConnection() {
1495
+        return $this->get(IDBConnection::class);
1496
+    }
1497
+
1498
+    /**
1499
+     * Returns the activity manager
1500
+     *
1501
+     * @return \OCP\Activity\IManager
1502
+     * @deprecated 20.0.0
1503
+     */
1504
+    public function getActivityManager() {
1505
+        return $this->get(\OCP\Activity\IManager::class);
1506
+    }
1507
+
1508
+    /**
1509
+     * Returns an job list for controlling background jobs
1510
+     *
1511
+     * @return IJobList
1512
+     * @deprecated 20.0.0
1513
+     */
1514
+    public function getJobList() {
1515
+        return $this->get(IJobList::class);
1516
+    }
1517
+
1518
+    /**
1519
+     * Returns a SecureRandom instance
1520
+     *
1521
+     * @return \OCP\Security\ISecureRandom
1522
+     * @deprecated 20.0.0
1523
+     */
1524
+    public function getSecureRandom() {
1525
+        return $this->get(ISecureRandom::class);
1526
+    }
1527
+
1528
+    /**
1529
+     * Returns a Crypto instance
1530
+     *
1531
+     * @return ICrypto
1532
+     * @deprecated 20.0.0
1533
+     */
1534
+    public function getCrypto() {
1535
+        return $this->get(ICrypto::class);
1536
+    }
1537
+
1538
+    /**
1539
+     * Returns a Hasher instance
1540
+     *
1541
+     * @return IHasher
1542
+     * @deprecated 20.0.0
1543
+     */
1544
+    public function getHasher() {
1545
+        return $this->get(IHasher::class);
1546
+    }
1547
+
1548
+    /**
1549
+     * Get the certificate manager
1550
+     *
1551
+     * @return \OCP\ICertificateManager
1552
+     */
1553
+    public function getCertificateManager() {
1554
+        return $this->get(ICertificateManager::class);
1555
+    }
1556
+
1557
+    /**
1558
+     * Get the manager for temporary files and folders
1559
+     *
1560
+     * @return \OCP\ITempManager
1561
+     * @deprecated 20.0.0
1562
+     */
1563
+    public function getTempManager() {
1564
+        return $this->get(ITempManager::class);
1565
+    }
1566
+
1567
+    /**
1568
+     * Get the app manager
1569
+     *
1570
+     * @return \OCP\App\IAppManager
1571
+     * @deprecated 20.0.0
1572
+     */
1573
+    public function getAppManager() {
1574
+        return $this->get(IAppManager::class);
1575
+    }
1576
+
1577
+    /**
1578
+     * Creates a new mailer
1579
+     *
1580
+     * @return IMailer
1581
+     * @deprecated 20.0.0
1582
+     */
1583
+    public function getMailer() {
1584
+        return $this->get(IMailer::class);
1585
+    }
1586
+
1587
+    /**
1588
+     * Get the webroot
1589
+     *
1590
+     * @return string
1591
+     * @deprecated 20.0.0
1592
+     */
1593
+    public function getWebRoot() {
1594
+        return $this->webRoot;
1595
+    }
1596
+
1597
+    /**
1598
+     * Get the locking provider
1599
+     *
1600
+     * @return ILockingProvider
1601
+     * @since 8.1.0
1602
+     * @deprecated 20.0.0
1603
+     */
1604
+    public function getLockingProvider() {
1605
+        return $this->get(ILockingProvider::class);
1606
+    }
1607
+
1608
+    /**
1609
+     * Get the MimeTypeDetector
1610
+     *
1611
+     * @return IMimeTypeDetector
1612
+     * @deprecated 20.0.0
1613
+     */
1614
+    public function getMimeTypeDetector() {
1615
+        return $this->get(IMimeTypeDetector::class);
1616
+    }
1617
+
1618
+    /**
1619
+     * Get the MimeTypeLoader
1620
+     *
1621
+     * @return IMimeTypeLoader
1622
+     * @deprecated 20.0.0
1623
+     */
1624
+    public function getMimeTypeLoader() {
1625
+        return $this->get(IMimeTypeLoader::class);
1626
+    }
1627
+
1628
+    /**
1629
+     * Get the Notification Manager
1630
+     *
1631
+     * @return \OCP\Notification\IManager
1632
+     * @since 8.2.0
1633
+     * @deprecated 20.0.0
1634
+     */
1635
+    public function getNotificationManager() {
1636
+        return $this->get(\OCP\Notification\IManager::class);
1637
+    }
1638
+
1639
+    /**
1640
+     * @return \OCA\Theming\ThemingDefaults
1641
+     * @deprecated 20.0.0
1642
+     */
1643
+    public function getThemingDefaults() {
1644
+        return $this->get('ThemingDefaults');
1645
+    }
1646
+
1647
+    /**
1648
+     * @return \OC\IntegrityCheck\Checker
1649
+     * @deprecated 20.0.0
1650
+     */
1651
+    public function getIntegrityCodeChecker() {
1652
+        return $this->get('IntegrityCodeChecker');
1653
+    }
1654
+
1655
+    /**
1656
+     * @return CsrfTokenManager
1657
+     * @deprecated 20.0.0
1658
+     */
1659
+    public function getCsrfTokenManager() {
1660
+        return $this->get(CsrfTokenManager::class);
1661
+    }
1662
+
1663
+    /**
1664
+     * @return ContentSecurityPolicyNonceManager
1665
+     * @deprecated 20.0.0
1666
+     */
1667
+    public function getContentSecurityPolicyNonceManager() {
1668
+        return $this->get(ContentSecurityPolicyNonceManager::class);
1669
+    }
1670
+
1671
+    /**
1672
+     * @return \OCP\Settings\IManager
1673
+     * @deprecated 20.0.0
1674
+     */
1675
+    public function getSettingsManager() {
1676
+        return $this->get(\OC\Settings\Manager::class);
1677
+    }
1678
+
1679
+    /**
1680
+     * @return \OCP\Files\IAppData
1681
+     * @deprecated 20.0.0 Use get(\OCP\Files\AppData\IAppDataFactory::class)->get($app) instead
1682
+     */
1683
+    public function getAppDataDir($app) {
1684
+        $factory = $this->get(\OC\Files\AppData\Factory::class);
1685
+        return $factory->get($app);
1686
+    }
1687
+
1688
+    /**
1689
+     * @return \OCP\Federation\ICloudIdManager
1690
+     * @deprecated 20.0.0
1691
+     */
1692
+    public function getCloudIdManager() {
1693
+        return $this->get(ICloudIdManager::class);
1694
+    }
1695 1695
 }
Please login to merge, or discard this patch.
Spacing   +87 added lines, -87 removed lines patch added patch discarded remove patch
@@ -275,7 +275,7 @@  discard block
 block discarded – undo
275 275
 		$this->registerParameter('isCLI', \OC::$CLI);
276 276
 		$this->registerParameter('serverRoot', \OC::$SERVERROOT);
277 277
 
278
-		$this->registerService(ContainerInterface::class, function (ContainerInterface $c) {
278
+		$this->registerService(ContainerInterface::class, function(ContainerInterface $c) {
279 279
 			return $c;
280 280
 		});
281 281
 		$this->registerDeprecatedAlias(\OCP\IServerContainer::class, ContainerInterface::class);
@@ -296,11 +296,11 @@  discard block
 block discarded – undo
296 296
 
297 297
 		$this->registerAlias(IActionFactory::class, ActionFactory::class);
298 298
 
299
-		$this->registerService(View::class, function (Server $c) {
299
+		$this->registerService(View::class, function(Server $c) {
300 300
 			return new View();
301 301
 		}, false);
302 302
 
303
-		$this->registerService(IPreview::class, function (ContainerInterface $c) {
303
+		$this->registerService(IPreview::class, function(ContainerInterface $c) {
304 304
 			return new PreviewManager(
305 305
 				$c->get(\OCP\IConfig::class),
306 306
 				$c->get(IRootFolder::class),
@@ -315,7 +315,7 @@  discard block
 block discarded – undo
315 315
 		});
316 316
 		$this->registerAlias(IMimeIconProvider::class, MimeIconProvider::class);
317 317
 
318
-		$this->registerService(Watcher::class, function (ContainerInterface $c): Watcher {
318
+		$this->registerService(Watcher::class, function(ContainerInterface $c): Watcher {
319 319
 			return new Watcher(
320 320
 				$c->get(\OC\Preview\Storage\StorageFactory::class),
321 321
 				$c->get(PreviewMapper::class),
@@ -323,11 +323,11 @@  discard block
 block discarded – undo
323 323
 			);
324 324
 		});
325 325
 
326
-		$this->registerService(IProfiler::class, function (Server $c) {
326
+		$this->registerService(IProfiler::class, function(Server $c) {
327 327
 			return new Profiler($c->get(SystemConfig::class));
328 328
 		});
329 329
 
330
-		$this->registerService(Encryption\Manager::class, function (Server $c): Encryption\Manager {
330
+		$this->registerService(Encryption\Manager::class, function(Server $c): Encryption\Manager {
331 331
 			$view = new View();
332 332
 			$util = new Encryption\Util(
333 333
 				$view,
@@ -346,7 +346,7 @@  discard block
 block discarded – undo
346 346
 		});
347 347
 		$this->registerAlias(\OCP\Encryption\IManager::class, Encryption\Manager::class);
348 348
 
349
-		$this->registerService(IFile::class, function (ContainerInterface $c) {
349
+		$this->registerService(IFile::class, function(ContainerInterface $c) {
350 350
 			$util = new Encryption\Util(
351 351
 				new View(),
352 352
 				$c->get(IUserManager::class),
@@ -360,7 +360,7 @@  discard block
 block discarded – undo
360 360
 			);
361 361
 		});
362 362
 
363
-		$this->registerService(IStorage::class, function (ContainerInterface $c) {
363
+		$this->registerService(IStorage::class, function(ContainerInterface $c) {
364 364
 			$view = new View();
365 365
 			$util = new Encryption\Util(
366 366
 				$view,
@@ -379,23 +379,23 @@  discard block
 block discarded – undo
379 379
 
380 380
 		$this->registerAlias(\OCP\ITagManager::class, TagManager::class);
381 381
 
382
-		$this->registerService('SystemTagManagerFactory', function (ContainerInterface $c) {
382
+		$this->registerService('SystemTagManagerFactory', function(ContainerInterface $c) {
383 383
 			/** @var \OCP\IConfig $config */
384 384
 			$config = $c->get(\OCP\IConfig::class);
385 385
 			$factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
386 386
 			return new $factoryClass($this);
387 387
 		});
388
-		$this->registerService(ISystemTagManager::class, function (ContainerInterface $c) {
388
+		$this->registerService(ISystemTagManager::class, function(ContainerInterface $c) {
389 389
 			return $c->get('SystemTagManagerFactory')->getManager();
390 390
 		});
391 391
 		/** @deprecated 19.0.0 */
392 392
 		$this->registerDeprecatedAlias('SystemTagManager', ISystemTagManager::class);
393 393
 
394
-		$this->registerService(ISystemTagObjectMapper::class, function (ContainerInterface $c) {
394
+		$this->registerService(ISystemTagObjectMapper::class, function(ContainerInterface $c) {
395 395
 			return $c->get('SystemTagManagerFactory')->getObjectMapper();
396 396
 		});
397 397
 		$this->registerAlias(IFileAccess::class, FileAccess::class);
398
-		$this->registerService('RootFolder', function (ContainerInterface $c) {
398
+		$this->registerService('RootFolder', function(ContainerInterface $c) {
399 399
 			$manager = \OC\Files\Filesystem::getMountManager();
400 400
 			$view = new View();
401 401
 			/** @var IUserSession $userSession */
@@ -421,7 +421,7 @@  discard block
 block discarded – undo
421 421
 
422 422
 			return $root;
423 423
 		});
424
-		$this->registerService(HookConnector::class, function (ContainerInterface $c) {
424
+		$this->registerService(HookConnector::class, function(ContainerInterface $c) {
425 425
 			return new HookConnector(
426 426
 				$c->get(IRootFolder::class),
427 427
 				new View(),
@@ -430,19 +430,19 @@  discard block
 block discarded – undo
430 430
 			);
431 431
 		});
432 432
 
433
-		$this->registerService(IRootFolder::class, function (ContainerInterface $c) {
434
-			return new LazyRoot(function () use ($c) {
433
+		$this->registerService(IRootFolder::class, function(ContainerInterface $c) {
434
+			return new LazyRoot(function() use ($c) {
435 435
 				return $c->get('RootFolder');
436 436
 			});
437 437
 		});
438 438
 
439 439
 		$this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
440 440
 
441
-		$this->registerService(DisplayNameCache::class, function (ContainerInterface $c) {
441
+		$this->registerService(DisplayNameCache::class, function(ContainerInterface $c) {
442 442
 			return $c->get(\OC\User\Manager::class)->getDisplayNameCache();
443 443
 		});
444 444
 
445
-		$this->registerService(\OCP\IGroupManager::class, function (ContainerInterface $c) {
445
+		$this->registerService(\OCP\IGroupManager::class, function(ContainerInterface $c) {
446 446
 			$groupManager = new \OC\Group\Manager(
447 447
 				$this->get(IUserManager::class),
448 448
 				$this->get(IEventDispatcher::class),
@@ -453,7 +453,7 @@  discard block
 block discarded – undo
453 453
 			return $groupManager;
454 454
 		});
455 455
 
456
-		$this->registerService(Store::class, function (ContainerInterface $c) {
456
+		$this->registerService(Store::class, function(ContainerInterface $c) {
457 457
 			$session = $c->get(ISession::class);
458 458
 			if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
459 459
 				$tokenProvider = $c->get(IProvider::class);
@@ -468,7 +468,7 @@  discard block
 block discarded – undo
468 468
 		$this->registerAlias(IProvider::class, Authentication\Token\Manager::class);
469 469
 		$this->registerAlias(OCPIProvider::class, Authentication\Token\Manager::class);
470 470
 
471
-		$this->registerService(\OC\User\Session::class, function (Server $c) {
471
+		$this->registerService(\OC\User\Session::class, function(Server $c) {
472 472
 			$manager = $c->get(IUserManager::class);
473 473
 			$session = new \OC\Session\Memory();
474 474
 			$timeFactory = new TimeFactory();
@@ -492,40 +492,40 @@  discard block
 block discarded – undo
492 492
 				$c->get(IEventDispatcher::class),
493 493
 			);
494 494
 			/** @deprecated 21.0.0 use BeforeUserCreatedEvent event with the IEventDispatcher instead */
495
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
495
+			$userSession->listen('\OC\User', 'preCreateUser', function($uid, $password) {
496 496
 				\OC_Hook::emit('OC_User', 'pre_createUser', ['run' => true, 'uid' => $uid, 'password' => $password]);
497 497
 			});
498 498
 			/** @deprecated 21.0.0 use UserCreatedEvent event with the IEventDispatcher instead */
499
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
499
+			$userSession->listen('\OC\User', 'postCreateUser', function($user, $password) {
500 500
 				/** @var \OC\User\User $user */
501 501
 				\OC_Hook::emit('OC_User', 'post_createUser', ['uid' => $user->getUID(), 'password' => $password]);
502 502
 			});
503 503
 			/** @deprecated 21.0.0 use BeforeUserDeletedEvent event with the IEventDispatcher instead */
504
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
504
+			$userSession->listen('\OC\User', 'preDelete', function($user) {
505 505
 				/** @var \OC\User\User $user */
506 506
 				\OC_Hook::emit('OC_User', 'pre_deleteUser', ['run' => true, 'uid' => $user->getUID()]);
507 507
 			});
508 508
 			/** @deprecated 21.0.0 use UserDeletedEvent event with the IEventDispatcher instead */
509
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
509
+			$userSession->listen('\OC\User', 'postDelete', function($user) {
510 510
 				/** @var \OC\User\User $user */
511 511
 				\OC_Hook::emit('OC_User', 'post_deleteUser', ['uid' => $user->getUID()]);
512 512
 			});
513
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
513
+			$userSession->listen('\OC\User', 'preSetPassword', function($user, $password, $recoveryPassword) {
514 514
 				/** @var \OC\User\User $user */
515 515
 				\OC_Hook::emit('OC_User', 'pre_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
516 516
 			});
517
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
517
+			$userSession->listen('\OC\User', 'postSetPassword', function($user, $password, $recoveryPassword) {
518 518
 				/** @var \OC\User\User $user */
519 519
 				\OC_Hook::emit('OC_User', 'post_setPassword', ['run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword]);
520 520
 			});
521
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
521
+			$userSession->listen('\OC\User', 'preLogin', function($uid, $password) {
522 522
 				\OC_Hook::emit('OC_User', 'pre_login', ['run' => true, 'uid' => $uid, 'password' => $password]);
523 523
 
524 524
 				/** @var IEventDispatcher $dispatcher */
525 525
 				$dispatcher = $this->get(IEventDispatcher::class);
526 526
 				$dispatcher->dispatchTyped(new BeforeUserLoggedInEvent($uid, $password));
527 527
 			});
528
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $loginName, $password, $isTokenLogin) {
528
+			$userSession->listen('\OC\User', 'postLogin', function($user, $loginName, $password, $isTokenLogin) {
529 529
 				/** @var \OC\User\User $user */
530 530
 				\OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'loginName' => $loginName, 'password' => $password, 'isTokenLogin' => $isTokenLogin]);
531 531
 
@@ -533,12 +533,12 @@  discard block
 block discarded – undo
533 533
 				$dispatcher = $this->get(IEventDispatcher::class);
534 534
 				$dispatcher->dispatchTyped(new UserLoggedInEvent($user, $loginName, $password, $isTokenLogin));
535 535
 			});
536
-			$userSession->listen('\OC\User', 'preRememberedLogin', function ($uid) {
536
+			$userSession->listen('\OC\User', 'preRememberedLogin', function($uid) {
537 537
 				/** @var IEventDispatcher $dispatcher */
538 538
 				$dispatcher = $this->get(IEventDispatcher::class);
539 539
 				$dispatcher->dispatchTyped(new BeforeUserLoggedInWithCookieEvent($uid));
540 540
 			});
541
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
541
+			$userSession->listen('\OC\User', 'postRememberedLogin', function($user, $password) {
542 542
 				/** @var \OC\User\User $user */
543 543
 				\OC_Hook::emit('OC_User', 'post_login', ['run' => true, 'uid' => $user->getUID(), 'password' => $password]);
544 544
 
@@ -546,19 +546,19 @@  discard block
 block discarded – undo
546 546
 				$dispatcher = $this->get(IEventDispatcher::class);
547 547
 				$dispatcher->dispatchTyped(new UserLoggedInWithCookieEvent($user, $password));
548 548
 			});
549
-			$userSession->listen('\OC\User', 'logout', function ($user) {
549
+			$userSession->listen('\OC\User', 'logout', function($user) {
550 550
 				\OC_Hook::emit('OC_User', 'logout', []);
551 551
 
552 552
 				/** @var IEventDispatcher $dispatcher */
553 553
 				$dispatcher = $this->get(IEventDispatcher::class);
554 554
 				$dispatcher->dispatchTyped(new BeforeUserLoggedOutEvent($user));
555 555
 			});
556
-			$userSession->listen('\OC\User', 'postLogout', function ($user) {
556
+			$userSession->listen('\OC\User', 'postLogout', function($user) {
557 557
 				/** @var IEventDispatcher $dispatcher */
558 558
 				$dispatcher = $this->get(IEventDispatcher::class);
559 559
 				$dispatcher->dispatchTyped(new UserLoggedOutEvent($user));
560 560
 			});
561
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) {
561
+			$userSession->listen('\OC\User', 'changeUser', function($user, $feature, $value, $oldValue) {
562 562
 				/** @var \OC\User\User $user */
563 563
 				\OC_Hook::emit('OC_User', 'changeUser', ['run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue]);
564 564
 			});
@@ -572,7 +572,7 @@  discard block
 block discarded – undo
572 572
 
573 573
 		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
574 574
 
575
-		$this->registerService(\OC\SystemConfig::class, function ($c) use ($config) {
575
+		$this->registerService(\OC\SystemConfig::class, function($c) use ($config) {
576 576
 			return new \OC\SystemConfig($config);
577 577
 		});
578 578
 
@@ -580,7 +580,7 @@  discard block
 block discarded – undo
580 580
 		$this->registerAlias(IUserConfig::class, \OC\Config\UserConfig::class);
581 581
 		$this->registerAlias(IAppManager::class, AppManager::class);
582 582
 
583
-		$this->registerService(IFactory::class, function (Server $c) {
583
+		$this->registerService(IFactory::class, function(Server $c) {
584 584
 			return new \OC\L10N\Factory(
585 585
 				$c->get(\OCP\IConfig::class),
586 586
 				$c->getRequest(),
@@ -594,7 +594,7 @@  discard block
 block discarded – undo
594 594
 		$this->registerAlias(IURLGenerator::class, URLGenerator::class);
595 595
 
596 596
 		$this->registerAlias(ICache::class, Cache\File::class);
597
-		$this->registerService(Factory::class, function (Server $c) {
597
+		$this->registerService(Factory::class, function(Server $c) {
598 598
 			$profiler = $c->get(IProfiler::class);
599 599
 			$logger = $c->get(LoggerInterface::class);
600 600
 			$serverVersion = $c->get(ServerVersion::class);
@@ -627,12 +627,12 @@  discard block
 block discarded – undo
627 627
 		});
628 628
 		$this->registerAlias(ICacheFactory::class, Factory::class);
629 629
 
630
-		$this->registerService('RedisFactory', function (Server $c) {
630
+		$this->registerService('RedisFactory', function(Server $c) {
631 631
 			$systemConfig = $c->get(SystemConfig::class);
632 632
 			return new RedisFactory($systemConfig, $c->get(IEventLogger::class));
633 633
 		});
634 634
 
635
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
635
+		$this->registerService(\OCP\Activity\IManager::class, function(Server $c) {
636 636
 			$l10n = $this->get(IFactory::class)->get('lib');
637 637
 			return new \OC\Activity\Manager(
638 638
 				$c->getRequest(),
@@ -645,14 +645,14 @@  discard block
 block discarded – undo
645 645
 			);
646 646
 		});
647 647
 
648
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
648
+		$this->registerService(\OCP\Activity\IEventMerger::class, function(Server $c) {
649 649
 			return new \OC\Activity\EventMerger(
650 650
 				$c->getL10N('lib')
651 651
 			);
652 652
 		});
653 653
 		$this->registerAlias(IValidator::class, Validator::class);
654 654
 
655
-		$this->registerService(AvatarManager::class, function (Server $c) {
655
+		$this->registerService(AvatarManager::class, function(Server $c) {
656 656
 			return new AvatarManager(
657 657
 				$c->get(IUserSession::class),
658 658
 				$c->get(\OC\User\Manager::class),
@@ -672,7 +672,7 @@  discard block
 block discarded – undo
672 672
 		$this->registerAlias(\OCP\Support\Subscription\IAssertion::class, \OC\Support\Subscription\Assertion::class);
673 673
 
674 674
 		/** Only used by the PsrLoggerAdapter should not be used by apps */
675
-		$this->registerService(\OC\Log::class, function (Server $c) {
675
+		$this->registerService(\OC\Log::class, function(Server $c) {
676 676
 			$logType = $c->get(AllConfig::class)->getSystemValue('log_type', 'file');
677 677
 			$factory = new LogFactory($c, $this->get(SystemConfig::class));
678 678
 			$logger = $factory->get($logType);
@@ -683,13 +683,13 @@  discard block
 block discarded – undo
683 683
 		// PSR-3 logger
684 684
 		$this->registerAlias(LoggerInterface::class, PsrLoggerAdapter::class);
685 685
 
686
-		$this->registerService(ILogFactory::class, function (Server $c) {
686
+		$this->registerService(ILogFactory::class, function(Server $c) {
687 687
 			return new LogFactory($c, $this->get(SystemConfig::class));
688 688
 		});
689 689
 
690 690
 		$this->registerAlias(IJobList::class, \OC\BackgroundJob\JobList::class);
691 691
 
692
-		$this->registerService(Router::class, function (Server $c) {
692
+		$this->registerService(Router::class, function(Server $c) {
693 693
 			$cacheFactory = $c->get(ICacheFactory::class);
694 694
 			if ($cacheFactory->isLocalCacheAvailable()) {
695 695
 				$router = $c->resolve(CachingRouter::class);
@@ -700,7 +700,7 @@  discard block
 block discarded – undo
700 700
 		});
701 701
 		$this->registerAlias(IRouter::class, Router::class);
702 702
 
703
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
703
+		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function($c) {
704 704
 			$config = $c->get(\OCP\IConfig::class);
705 705
 			if (ltrim($config->getSystemValueString('memcache.distributed', ''), '\\') === \OC\Memcache\Redis::class) {
706 706
 				$backend = new \OC\Security\RateLimiting\Backend\MemoryCacheBackend(
@@ -730,7 +730,7 @@  discard block
 block discarded – undo
730 730
 		$this->registerAlias(ICredentialsManager::class, CredentialsManager::class);
731 731
 
732 732
 		$this->registerAlias(IDBConnection::class, ConnectionAdapter::class);
733
-		$this->registerService(Connection::class, function (Server $c) {
733
+		$this->registerService(Connection::class, function(Server $c) {
734 734
 			$systemConfig = $c->get(SystemConfig::class);
735 735
 			$factory = new \OC\DB\ConnectionFactory($systemConfig, $c->get(ICacheFactory::class));
736 736
 			$type = $systemConfig->getValue('dbtype', 'sqlite');
@@ -743,17 +743,17 @@  discard block
 block discarded – undo
743 743
 
744 744
 		$this->registerAlias(ICertificateManager::class, CertificateManager::class);
745 745
 		$this->registerAlias(IClientService::class, ClientService::class);
746
-		$this->registerService(NegativeDnsCache::class, function (ContainerInterface $c) {
746
+		$this->registerService(NegativeDnsCache::class, function(ContainerInterface $c) {
747 747
 			return new NegativeDnsCache(
748 748
 				$c->get(ICacheFactory::class),
749 749
 			);
750 750
 		});
751 751
 		$this->registerDeprecatedAlias('HttpClientService', IClientService::class);
752
-		$this->registerService(IEventLogger::class, function (ContainerInterface $c) {
752
+		$this->registerService(IEventLogger::class, function(ContainerInterface $c) {
753 753
 			return new EventLogger($c->get(SystemConfig::class), $c->get(LoggerInterface::class), $c->get(Log::class));
754 754
 		});
755 755
 
756
-		$this->registerService(IQueryLogger::class, function (ContainerInterface $c) {
756
+		$this->registerService(IQueryLogger::class, function(ContainerInterface $c) {
757 757
 			$queryLogger = new QueryLogger();
758 758
 			if ($c->get(SystemConfig::class)->getValue('debug', false)) {
759 759
 				// In debug mode, module is being activated by default
@@ -765,7 +765,7 @@  discard block
 block discarded – undo
765 765
 		$this->registerAlias(ITempManager::class, TempManager::class);
766 766
 		$this->registerAlias(IDateTimeZone::class, DateTimeZone::class);
767 767
 
768
-		$this->registerService(IDateTimeFormatter::class, function (Server $c) {
768
+		$this->registerService(IDateTimeFormatter::class, function(Server $c) {
769 769
 			$language = $c->get(\OCP\IConfig::class)->getUserValue($c->get(ISession::class)->get('user_id'), 'core', 'lang', null);
770 770
 
771 771
 			return new DateTimeFormatter(
@@ -774,14 +774,14 @@  discard block
 block discarded – undo
774 774
 			);
775 775
 		});
776 776
 
777
-		$this->registerService(IUserMountCache::class, function (ContainerInterface $c) {
777
+		$this->registerService(IUserMountCache::class, function(ContainerInterface $c) {
778 778
 			$mountCache = $c->get(UserMountCache::class);
779 779
 			$listener = new UserMountCacheListener($mountCache);
780 780
 			$listener->listen($c->get(IUserManager::class));
781 781
 			return $mountCache;
782 782
 		});
783 783
 
784
-		$this->registerService(IMountProviderCollection::class, function (ContainerInterface $c) {
784
+		$this->registerService(IMountProviderCollection::class, function(ContainerInterface $c) {
785 785
 			$loader = $c->get(IStorageFactory::class);
786 786
 			$mountCache = $c->get(IUserMountCache::class);
787 787
 			$eventLogger = $c->get(IEventLogger::class);
@@ -800,7 +800,7 @@  discard block
 block discarded – undo
800 800
 			return $manager;
801 801
 		});
802 802
 
803
-		$this->registerService(IBus::class, function (ContainerInterface $c) {
803
+		$this->registerService(IBus::class, function(ContainerInterface $c) {
804 804
 			$busClass = $c->get(\OCP\IConfig::class)->getSystemValueString('commandbus');
805 805
 			if ($busClass) {
806 806
 				[$app, $class] = explode('::', $busClass, 2);
@@ -819,7 +819,7 @@  discard block
 block discarded – undo
819 819
 		$this->registerAlias(ITrustedDomainHelper::class, TrustedDomainHelper::class);
820 820
 		$this->registerAlias(IThrottler::class, Throttler::class);
821 821
 
822
-		$this->registerService(\OC\Security\Bruteforce\Backend\IBackend::class, function ($c) {
822
+		$this->registerService(\OC\Security\Bruteforce\Backend\IBackend::class, function($c) {
823 823
 			$config = $c->get(\OCP\IConfig::class);
824 824
 			if (!$config->getSystemValueBool('auth.bruteforce.protection.force.database', false)
825 825
 				&& ltrim($config->getSystemValueString('memcache.distributed', ''), '\\') === \OC\Memcache\Redis::class) {
@@ -832,7 +832,7 @@  discard block
 block discarded – undo
832 832
 		});
833 833
 
834 834
 		$this->registerDeprecatedAlias('IntegrityCodeChecker', Checker::class);
835
-		$this->registerService(Checker::class, function (ContainerInterface $c) {
835
+		$this->registerService(Checker::class, function(ContainerInterface $c) {
836 836
 			// IConfig requires a working database. This code
837 837
 			// might however be called when Nextcloud is not yet setup.
838 838
 			if (\OC::$server->get(SystemConfig::class)->getValue('installed', false)) {
@@ -854,7 +854,7 @@  discard block
 block discarded – undo
854 854
 				$c->get(IMimeTypeDetector::class)
855 855
 			);
856 856
 		});
857
-		$this->registerService(Request::class, function (ContainerInterface $c) {
857
+		$this->registerService(Request::class, function(ContainerInterface $c) {
858 858
 			if (isset($this['urlParams'])) {
859 859
 				$urlParams = $this['urlParams'];
860 860
 			} else {
@@ -890,7 +890,7 @@  discard block
 block discarded – undo
890 890
 		});
891 891
 		$this->registerAlias(\OCP\IRequest::class, Request::class);
892 892
 
893
-		$this->registerService(IRequestId::class, function (ContainerInterface $c): IRequestId {
893
+		$this->registerService(IRequestId::class, function(ContainerInterface $c): IRequestId {
894 894
 			return new RequestId(
895 895
 				$_SERVER['UNIQUE_ID'] ?? '',
896 896
 				$this->get(ISecureRandom::class)
@@ -900,7 +900,7 @@  discard block
 block discarded – undo
900 900
 		/** @since 32.0.0 */
901 901
 		$this->registerAlias(IEmailValidator::class, EmailValidator::class);
902 902
 
903
-		$this->registerService(IMailer::class, function (Server $c) {
903
+		$this->registerService(IMailer::class, function(Server $c) {
904 904
 			return new Mailer(
905 905
 				$c->get(\OCP\IConfig::class),
906 906
 				$c->get(LoggerInterface::class),
@@ -916,7 +916,7 @@  discard block
 block discarded – undo
916 916
 		/** @since 30.0.0 */
917 917
 		$this->registerAlias(\OCP\Mail\Provider\IManager::class, \OC\Mail\Provider\Manager::class);
918 918
 
919
-		$this->registerService(ILDAPProviderFactory::class, function (ContainerInterface $c) {
919
+		$this->registerService(ILDAPProviderFactory::class, function(ContainerInterface $c) {
920 920
 			$config = $c->get(\OCP\IConfig::class);
921 921
 			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
922 922
 			if (is_null($factoryClass) || !class_exists($factoryClass)) {
@@ -925,11 +925,11 @@  discard block
 block discarded – undo
925 925
 			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
926 926
 			return new $factoryClass($this);
927 927
 		});
928
-		$this->registerService(ILDAPProvider::class, function (ContainerInterface $c) {
928
+		$this->registerService(ILDAPProvider::class, function(ContainerInterface $c) {
929 929
 			$factory = $c->get(ILDAPProviderFactory::class);
930 930
 			return $factory->getLDAPProvider();
931 931
 		});
932
-		$this->registerService(ILockingProvider::class, function (ContainerInterface $c) {
932
+		$this->registerService(ILockingProvider::class, function(ContainerInterface $c) {
933 933
 			$ini = $c->get(IniGetWrapper::class);
934 934
 			$config = $c->get(\OCP\IConfig::class);
935 935
 			$ttl = $config->getSystemValueInt('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
@@ -951,51 +951,51 @@  discard block
 block discarded – undo
951 951
 			return new NoopLockingProvider();
952 952
 		});
953 953
 
954
-		$this->registerService(ILockManager::class, function (Server $c): LockManager {
954
+		$this->registerService(ILockManager::class, function(Server $c): LockManager {
955 955
 			return new LockManager();
956 956
 		});
957 957
 
958 958
 		$this->registerAlias(ILockdownManager::class, 'LockdownManager');
959
-		$this->registerService(SetupManager::class, function ($c) {
959
+		$this->registerService(SetupManager::class, function($c) {
960 960
 			// create the setupmanager through the mount manager to resolve the cyclic dependency
961 961
 			return $c->get(\OC\Files\Mount\Manager::class)->getSetupManager();
962 962
 		});
963 963
 		$this->registerAlias(IMountManager::class, \OC\Files\Mount\Manager::class);
964 964
 
965
-		$this->registerService(IMimeTypeDetector::class, function (ContainerInterface $c) {
965
+		$this->registerService(IMimeTypeDetector::class, function(ContainerInterface $c) {
966 966
 			return new \OC\Files\Type\Detection(
967 967
 				$c->get(IURLGenerator::class),
968 968
 				$c->get(LoggerInterface::class),
969 969
 				\OC::$configDir,
970
-				\OC::$SERVERROOT . '/resources/config/'
970
+				\OC::$SERVERROOT.'/resources/config/'
971 971
 			);
972 972
 		});
973 973
 
974 974
 		$this->registerAlias(IMimeTypeLoader::class, Loader::class);
975
-		$this->registerService(BundleFetcher::class, function () {
975
+		$this->registerService(BundleFetcher::class, function() {
976 976
 			return new BundleFetcher($this->getL10N('lib'));
977 977
 		});
978 978
 		$this->registerAlias(\OCP\Notification\IManager::class, Manager::class);
979 979
 
980
-		$this->registerService(CapabilitiesManager::class, function (ContainerInterface $c) {
980
+		$this->registerService(CapabilitiesManager::class, function(ContainerInterface $c) {
981 981
 			$manager = new CapabilitiesManager($c->get(LoggerInterface::class));
982
-			$manager->registerCapability(function () use ($c) {
982
+			$manager->registerCapability(function() use ($c) {
983 983
 				return new \OC\OCS\CoreCapabilities($c->get(\OCP\IConfig::class));
984 984
 			});
985
-			$manager->registerCapability(function () use ($c) {
985
+			$manager->registerCapability(function() use ($c) {
986 986
 				return $c->get(\OC\Security\Bruteforce\Capabilities::class);
987 987
 			});
988 988
 			return $manager;
989 989
 		});
990 990
 
991
-		$this->registerService(ICommentsManager::class, function (Server $c) {
991
+		$this->registerService(ICommentsManager::class, function(Server $c) {
992 992
 			$config = $c->get(\OCP\IConfig::class);
993 993
 			$factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
994 994
 			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
995 995
 			$factory = new $factoryClass($this);
996 996
 			$manager = $factory->getManager();
997 997
 
998
-			$manager->registerDisplayNameResolver('user', function ($id) use ($c) {
998
+			$manager->registerDisplayNameResolver('user', function($id) use ($c) {
999 999
 				$manager = $c->get(IUserManager::class);
1000 1000
 				$userDisplayName = $manager->getDisplayName($id);
1001 1001
 				if ($userDisplayName === null) {
@@ -1009,7 +1009,7 @@  discard block
 block discarded – undo
1009 1009
 		});
1010 1010
 
1011 1011
 		$this->registerAlias(\OC_Defaults::class, 'ThemingDefaults');
1012
-		$this->registerService('ThemingDefaults', function (Server $c) {
1012
+		$this->registerService('ThemingDefaults', function(Server $c) {
1013 1013
 			try {
1014 1014
 				$classExists = class_exists('OCA\Theming\ThemingDefaults');
1015 1015
 			} catch (\OCP\AutoloadNotAllowedException $e) {
@@ -1060,7 +1060,7 @@  discard block
 block discarded – undo
1060 1060
 			}
1061 1061
 			return new \OC_Defaults();
1062 1062
 		});
1063
-		$this->registerService(JSCombiner::class, function (Server $c) {
1063
+		$this->registerService(JSCombiner::class, function(Server $c) {
1064 1064
 			return new JSCombiner(
1065 1065
 				$c->getAppDataDir('js'),
1066 1066
 				$c->get(IURLGenerator::class),
@@ -1071,7 +1071,7 @@  discard block
 block discarded – undo
1071 1071
 		});
1072 1072
 		$this->registerAlias(\OCP\EventDispatcher\IEventDispatcher::class, \OC\EventDispatcher\EventDispatcher::class);
1073 1073
 
1074
-		$this->registerService('CryptoWrapper', function (ContainerInterface $c) {
1074
+		$this->registerService('CryptoWrapper', function(ContainerInterface $c) {
1075 1075
 			// FIXME: Instantiated here due to cyclic dependency
1076 1076
 			$request = new Request(
1077 1077
 				[
@@ -1095,12 +1095,12 @@  discard block
 block discarded – undo
1095 1095
 				$request
1096 1096
 			);
1097 1097
 		});
1098
-		$this->registerService(SessionStorage::class, function (ContainerInterface $c) {
1098
+		$this->registerService(SessionStorage::class, function(ContainerInterface $c) {
1099 1099
 			return new SessionStorage($c->get(ISession::class));
1100 1100
 		});
1101 1101
 		$this->registerAlias(\OCP\Security\IContentSecurityPolicyManager::class, ContentSecurityPolicyManager::class);
1102 1102
 
1103
-		$this->registerService(IProviderFactory::class, function (ContainerInterface $c) {
1103
+		$this->registerService(IProviderFactory::class, function(ContainerInterface $c) {
1104 1104
 			$config = $c->get(\OCP\IConfig::class);
1105 1105
 			$factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1106 1106
 			/** @var \OCP\Share\IProviderFactory $factory */
@@ -1109,7 +1109,7 @@  discard block
 block discarded – undo
1109 1109
 
1110 1110
 		$this->registerAlias(\OCP\Share\IManager::class, \OC\Share20\Manager::class);
1111 1111
 
1112
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function (Server $c) {
1112
+		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1113 1113
 			$instance = new Collaboration\Collaborators\Search($c);
1114 1114
 
1115 1115
 			// register default plugins
@@ -1134,20 +1134,20 @@  discard block
 block discarded – undo
1134 1134
 
1135 1135
 		$this->registerDeprecatedAlias('SettingsManager', \OC\Settings\Manager::class);
1136 1136
 		$this->registerAlias(\OCP\Settings\IManager::class, \OC\Settings\Manager::class);
1137
-		$this->registerService(\OC\Files\AppData\Factory::class, function (ContainerInterface $c) {
1137
+		$this->registerService(\OC\Files\AppData\Factory::class, function(ContainerInterface $c) {
1138 1138
 			return new \OC\Files\AppData\Factory(
1139 1139
 				$c->get(IRootFolder::class),
1140 1140
 				$c->get(SystemConfig::class)
1141 1141
 			);
1142 1142
 		});
1143 1143
 
1144
-		$this->registerService('LockdownManager', function (ContainerInterface $c) {
1145
-			return new LockdownManager(function () use ($c) {
1144
+		$this->registerService('LockdownManager', function(ContainerInterface $c) {
1145
+			return new LockdownManager(function() use ($c) {
1146 1146
 				return $c->get(ISession::class);
1147 1147
 			});
1148 1148
 		});
1149 1149
 
1150
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (ContainerInterface $c) {
1150
+		$this->registerService(\OCP\OCS\IDiscoveryService::class, function(ContainerInterface $c) {
1151 1151
 			return new DiscoveryService(
1152 1152
 				$c->get(ICacheFactory::class),
1153 1153
 				$c->get(IClientService::class)
@@ -1155,7 +1155,7 @@  discard block
 block discarded – undo
1155 1155
 		});
1156 1156
 		$this->registerAlias(IOCMDiscoveryService::class, OCMDiscoveryService::class);
1157 1157
 
1158
-		$this->registerService(ICloudIdManager::class, function (ContainerInterface $c) {
1158
+		$this->registerService(ICloudIdManager::class, function(ContainerInterface $c) {
1159 1159
 			return new CloudIdManager(
1160 1160
 				$c->get(ICacheFactory::class),
1161 1161
 				$c->get(IEventDispatcher::class),
@@ -1167,7 +1167,7 @@  discard block
 block discarded – undo
1167 1167
 
1168 1168
 		$this->registerAlias(\OCP\GlobalScale\IConfig::class, \OC\GlobalScale\Config::class);
1169 1169
 		$this->registerAlias(ICloudFederationProviderManager::class, CloudFederationProviderManager::class);
1170
-		$this->registerService(ICloudFederationFactory::class, function (Server $c) {
1170
+		$this->registerService(ICloudFederationFactory::class, function(Server $c) {
1171 1171
 			return new CloudFederationFactory();
1172 1172
 		});
1173 1173
 
@@ -1176,27 +1176,27 @@  discard block
 block discarded – undo
1176 1176
 		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1177 1177
 		$this->registerAlias(\Psr\Clock\ClockInterface::class, \OCP\AppFramework\Utility\ITimeFactory::class);
1178 1178
 
1179
-		$this->registerService(Defaults::class, function (Server $c) {
1179
+		$this->registerService(Defaults::class, function(Server $c) {
1180 1180
 			return new Defaults(
1181 1181
 				$c->get('ThemingDefaults')
1182 1182
 			);
1183 1183
 		});
1184 1184
 
1185
-		$this->registerService(\OCP\ISession::class, function (ContainerInterface $c) {
1185
+		$this->registerService(\OCP\ISession::class, function(ContainerInterface $c) {
1186 1186
 			return $c->get(\OCP\IUserSession::class)->getSession();
1187 1187
 		}, false);
1188 1188
 
1189
-		$this->registerService(IShareHelper::class, function (ContainerInterface $c) {
1189
+		$this->registerService(IShareHelper::class, function(ContainerInterface $c) {
1190 1190
 			return new ShareHelper(
1191 1191
 				$c->get(\OCP\Share\IManager::class)
1192 1192
 			);
1193 1193
 		});
1194 1194
 
1195
-		$this->registerService(IApiFactory::class, function (ContainerInterface $c) {
1195
+		$this->registerService(IApiFactory::class, function(ContainerInterface $c) {
1196 1196
 			return new ApiFactory($c->get(IClientService::class));
1197 1197
 		});
1198 1198
 
1199
-		$this->registerService(IInstanceFactory::class, function (ContainerInterface $c) {
1199
+		$this->registerService(IInstanceFactory::class, function(ContainerInterface $c) {
1200 1200
 			$memcacheFactory = $c->get(ICacheFactory::class);
1201 1201
 			return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->get(IClientService::class));
1202 1202
 		});
@@ -1268,7 +1268,7 @@  discard block
 block discarded – undo
1268 1268
 		$this->registerAlias(ISignatureManager::class, SignatureManager::class);
1269 1269
 
1270 1270
 		$this->registerAlias(ISnowflakeGenerator::class, SnowflakeGenerator::class);
1271
-		$this->registerService(ISequence::class, function (ContainerInterface $c): ISequence {
1271
+		$this->registerService(ISequence::class, function(ContainerInterface $c): ISequence {
1272 1272
 			if (PHP_SAPI !== 'cli') {
1273 1273
 				$sequence = $c->get(APCuSequence::class);
1274 1274
 				if ($sequence->isAvailable()) {
Please login to merge, or discard this patch.
lib/private/Settings/AuthorizedGroup.php 1 patch
Indentation   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -15,17 +15,17 @@
 block discarded – undo
15 15
  * @method getClass(): string
16 16
  */
17 17
 class AuthorizedGroup extends Entity implements \JsonSerializable {
18
-	/** @var string $group_id */
19
-	protected $groupId;
18
+    /** @var string $group_id */
19
+    protected $groupId;
20 20
 
21
-	/** @var string $class */
22
-	protected $class;
21
+    /** @var string $class */
22
+    protected $class;
23 23
 
24
-	public function jsonSerialize(): array {
25
-		return [
26
-			'id' => $this->getId(),
27
-			'group_id' => $this->groupId,
28
-			'class' => $this->class
29
-		];
30
-	}
24
+    public function jsonSerialize(): array {
25
+        return [
26
+            'id' => $this->getId(),
27
+            'group_id' => $this->groupId,
28
+            'class' => $this->class
29
+        ];
30
+    }
31 31
 }
Please login to merge, or discard this patch.
lib/private/Preview/Storage/LocalPreviewStorage.php 2 patches
Indentation   +212 added lines, -212 removed lines patch added patch discarded remove patch
@@ -29,216 +29,216 @@
 block discarded – undo
29 29
 use RecursiveIteratorIterator;
30 30
 
31 31
 class LocalPreviewStorage implements IPreviewStorage {
32
-	private readonly string $rootFolder;
33
-	private readonly string $instanceId;
34
-
35
-	public function __construct(
36
-		private readonly IConfig $config,
37
-		private readonly PreviewMapper $previewMapper,
38
-		private readonly IAppConfig $appConfig,
39
-		private readonly IDBConnection $connection,
40
-		private readonly IMimeTypeDetector $mimeTypeDetector,
41
-		private readonly LoggerInterface $logger,
42
-		private readonly ISnowflakeGenerator $generator,
43
-	) {
44
-		$this->instanceId = $this->config->getSystemValueString('instanceid');
45
-		$this->rootFolder = $this->config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data');
46
-	}
47
-
48
-	#[Override]
49
-	public function writePreview(Preview $preview, mixed $stream): int {
50
-		$previewPath = $this->constructPath($preview);
51
-		$this->createParentFiles($previewPath);
52
-		return file_put_contents($previewPath, $stream);
53
-	}
54
-
55
-	#[Override]
56
-	public function readPreview(Preview $preview): mixed {
57
-		$previewPath = $this->constructPath($preview);
58
-		$resource = @fopen($previewPath, 'r');
59
-		if ($resource === false) {
60
-			throw new NotFoundException('Unable to open preview stream at ' . $previewPath);
61
-		}
62
-		return $resource;
63
-	}
64
-
65
-	#[Override]
66
-	public function deletePreview(Preview $preview): void {
67
-		$previewPath = $this->constructPath($preview);
68
-		if (!@unlink($previewPath) && is_file($previewPath)) {
69
-			throw new NotPermittedException('Unable to delete preview at ' . $previewPath);
70
-		}
71
-	}
72
-
73
-	public function getPreviewRootFolder(): string {
74
-		return $this->rootFolder . '/appdata_' . $this->instanceId . '/preview/';
75
-	}
76
-
77
-	private function constructPath(Preview $preview): string {
78
-		return $this->getPreviewRootFolder() . implode('/', str_split(substr(md5((string)$preview->getFileId()), 0, 7))) . '/' . $preview->getFileId() . '/' . $preview->getName();
79
-	}
80
-
81
-	private function createParentFiles(string $path): void {
82
-		$dirname = dirname($path);
83
-		@mkdir($dirname, recursive: true);
84
-		if (!is_dir($dirname)) {
85
-			throw new NotPermittedException("Unable to create directory '$dirname'");
86
-		}
87
-	}
88
-
89
-	#[Override]
90
-	public function migratePreview(Preview $preview, SimpleFile $file): void {
91
-		// legacy flat directory
92
-		$sourcePath = $this->getPreviewRootFolder() . $preview->getFileId() . '/' . $preview->getName();
93
-		if (!file_exists($sourcePath)) {
94
-			return;
95
-		}
96
-
97
-		$destinationPath = $this->constructPath($preview);
98
-		if (file_exists($destinationPath)) {
99
-			@unlink($sourcePath); // We already have a new preview, just delete the old one
100
-			return;
101
-		}
102
-
103
-		$this->createParentFiles($destinationPath);
104
-		$ok = rename($sourcePath, $destinationPath);
105
-		if (!$ok) {
106
-			throw new LogicException('Failed to move ' . $sourcePath . ' to ' . $destinationPath);
107
-		}
108
-	}
109
-
110
-	#[Override]
111
-	public function scan(): int {
112
-		$checkForFileCache = !$this->appConfig->getValueBool('core', 'previewMovedDone');
113
-
114
-		$scanner = new RecursiveDirectoryIterator($this->getPreviewRootFolder());
115
-		$previewsFound = 0;
116
-		foreach (new RecursiveIteratorIterator($scanner) as $file) {
117
-			if ($file->isFile()) {
118
-				$preview = Preview::fromPath((string)$file, $this->mimeTypeDetector);
119
-				if ($preview === false) {
120
-					$this->logger->error('Unable to parse preview information for ' . $file->getRealPath());
121
-					continue;
122
-				}
123
-				$preview->generateId();
124
-				try {
125
-					$preview->setSize($file->getSize());
126
-					$preview->setMtime($file->getMtime());
127
-					$preview->setEncrypted(false);
128
-
129
-					$qb = $this->connection->getQueryBuilder();
130
-					$result = $qb->select('storage', 'etag', 'mimetype')
131
-						->from('filecache')
132
-						->where($qb->expr()->eq('fileid', $qb->createNamedParameter($preview->getFileId())))
133
-						->setMaxResults(1)
134
-						->runAcrossAllShards() // Unavoidable because we can't extract the storage_id from the preview name
135
-						->executeQuery()
136
-						->fetchAll();
137
-
138
-					if (empty($result)) {
139
-						// original file is deleted
140
-						@unlink($file->getRealPath());
141
-						continue;
142
-					}
143
-
144
-					if ($checkForFileCache) {
145
-						$relativePath = str_replace($this->rootFolder . '/', '', $file->getRealPath());
146
-						$rowAffected = $qb->delete('filecache')
147
-							->where($qb->expr()->eq('path_hash', $qb->createNamedParameter(md5($relativePath))))
148
-							->executeStatement();
149
-						if ($rowAffected > 0) {
150
-							$this->deleteParentsFromFileCache(dirname($relativePath));
151
-						}
152
-					}
153
-
154
-					$preview->setStorageId($result[0]['storage']);
155
-					$preview->setEtag($result[0]['etag']);
156
-					$preview->setSourceMimetype($result[0]['mimetype']);
157
-					$preview->generateId();
158
-					// try to insert, if that fails the preview is already in the DB
159
-					$this->previewMapper->insert($preview);
160
-
161
-					// Move old flat preview to new format
162
-					$dirName = str_replace($this->getPreviewRootFolder(), '', $file->getPath());
163
-					if (preg_match('/[0-9a-e]\/[0-9a-e]\/[0-9a-e]\/[0-9a-e]\/[0-9a-e]\/[0-9a-e]\/[0-9a-e]\/[0-9]+/', $dirName) !== 1) {
164
-						$previewPath = $this->constructPath($preview);
165
-						$this->createParentFiles($previewPath);
166
-						$ok = rename($file->getRealPath(), $previewPath);
167
-						if (!$ok) {
168
-							throw new LogicException('Failed to move ' . $file->getRealPath() . ' to ' . $previewPath);
169
-						}
170
-					}
171
-				} catch (Exception $e) {
172
-					if ($e->getReason() !== Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
173
-						throw $e;
174
-					}
175
-				}
176
-				$previewsFound++;
177
-			}
178
-		}
179
-
180
-		return $previewsFound;
181
-	}
182
-
183
-	private function deleteParentsFromFileCache(string $dirname): void {
184
-		$qb = $this->connection->getQueryBuilder();
185
-
186
-		$result = $qb->select('fileid', 'path', 'storage', 'parent')
187
-			->from('filecache')
188
-			->where($qb->expr()->eq('path_hash', $qb->createNamedParameter(md5($dirname))))
189
-			->setMaxResults(1)
190
-			->runAcrossAllShards()
191
-			->executeQuery()
192
-			->fetchAll();
193
-
194
-		if (empty($result)) {
195
-			return;
196
-		}
197
-
198
-		$this->connection->beginTransaction();
199
-
200
-		$parentId = $result[0]['parent'];
201
-		$fileId = $result[0]['fileid'];
202
-		$storage = $result[0]['storage'];
203
-
204
-		try {
205
-			while (true) {
206
-				$qb = $this->connection->getQueryBuilder();
207
-				$childs = $qb->select('fileid', 'path', 'storage')
208
-					->from('filecache')
209
-					->where($qb->expr()->eq('parent', $qb->createNamedParameter($fileId)))
210
-					->hintShardKey('storage', $storage)
211
-					->executeQuery()
212
-					->fetchAll();
213
-
214
-				if (!empty($childs)) {
215
-					break;
216
-				}
217
-
218
-				$qb = $this->connection->getQueryBuilder();
219
-				$qb->delete('filecache')
220
-					->where($qb->expr()->eq('fileid', $qb->createNamedParameter($fileId)))
221
-					->hintShardKey('storage', $result[0]['storage'])
222
-					->executeStatement();
223
-
224
-				$qb = $this->connection->getQueryBuilder();
225
-				$result = $qb->select('fileid', 'path', 'storage', 'parent')
226
-					->from('filecache')
227
-					->where($qb->expr()->eq('fileid', $qb->createNamedParameter($parentId)))
228
-					->setMaxResults(1)
229
-					->hintShardKey('storage', $storage)
230
-					->executeQuery()
231
-					->fetchAll();
232
-
233
-				if (empty($result)) {
234
-					break;
235
-				}
236
-
237
-				$fileId = $parentId;
238
-				$parentId = $result[0]['parent'];
239
-			}
240
-		} finally {
241
-			$this->connection->commit();
242
-		}
243
-	}
32
+    private readonly string $rootFolder;
33
+    private readonly string $instanceId;
34
+
35
+    public function __construct(
36
+        private readonly IConfig $config,
37
+        private readonly PreviewMapper $previewMapper,
38
+        private readonly IAppConfig $appConfig,
39
+        private readonly IDBConnection $connection,
40
+        private readonly IMimeTypeDetector $mimeTypeDetector,
41
+        private readonly LoggerInterface $logger,
42
+        private readonly ISnowflakeGenerator $generator,
43
+    ) {
44
+        $this->instanceId = $this->config->getSystemValueString('instanceid');
45
+        $this->rootFolder = $this->config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data');
46
+    }
47
+
48
+    #[Override]
49
+    public function writePreview(Preview $preview, mixed $stream): int {
50
+        $previewPath = $this->constructPath($preview);
51
+        $this->createParentFiles($previewPath);
52
+        return file_put_contents($previewPath, $stream);
53
+    }
54
+
55
+    #[Override]
56
+    public function readPreview(Preview $preview): mixed {
57
+        $previewPath = $this->constructPath($preview);
58
+        $resource = @fopen($previewPath, 'r');
59
+        if ($resource === false) {
60
+            throw new NotFoundException('Unable to open preview stream at ' . $previewPath);
61
+        }
62
+        return $resource;
63
+    }
64
+
65
+    #[Override]
66
+    public function deletePreview(Preview $preview): void {
67
+        $previewPath = $this->constructPath($preview);
68
+        if (!@unlink($previewPath) && is_file($previewPath)) {
69
+            throw new NotPermittedException('Unable to delete preview at ' . $previewPath);
70
+        }
71
+    }
72
+
73
+    public function getPreviewRootFolder(): string {
74
+        return $this->rootFolder . '/appdata_' . $this->instanceId . '/preview/';
75
+    }
76
+
77
+    private function constructPath(Preview $preview): string {
78
+        return $this->getPreviewRootFolder() . implode('/', str_split(substr(md5((string)$preview->getFileId()), 0, 7))) . '/' . $preview->getFileId() . '/' . $preview->getName();
79
+    }
80
+
81
+    private function createParentFiles(string $path): void {
82
+        $dirname = dirname($path);
83
+        @mkdir($dirname, recursive: true);
84
+        if (!is_dir($dirname)) {
85
+            throw new NotPermittedException("Unable to create directory '$dirname'");
86
+        }
87
+    }
88
+
89
+    #[Override]
90
+    public function migratePreview(Preview $preview, SimpleFile $file): void {
91
+        // legacy flat directory
92
+        $sourcePath = $this->getPreviewRootFolder() . $preview->getFileId() . '/' . $preview->getName();
93
+        if (!file_exists($sourcePath)) {
94
+            return;
95
+        }
96
+
97
+        $destinationPath = $this->constructPath($preview);
98
+        if (file_exists($destinationPath)) {
99
+            @unlink($sourcePath); // We already have a new preview, just delete the old one
100
+            return;
101
+        }
102
+
103
+        $this->createParentFiles($destinationPath);
104
+        $ok = rename($sourcePath, $destinationPath);
105
+        if (!$ok) {
106
+            throw new LogicException('Failed to move ' . $sourcePath . ' to ' . $destinationPath);
107
+        }
108
+    }
109
+
110
+    #[Override]
111
+    public function scan(): int {
112
+        $checkForFileCache = !$this->appConfig->getValueBool('core', 'previewMovedDone');
113
+
114
+        $scanner = new RecursiveDirectoryIterator($this->getPreviewRootFolder());
115
+        $previewsFound = 0;
116
+        foreach (new RecursiveIteratorIterator($scanner) as $file) {
117
+            if ($file->isFile()) {
118
+                $preview = Preview::fromPath((string)$file, $this->mimeTypeDetector);
119
+                if ($preview === false) {
120
+                    $this->logger->error('Unable to parse preview information for ' . $file->getRealPath());
121
+                    continue;
122
+                }
123
+                $preview->generateId();
124
+                try {
125
+                    $preview->setSize($file->getSize());
126
+                    $preview->setMtime($file->getMtime());
127
+                    $preview->setEncrypted(false);
128
+
129
+                    $qb = $this->connection->getQueryBuilder();
130
+                    $result = $qb->select('storage', 'etag', 'mimetype')
131
+                        ->from('filecache')
132
+                        ->where($qb->expr()->eq('fileid', $qb->createNamedParameter($preview->getFileId())))
133
+                        ->setMaxResults(1)
134
+                        ->runAcrossAllShards() // Unavoidable because we can't extract the storage_id from the preview name
135
+                        ->executeQuery()
136
+                        ->fetchAll();
137
+
138
+                    if (empty($result)) {
139
+                        // original file is deleted
140
+                        @unlink($file->getRealPath());
141
+                        continue;
142
+                    }
143
+
144
+                    if ($checkForFileCache) {
145
+                        $relativePath = str_replace($this->rootFolder . '/', '', $file->getRealPath());
146
+                        $rowAffected = $qb->delete('filecache')
147
+                            ->where($qb->expr()->eq('path_hash', $qb->createNamedParameter(md5($relativePath))))
148
+                            ->executeStatement();
149
+                        if ($rowAffected > 0) {
150
+                            $this->deleteParentsFromFileCache(dirname($relativePath));
151
+                        }
152
+                    }
153
+
154
+                    $preview->setStorageId($result[0]['storage']);
155
+                    $preview->setEtag($result[0]['etag']);
156
+                    $preview->setSourceMimetype($result[0]['mimetype']);
157
+                    $preview->generateId();
158
+                    // try to insert, if that fails the preview is already in the DB
159
+                    $this->previewMapper->insert($preview);
160
+
161
+                    // Move old flat preview to new format
162
+                    $dirName = str_replace($this->getPreviewRootFolder(), '', $file->getPath());
163
+                    if (preg_match('/[0-9a-e]\/[0-9a-e]\/[0-9a-e]\/[0-9a-e]\/[0-9a-e]\/[0-9a-e]\/[0-9a-e]\/[0-9]+/', $dirName) !== 1) {
164
+                        $previewPath = $this->constructPath($preview);
165
+                        $this->createParentFiles($previewPath);
166
+                        $ok = rename($file->getRealPath(), $previewPath);
167
+                        if (!$ok) {
168
+                            throw new LogicException('Failed to move ' . $file->getRealPath() . ' to ' . $previewPath);
169
+                        }
170
+                    }
171
+                } catch (Exception $e) {
172
+                    if ($e->getReason() !== Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
173
+                        throw $e;
174
+                    }
175
+                }
176
+                $previewsFound++;
177
+            }
178
+        }
179
+
180
+        return $previewsFound;
181
+    }
182
+
183
+    private function deleteParentsFromFileCache(string $dirname): void {
184
+        $qb = $this->connection->getQueryBuilder();
185
+
186
+        $result = $qb->select('fileid', 'path', 'storage', 'parent')
187
+            ->from('filecache')
188
+            ->where($qb->expr()->eq('path_hash', $qb->createNamedParameter(md5($dirname))))
189
+            ->setMaxResults(1)
190
+            ->runAcrossAllShards()
191
+            ->executeQuery()
192
+            ->fetchAll();
193
+
194
+        if (empty($result)) {
195
+            return;
196
+        }
197
+
198
+        $this->connection->beginTransaction();
199
+
200
+        $parentId = $result[0]['parent'];
201
+        $fileId = $result[0]['fileid'];
202
+        $storage = $result[0]['storage'];
203
+
204
+        try {
205
+            while (true) {
206
+                $qb = $this->connection->getQueryBuilder();
207
+                $childs = $qb->select('fileid', 'path', 'storage')
208
+                    ->from('filecache')
209
+                    ->where($qb->expr()->eq('parent', $qb->createNamedParameter($fileId)))
210
+                    ->hintShardKey('storage', $storage)
211
+                    ->executeQuery()
212
+                    ->fetchAll();
213
+
214
+                if (!empty($childs)) {
215
+                    break;
216
+                }
217
+
218
+                $qb = $this->connection->getQueryBuilder();
219
+                $qb->delete('filecache')
220
+                    ->where($qb->expr()->eq('fileid', $qb->createNamedParameter($fileId)))
221
+                    ->hintShardKey('storage', $result[0]['storage'])
222
+                    ->executeStatement();
223
+
224
+                $qb = $this->connection->getQueryBuilder();
225
+                $result = $qb->select('fileid', 'path', 'storage', 'parent')
226
+                    ->from('filecache')
227
+                    ->where($qb->expr()->eq('fileid', $qb->createNamedParameter($parentId)))
228
+                    ->setMaxResults(1)
229
+                    ->hintShardKey('storage', $storage)
230
+                    ->executeQuery()
231
+                    ->fetchAll();
232
+
233
+                if (empty($result)) {
234
+                    break;
235
+                }
236
+
237
+                $fileId = $parentId;
238
+                $parentId = $result[0]['parent'];
239
+            }
240
+        } finally {
241
+            $this->connection->commit();
242
+        }
243
+    }
244 244
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -42,7 +42,7 @@  discard block
 block discarded – undo
42 42
 		private readonly ISnowflakeGenerator $generator,
43 43
 	) {
44 44
 		$this->instanceId = $this->config->getSystemValueString('instanceid');
45
-		$this->rootFolder = $this->config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data');
45
+		$this->rootFolder = $this->config->getSystemValue('datadirectory', OC::$SERVERROOT.'/data');
46 46
 	}
47 47
 
48 48
 	#[Override]
@@ -57,7 +57,7 @@  discard block
 block discarded – undo
57 57
 		$previewPath = $this->constructPath($preview);
58 58
 		$resource = @fopen($previewPath, 'r');
59 59
 		if ($resource === false) {
60
-			throw new NotFoundException('Unable to open preview stream at ' . $previewPath);
60
+			throw new NotFoundException('Unable to open preview stream at '.$previewPath);
61 61
 		}
62 62
 		return $resource;
63 63
 	}
@@ -66,16 +66,16 @@  discard block
 block discarded – undo
66 66
 	public function deletePreview(Preview $preview): void {
67 67
 		$previewPath = $this->constructPath($preview);
68 68
 		if (!@unlink($previewPath) && is_file($previewPath)) {
69
-			throw new NotPermittedException('Unable to delete preview at ' . $previewPath);
69
+			throw new NotPermittedException('Unable to delete preview at '.$previewPath);
70 70
 		}
71 71
 	}
72 72
 
73 73
 	public function getPreviewRootFolder(): string {
74
-		return $this->rootFolder . '/appdata_' . $this->instanceId . '/preview/';
74
+		return $this->rootFolder.'/appdata_'.$this->instanceId.'/preview/';
75 75
 	}
76 76
 
77 77
 	private function constructPath(Preview $preview): string {
78
-		return $this->getPreviewRootFolder() . implode('/', str_split(substr(md5((string)$preview->getFileId()), 0, 7))) . '/' . $preview->getFileId() . '/' . $preview->getName();
78
+		return $this->getPreviewRootFolder().implode('/', str_split(substr(md5((string) $preview->getFileId()), 0, 7))).'/'.$preview->getFileId().'/'.$preview->getName();
79 79
 	}
80 80
 
81 81
 	private function createParentFiles(string $path): void {
@@ -89,7 +89,7 @@  discard block
 block discarded – undo
89 89
 	#[Override]
90 90
 	public function migratePreview(Preview $preview, SimpleFile $file): void {
91 91
 		// legacy flat directory
92
-		$sourcePath = $this->getPreviewRootFolder() . $preview->getFileId() . '/' . $preview->getName();
92
+		$sourcePath = $this->getPreviewRootFolder().$preview->getFileId().'/'.$preview->getName();
93 93
 		if (!file_exists($sourcePath)) {
94 94
 			return;
95 95
 		}
@@ -103,7 +103,7 @@  discard block
 block discarded – undo
103 103
 		$this->createParentFiles($destinationPath);
104 104
 		$ok = rename($sourcePath, $destinationPath);
105 105
 		if (!$ok) {
106
-			throw new LogicException('Failed to move ' . $sourcePath . ' to ' . $destinationPath);
106
+			throw new LogicException('Failed to move '.$sourcePath.' to '.$destinationPath);
107 107
 		}
108 108
 	}
109 109
 
@@ -115,9 +115,9 @@  discard block
 block discarded – undo
115 115
 		$previewsFound = 0;
116 116
 		foreach (new RecursiveIteratorIterator($scanner) as $file) {
117 117
 			if ($file->isFile()) {
118
-				$preview = Preview::fromPath((string)$file, $this->mimeTypeDetector);
118
+				$preview = Preview::fromPath((string) $file, $this->mimeTypeDetector);
119 119
 				if ($preview === false) {
120
-					$this->logger->error('Unable to parse preview information for ' . $file->getRealPath());
120
+					$this->logger->error('Unable to parse preview information for '.$file->getRealPath());
121 121
 					continue;
122 122
 				}
123 123
 				$preview->generateId();
@@ -142,7 +142,7 @@  discard block
 block discarded – undo
142 142
 					}
143 143
 
144 144
 					if ($checkForFileCache) {
145
-						$relativePath = str_replace($this->rootFolder . '/', '', $file->getRealPath());
145
+						$relativePath = str_replace($this->rootFolder.'/', '', $file->getRealPath());
146 146
 						$rowAffected = $qb->delete('filecache')
147 147
 							->where($qb->expr()->eq('path_hash', $qb->createNamedParameter(md5($relativePath))))
148 148
 							->executeStatement();
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
 						$this->createParentFiles($previewPath);
166 166
 						$ok = rename($file->getRealPath(), $previewPath);
167 167
 						if (!$ok) {
168
-							throw new LogicException('Failed to move ' . $file->getRealPath() . ' to ' . $previewPath);
168
+							throw new LogicException('Failed to move '.$file->getRealPath().' to '.$previewPath);
169 169
 						}
170 170
 					}
171 171
 				} catch (Exception $e) {
Please login to merge, or discard this patch.