Completed
Push — master ( 16088c...1f9f41 )
by Daniel
23:50
created
tests/lib/Files/Template/TemplateManagerTest.php 2 patches
Indentation   +74 added lines, -74 removed lines patch added patch discarded remove patch
@@ -27,78 +27,78 @@
 block discarded – undo
27 27
 
28 28
 class TemplateManagerTest extends TestCase {
29 29
 
30
-	private IRootFolder $rootFolder;
31
-	private Coordinator $bootstrapCoordinator;
32
-
33
-	private TemplateManager $templateManager;
34
-
35
-	protected function setUp(): void {
36
-		parent::setUp();
37
-
38
-		$l10n = $this->createMock(IL10N::class);
39
-		$l10n->method('t')
40
-			->willReturnCallback(fn ($string, $params) => sprintf($string, ...$params));
41
-		$l10nFactory = $this->createMock(IFactory::class);
42
-		$l10nFactory->method('get')
43
-			->willReturn($l10n);
44
-		$database = $this->createMock(IDBConnection::class);
45
-		$database->method('supports4ByteText')->willReturn(true);
46
-		$config = $this->createMock(IConfig::class);
47
-		$logger = new NullLogger();
48
-
49
-		$filenameValidator = new FilenameValidator(
50
-			$l10nFactory,
51
-			$database,
52
-			$config,
53
-			$logger,
54
-		);
55
-
56
-		$serverContainer = $this->createMock(\OCP\IServerContainer::class);
57
-		$eventDispatcher = $this->createMock(\OCP\EventDispatcher\IEventDispatcher::class);
58
-		$this->bootstrapCoordinator = $this->createMock(Coordinator::class);
59
-		$this->bootstrapCoordinator->method('getRegistrationContext')
60
-			->willReturn(new RegistrationContext($logger));
61
-		$this->rootFolder = $this->createMock(IRootFolder::class);
62
-		$userSession = $this->createMock(\OCP\IUserSession::class);
63
-		$userManager = $this->createMock(\OCP\IUserManager::class);
64
-		$previewManager = $this->createMock(IPreview::class);
65
-
66
-		$this->templateManager = new TemplateManager(
67
-			$serverContainer,
68
-			$eventDispatcher,
69
-			$this->bootstrapCoordinator,
70
-			$this->rootFolder,
71
-			$userSession,
72
-			$userManager,
73
-			$previewManager,
74
-			$config,
75
-			$l10nFactory,
76
-			$logger,
77
-			$filenameValidator
78
-		);
79
-	}
80
-
81
-	public function testCreateFromTemplateShoudValidateFilename(): void {
82
-		$this->expectException(GenericFileException::class);
83
-
84
-		$fileDirectory = '/';
85
-		$filePath = $fileDirectory . str_repeat('a', 251);
86
-
87
-		$userFolder = $this->createMock(Folder::class);
88
-		$userFolder->method('get')
89
-			->willReturnCallback(function ($path) use ($filePath, $fileDirectory) {
90
-				if ($path === $filePath) {
91
-					throw new NotFoundException();
92
-				}
93
-				return $this->createMock(Folder::class);
94
-			});
95
-		$userFolder->method('nodeExists')
96
-			->willReturnCallback(function ($path) use ($filePath, $fileDirectory) {
97
-				return $path === $fileDirectory;
98
-			});
99
-		$this->rootFolder->method('getUserFolder')
100
-			->willReturn($userFolder);
101
-
102
-		$this->templateManager->createFromTemplate($filePath);
103
-	}
30
+    private IRootFolder $rootFolder;
31
+    private Coordinator $bootstrapCoordinator;
32
+
33
+    private TemplateManager $templateManager;
34
+
35
+    protected function setUp(): void {
36
+        parent::setUp();
37
+
38
+        $l10n = $this->createMock(IL10N::class);
39
+        $l10n->method('t')
40
+            ->willReturnCallback(fn ($string, $params) => sprintf($string, ...$params));
41
+        $l10nFactory = $this->createMock(IFactory::class);
42
+        $l10nFactory->method('get')
43
+            ->willReturn($l10n);
44
+        $database = $this->createMock(IDBConnection::class);
45
+        $database->method('supports4ByteText')->willReturn(true);
46
+        $config = $this->createMock(IConfig::class);
47
+        $logger = new NullLogger();
48
+
49
+        $filenameValidator = new FilenameValidator(
50
+            $l10nFactory,
51
+            $database,
52
+            $config,
53
+            $logger,
54
+        );
55
+
56
+        $serverContainer = $this->createMock(\OCP\IServerContainer::class);
57
+        $eventDispatcher = $this->createMock(\OCP\EventDispatcher\IEventDispatcher::class);
58
+        $this->bootstrapCoordinator = $this->createMock(Coordinator::class);
59
+        $this->bootstrapCoordinator->method('getRegistrationContext')
60
+            ->willReturn(new RegistrationContext($logger));
61
+        $this->rootFolder = $this->createMock(IRootFolder::class);
62
+        $userSession = $this->createMock(\OCP\IUserSession::class);
63
+        $userManager = $this->createMock(\OCP\IUserManager::class);
64
+        $previewManager = $this->createMock(IPreview::class);
65
+
66
+        $this->templateManager = new TemplateManager(
67
+            $serverContainer,
68
+            $eventDispatcher,
69
+            $this->bootstrapCoordinator,
70
+            $this->rootFolder,
71
+            $userSession,
72
+            $userManager,
73
+            $previewManager,
74
+            $config,
75
+            $l10nFactory,
76
+            $logger,
77
+            $filenameValidator
78
+        );
79
+    }
80
+
81
+    public function testCreateFromTemplateShoudValidateFilename(): void {
82
+        $this->expectException(GenericFileException::class);
83
+
84
+        $fileDirectory = '/';
85
+        $filePath = $fileDirectory . str_repeat('a', 251);
86
+
87
+        $userFolder = $this->createMock(Folder::class);
88
+        $userFolder->method('get')
89
+            ->willReturnCallback(function ($path) use ($filePath, $fileDirectory) {
90
+                if ($path === $filePath) {
91
+                    throw new NotFoundException();
92
+                }
93
+                return $this->createMock(Folder::class);
94
+            });
95
+        $userFolder->method('nodeExists')
96
+            ->willReturnCallback(function ($path) use ($filePath, $fileDirectory) {
97
+                return $path === $fileDirectory;
98
+            });
99
+        $this->rootFolder->method('getUserFolder')
100
+            ->willReturn($userFolder);
101
+
102
+        $this->templateManager->createFromTemplate($filePath);
103
+    }
104 104
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -82,18 +82,18 @@
 block discarded – undo
82 82
 		$this->expectException(GenericFileException::class);
83 83
 
84 84
 		$fileDirectory = '/';
85
-		$filePath = $fileDirectory . str_repeat('a', 251);
85
+		$filePath = $fileDirectory.str_repeat('a', 251);
86 86
 
87 87
 		$userFolder = $this->createMock(Folder::class);
88 88
 		$userFolder->method('get')
89
-			->willReturnCallback(function ($path) use ($filePath, $fileDirectory) {
89
+			->willReturnCallback(function($path) use ($filePath, $fileDirectory) {
90 90
 				if ($path === $filePath) {
91 91
 					throw new NotFoundException();
92 92
 				}
93 93
 				return $this->createMock(Folder::class);
94 94
 			});
95 95
 		$userFolder->method('nodeExists')
96
-			->willReturnCallback(function ($path) use ($filePath, $fileDirectory) {
96
+			->willReturnCallback(function($path) use ($filePath, $fileDirectory) {
97 97
 				return $path === $fileDirectory;
98 98
 			});
99 99
 		$this->rootFolder->method('getUserFolder')
Please login to merge, or discard this patch.
lib/private/Files/Template/TemplateManager.php 1 patch
Indentation   +384 added lines, -384 removed lines patch added patch discarded remove patch
@@ -36,390 +36,390 @@
 block discarded – undo
36 36
 use Psr\Log\LoggerInterface;
37 37
 
38 38
 class TemplateManager implements ITemplateManager {
39
-	private $registeredTypes = [];
40
-	private $types = [];
41
-
42
-	/** @var array|null */
43
-	private $providers = null;
44
-
45
-	private $serverContainer;
46
-	private $eventDispatcher;
47
-	private $rootFolder;
48
-	private $userManager;
49
-	private $previewManager;
50
-	private $config;
51
-	private $l10n;
52
-	private $logger;
53
-	private $userId;
54
-	private $l10nFactory;
55
-	/** @var Coordinator */
56
-	private $bootstrapCoordinator;
57
-
58
-	public function __construct(
59
-		IServerContainer $serverContainer,
60
-		IEventDispatcher $eventDispatcher,
61
-		Coordinator $coordinator,
62
-		IRootFolder $rootFolder,
63
-		IUserSession $userSession,
64
-		IUserManager $userManager,
65
-		IPreview $previewManager,
66
-		IConfig $config,
67
-		IFactory $l10nFactory,
68
-		LoggerInterface $logger,
69
-		private IFilenameValidator $filenameValidator,
70
-	) {
71
-		$this->serverContainer = $serverContainer;
72
-		$this->eventDispatcher = $eventDispatcher;
73
-		$this->bootstrapCoordinator = $coordinator;
74
-		$this->rootFolder = $rootFolder;
75
-		$this->userManager = $userManager;
76
-		$this->previewManager = $previewManager;
77
-		$this->config = $config;
78
-		$this->l10nFactory = $l10nFactory;
79
-		$this->l10n = $l10nFactory->get('lib');
80
-		$this->logger = $logger;
81
-		$user = $userSession->getUser();
82
-		$this->userId = $user ? $user->getUID() : null;
83
-	}
84
-
85
-	public function registerTemplateFileCreator(callable $callback): void {
86
-		$this->registeredTypes[] = $callback;
87
-	}
88
-
89
-	public function getRegisteredProviders(): array {
90
-		if ($this->providers !== null) {
91
-			return $this->providers;
92
-		}
93
-
94
-		$context = $this->bootstrapCoordinator->getRegistrationContext();
95
-
96
-		$this->providers = [];
97
-		foreach ($context->getTemplateProviders() as $provider) {
98
-			$class = $provider->getService();
99
-			$this->providers[$class] = $this->serverContainer->get($class);
100
-		}
101
-		return $this->providers;
102
-	}
103
-
104
-	public function getTypes(): array {
105
-		if (!empty($this->types)) {
106
-			return $this->types;
107
-		}
108
-		$this->eventDispatcher->dispatchTyped(new RegisterTemplateCreatorEvent($this));
109
-		foreach ($this->registeredTypes as $registeredType) {
110
-			$this->types[] = $registeredType();
111
-		}
112
-		return $this->types;
113
-	}
114
-
115
-	public function listCreators(): array {
116
-		$types = $this->getTypes();
117
-		usort($types, function (TemplateFileCreator $a, TemplateFileCreator $b) {
118
-			return $a->getOrder() - $b->getOrder();
119
-		});
120
-		return $types;
121
-	}
122
-
123
-	public function listTemplates(): array {
124
-		return array_values(array_map(function (TemplateFileCreator $entry) {
125
-			return array_merge($entry->jsonSerialize(), [
126
-				'templates' => $this->getTemplateFiles($entry)
127
-			]);
128
-		}, $this->listCreators()));
129
-	}
130
-
131
-	public function listTemplateFields(int $fileId): array {
132
-		foreach ($this->listCreators() as $creator) {
133
-			$fields = $this->getTemplateFields($creator, $fileId);
134
-			if (empty($fields)) {
135
-				continue;
136
-			}
137
-
138
-			return $fields;
139
-		}
140
-
141
-		return [];
142
-	}
143
-
144
-	/**
145
-	 * @param string $filePath
146
-	 * @param string $templateId
147
-	 * @param array $templateFields
148
-	 * @return array
149
-	 * @throws GenericFileException
150
-	 */
151
-	public function createFromTemplate(string $filePath, string $templateId = '', string $templateType = 'user', array $templateFields = []): array {
152
-		$userFolder = $this->rootFolder->getUserFolder($this->userId);
153
-		try {
154
-			$userFolder->get($filePath);
155
-			throw new GenericFileException($this->l10n->t('File already exists'));
156
-		} catch (NotFoundException $e) {
157
-		}
158
-		try {
159
-			if (!$userFolder->nodeExists(dirname($filePath))) {
160
-				throw new GenericFileException($this->l10n->t('Invalid path'));
161
-			}
162
-			$folder = $userFolder->get(dirname($filePath));
163
-			$template = null;
164
-			if ($templateType === 'user' && $templateId !== '') {
165
-				$template = $userFolder->get($templateId);
166
-			} else {
167
-				$matchingProvider = array_filter($this->getRegisteredProviders(), function (ICustomTemplateProvider $provider) use ($templateType) {
168
-					return $templateType === get_class($provider);
169
-				});
170
-				$provider = array_shift($matchingProvider);
171
-				if ($provider) {
172
-					$template = $provider->getCustomTemplate($templateId);
173
-				}
174
-			}
175
-
176
-			$filename = basename($filePath);
177
-			$this->filenameValidator->validateFilename($filename);
178
-			$targetFile = $folder->newFile($filename, ($template instanceof File ? $template->fopen('rb') : null));
179
-
180
-			$this->eventDispatcher->dispatchTyped(new FileCreatedFromTemplateEvent($template, $targetFile, $templateFields));
181
-			return $this->formatFile($userFolder->get($filePath));
182
-		} catch (\Exception $e) {
183
-			$this->logger->error($e->getMessage(), ['exception' => $e]);
184
-			throw new GenericFileException($this->l10n->t('Failed to create file from template'));
185
-		}
186
-	}
187
-
188
-	/**
189
-	 * @return Folder
190
-	 * @throws \OCP\Files\NotFoundException
191
-	 * @throws \OCP\Files\NotPermittedException
192
-	 * @throws \OC\User\NoUserException
193
-	 */
194
-	private function getTemplateFolder(): Folder {
195
-		if ($this->getTemplatePath() !== '') {
196
-			$path = $this->rootFolder->getUserFolder($this->userId)->get($this->getTemplatePath());
197
-			if ($path instanceof Folder) {
198
-				return $path;
199
-			}
200
-		}
201
-		throw new NotFoundException();
202
-	}
203
-
204
-	/**
205
-	 * @return list<Template>
206
-	 */
207
-	private function getTemplateFiles(TemplateFileCreator $type): array {
208
-		$templates = array_merge(
209
-			$this->getProviderTemplates($type),
210
-			$this->getUserTemplates($type)
211
-		);
212
-
213
-		$this->eventDispatcher->dispatchTyped(new BeforeGetTemplatesEvent($templates, false));
214
-
215
-		return $templates;
216
-	}
217
-
218
-	/**
219
-	 * @return list<Template>
220
-	 */
221
-	private function getProviderTemplates(TemplateFileCreator $type): array {
222
-		$templates = [];
223
-		foreach ($this->getRegisteredProviders() as $provider) {
224
-			foreach ($type->getMimetypes() as $mimetype) {
225
-				foreach ($provider->getCustomTemplates($mimetype) as $template) {
226
-					$templates[] = $template;
227
-				}
228
-			}
229
-		}
230
-
231
-		return $templates;
232
-	}
233
-
234
-	/**
235
-	 * @return list<Template>
236
-	 */
237
-	private function getUserTemplates(TemplateFileCreator $type): array {
238
-		$templates = [];
239
-
240
-		try {
241
-			$userTemplateFolder = $this->getTemplateFolder();
242
-		} catch (\Exception $e) {
243
-			return $templates;
244
-		}
245
-
246
-		foreach ($type->getMimetypes() as $mimetype) {
247
-			foreach ($userTemplateFolder->searchByMime($mimetype) as $templateFile) {
248
-				$template = new Template(
249
-					'user',
250
-					$this->rootFolder->getUserFolder($this->userId)->getRelativePath($templateFile->getPath()),
251
-					$templateFile
252
-				);
253
-				$template->setHasPreview($this->previewManager->isAvailable($templateFile));
254
-				$templates[] = $template;
255
-			}
256
-		}
257
-
258
-		return $templates;
259
-	}
260
-
261
-	/*
39
+    private $registeredTypes = [];
40
+    private $types = [];
41
+
42
+    /** @var array|null */
43
+    private $providers = null;
44
+
45
+    private $serverContainer;
46
+    private $eventDispatcher;
47
+    private $rootFolder;
48
+    private $userManager;
49
+    private $previewManager;
50
+    private $config;
51
+    private $l10n;
52
+    private $logger;
53
+    private $userId;
54
+    private $l10nFactory;
55
+    /** @var Coordinator */
56
+    private $bootstrapCoordinator;
57
+
58
+    public function __construct(
59
+        IServerContainer $serverContainer,
60
+        IEventDispatcher $eventDispatcher,
61
+        Coordinator $coordinator,
62
+        IRootFolder $rootFolder,
63
+        IUserSession $userSession,
64
+        IUserManager $userManager,
65
+        IPreview $previewManager,
66
+        IConfig $config,
67
+        IFactory $l10nFactory,
68
+        LoggerInterface $logger,
69
+        private IFilenameValidator $filenameValidator,
70
+    ) {
71
+        $this->serverContainer = $serverContainer;
72
+        $this->eventDispatcher = $eventDispatcher;
73
+        $this->bootstrapCoordinator = $coordinator;
74
+        $this->rootFolder = $rootFolder;
75
+        $this->userManager = $userManager;
76
+        $this->previewManager = $previewManager;
77
+        $this->config = $config;
78
+        $this->l10nFactory = $l10nFactory;
79
+        $this->l10n = $l10nFactory->get('lib');
80
+        $this->logger = $logger;
81
+        $user = $userSession->getUser();
82
+        $this->userId = $user ? $user->getUID() : null;
83
+    }
84
+
85
+    public function registerTemplateFileCreator(callable $callback): void {
86
+        $this->registeredTypes[] = $callback;
87
+    }
88
+
89
+    public function getRegisteredProviders(): array {
90
+        if ($this->providers !== null) {
91
+            return $this->providers;
92
+        }
93
+
94
+        $context = $this->bootstrapCoordinator->getRegistrationContext();
95
+
96
+        $this->providers = [];
97
+        foreach ($context->getTemplateProviders() as $provider) {
98
+            $class = $provider->getService();
99
+            $this->providers[$class] = $this->serverContainer->get($class);
100
+        }
101
+        return $this->providers;
102
+    }
103
+
104
+    public function getTypes(): array {
105
+        if (!empty($this->types)) {
106
+            return $this->types;
107
+        }
108
+        $this->eventDispatcher->dispatchTyped(new RegisterTemplateCreatorEvent($this));
109
+        foreach ($this->registeredTypes as $registeredType) {
110
+            $this->types[] = $registeredType();
111
+        }
112
+        return $this->types;
113
+    }
114
+
115
+    public function listCreators(): array {
116
+        $types = $this->getTypes();
117
+        usort($types, function (TemplateFileCreator $a, TemplateFileCreator $b) {
118
+            return $a->getOrder() - $b->getOrder();
119
+        });
120
+        return $types;
121
+    }
122
+
123
+    public function listTemplates(): array {
124
+        return array_values(array_map(function (TemplateFileCreator $entry) {
125
+            return array_merge($entry->jsonSerialize(), [
126
+                'templates' => $this->getTemplateFiles($entry)
127
+            ]);
128
+        }, $this->listCreators()));
129
+    }
130
+
131
+    public function listTemplateFields(int $fileId): array {
132
+        foreach ($this->listCreators() as $creator) {
133
+            $fields = $this->getTemplateFields($creator, $fileId);
134
+            if (empty($fields)) {
135
+                continue;
136
+            }
137
+
138
+            return $fields;
139
+        }
140
+
141
+        return [];
142
+    }
143
+
144
+    /**
145
+     * @param string $filePath
146
+     * @param string $templateId
147
+     * @param array $templateFields
148
+     * @return array
149
+     * @throws GenericFileException
150
+     */
151
+    public function createFromTemplate(string $filePath, string $templateId = '', string $templateType = 'user', array $templateFields = []): array {
152
+        $userFolder = $this->rootFolder->getUserFolder($this->userId);
153
+        try {
154
+            $userFolder->get($filePath);
155
+            throw new GenericFileException($this->l10n->t('File already exists'));
156
+        } catch (NotFoundException $e) {
157
+        }
158
+        try {
159
+            if (!$userFolder->nodeExists(dirname($filePath))) {
160
+                throw new GenericFileException($this->l10n->t('Invalid path'));
161
+            }
162
+            $folder = $userFolder->get(dirname($filePath));
163
+            $template = null;
164
+            if ($templateType === 'user' && $templateId !== '') {
165
+                $template = $userFolder->get($templateId);
166
+            } else {
167
+                $matchingProvider = array_filter($this->getRegisteredProviders(), function (ICustomTemplateProvider $provider) use ($templateType) {
168
+                    return $templateType === get_class($provider);
169
+                });
170
+                $provider = array_shift($matchingProvider);
171
+                if ($provider) {
172
+                    $template = $provider->getCustomTemplate($templateId);
173
+                }
174
+            }
175
+
176
+            $filename = basename($filePath);
177
+            $this->filenameValidator->validateFilename($filename);
178
+            $targetFile = $folder->newFile($filename, ($template instanceof File ? $template->fopen('rb') : null));
179
+
180
+            $this->eventDispatcher->dispatchTyped(new FileCreatedFromTemplateEvent($template, $targetFile, $templateFields));
181
+            return $this->formatFile($userFolder->get($filePath));
182
+        } catch (\Exception $e) {
183
+            $this->logger->error($e->getMessage(), ['exception' => $e]);
184
+            throw new GenericFileException($this->l10n->t('Failed to create file from template'));
185
+        }
186
+    }
187
+
188
+    /**
189
+     * @return Folder
190
+     * @throws \OCP\Files\NotFoundException
191
+     * @throws \OCP\Files\NotPermittedException
192
+     * @throws \OC\User\NoUserException
193
+     */
194
+    private function getTemplateFolder(): Folder {
195
+        if ($this->getTemplatePath() !== '') {
196
+            $path = $this->rootFolder->getUserFolder($this->userId)->get($this->getTemplatePath());
197
+            if ($path instanceof Folder) {
198
+                return $path;
199
+            }
200
+        }
201
+        throw new NotFoundException();
202
+    }
203
+
204
+    /**
205
+     * @return list<Template>
206
+     */
207
+    private function getTemplateFiles(TemplateFileCreator $type): array {
208
+        $templates = array_merge(
209
+            $this->getProviderTemplates($type),
210
+            $this->getUserTemplates($type)
211
+        );
212
+
213
+        $this->eventDispatcher->dispatchTyped(new BeforeGetTemplatesEvent($templates, false));
214
+
215
+        return $templates;
216
+    }
217
+
218
+    /**
219
+     * @return list<Template>
220
+     */
221
+    private function getProviderTemplates(TemplateFileCreator $type): array {
222
+        $templates = [];
223
+        foreach ($this->getRegisteredProviders() as $provider) {
224
+            foreach ($type->getMimetypes() as $mimetype) {
225
+                foreach ($provider->getCustomTemplates($mimetype) as $template) {
226
+                    $templates[] = $template;
227
+                }
228
+            }
229
+        }
230
+
231
+        return $templates;
232
+    }
233
+
234
+    /**
235
+     * @return list<Template>
236
+     */
237
+    private function getUserTemplates(TemplateFileCreator $type): array {
238
+        $templates = [];
239
+
240
+        try {
241
+            $userTemplateFolder = $this->getTemplateFolder();
242
+        } catch (\Exception $e) {
243
+            return $templates;
244
+        }
245
+
246
+        foreach ($type->getMimetypes() as $mimetype) {
247
+            foreach ($userTemplateFolder->searchByMime($mimetype) as $templateFile) {
248
+                $template = new Template(
249
+                    'user',
250
+                    $this->rootFolder->getUserFolder($this->userId)->getRelativePath($templateFile->getPath()),
251
+                    $templateFile
252
+                );
253
+                $template->setHasPreview($this->previewManager->isAvailable($templateFile));
254
+                $templates[] = $template;
255
+            }
256
+        }
257
+
258
+        return $templates;
259
+    }
260
+
261
+    /*
262 262
 	 * @return list<Field>
263 263
 	 */
264
-	private function getTemplateFields(TemplateFileCreator $type, int $fileId): array {
265
-		$providerTemplates = $this->getProviderTemplates($type);
266
-		$userTemplates = $this->getUserTemplates($type);
267
-
268
-		$matchedTemplates = array_filter(
269
-			array_merge($providerTemplates, $userTemplates),
270
-			function (Template $template) use ($fileId) {
271
-				return $template->jsonSerialize()['fileid'] === $fileId;
272
-			});
273
-
274
-		if (empty($matchedTemplates)) {
275
-			return [];
276
-		}
277
-
278
-		$this->eventDispatcher->dispatchTyped(new BeforeGetTemplatesEvent($matchedTemplates, true));
279
-
280
-		return array_values(array_map(function (Template $template) {
281
-			return $template->jsonSerialize()['fields'] ?? [];
282
-		}, $matchedTemplates));
283
-	}
284
-
285
-	/**
286
-	 * @param Node|File $file
287
-	 * @return array
288
-	 * @throws NotFoundException
289
-	 * @throws \OCP\Files\InvalidPathException
290
-	 */
291
-	private function formatFile(Node $file): array {
292
-		return [
293
-			'basename' => $file->getName(),
294
-			'etag' => $file->getEtag(),
295
-			'fileid' => $file->getId(),
296
-			'filename' => $this->rootFolder->getUserFolder($this->userId)->getRelativePath($file->getPath()),
297
-			'lastmod' => $file->getMTime(),
298
-			'mime' => $file->getMimetype(),
299
-			'size' => $file->getSize(),
300
-			'type' => $file->getType(),
301
-			'hasPreview' => $this->previewManager->isAvailable($file),
302
-			'permissions' => $file->getPermissions(),
303
-		];
304
-	}
305
-
306
-	public function hasTemplateDirectory(): bool {
307
-		try {
308
-			$this->getTemplateFolder();
309
-			return true;
310
-		} catch (\Exception $e) {
311
-		}
312
-		return false;
313
-	}
314
-
315
-	public function setTemplatePath(string $path): void {
316
-		$this->config->setUserValue($this->userId, 'core', 'templateDirectory', $path);
317
-	}
318
-
319
-	public function getTemplatePath(): string {
320
-		return $this->config->getUserValue($this->userId, 'core', 'templateDirectory', '');
321
-	}
322
-
323
-	public function initializeTemplateDirectory(?string $path = null, ?string $userId = null, $copyTemplates = true): string {
324
-		if ($userId !== null) {
325
-			$this->userId = $userId;
326
-		}
327
-
328
-		$defaultSkeletonDirectory = \OC::$SERVERROOT . '/core/skeleton';
329
-		$defaultTemplateDirectory = \OC::$SERVERROOT . '/core/skeleton/Templates';
330
-		$skeletonPath = $this->config->getSystemValueString('skeletondirectory', $defaultSkeletonDirectory);
331
-		$skeletonTemplatePath = $this->config->getSystemValueString('templatedirectory', $defaultTemplateDirectory);
332
-		$isDefaultSkeleton = $skeletonPath === $defaultSkeletonDirectory;
333
-		$isDefaultTemplates = $skeletonTemplatePath === $defaultTemplateDirectory;
334
-		$userLang = $this->l10nFactory->getUserLanguage($this->userManager->get($this->userId));
335
-
336
-		if ($skeletonTemplatePath === '') {
337
-			$this->setTemplatePath('');
338
-			return '';
339
-		}
340
-
341
-		try {
342
-			$l10n = $this->l10nFactory->get('lib', $userLang);
343
-			$userFolder = $this->rootFolder->getUserFolder($this->userId);
344
-			$userTemplatePath = $path ?? $this->config->getAppValue('core', 'defaultTemplateDirectory', $l10n->t('Templates')) . '/';
345
-
346
-			// Initial user setup without a provided path
347
-			if ($path === null) {
348
-				// All locations are default so we just need to rename the directory to the users language
349
-				if ($isDefaultSkeleton && $isDefaultTemplates) {
350
-					if (!$userFolder->nodeExists('Templates')) {
351
-						return '';
352
-					}
353
-					$newPath = Filesystem::normalizePath($userFolder->getPath() . '/' . $userTemplatePath);
354
-					if ($newPath !== $userFolder->get('Templates')->getPath()) {
355
-						$userFolder->get('Templates')->move($newPath);
356
-					}
357
-					$this->setTemplatePath($userTemplatePath);
358
-					return $userTemplatePath;
359
-				}
360
-
361
-				if ($isDefaultSkeleton && !empty($skeletonTemplatePath) && !$isDefaultTemplates && $userFolder->nodeExists('Templates')) {
362
-					$shippedSkeletonTemplates = $userFolder->get('Templates');
363
-					$shippedSkeletonTemplates->delete();
364
-				}
365
-			}
366
-
367
-			try {
368
-				$folder = $userFolder->get($userTemplatePath);
369
-			} catch (NotFoundException $e) {
370
-				$folder = $userFolder->get(dirname($userTemplatePath));
371
-				$folder = $folder->newFolder(basename($userTemplatePath));
372
-			}
373
-
374
-			$folderIsEmpty = count($folder->getDirectoryListing()) === 0;
375
-
376
-			if (!$copyTemplates) {
377
-				$this->setTemplatePath($userTemplatePath);
378
-				return $userTemplatePath;
379
-			}
380
-
381
-			if (!$isDefaultTemplates && $folderIsEmpty) {
382
-				$localizedSkeletonTemplatePath = $this->getLocalizedTemplatePath($skeletonTemplatePath, $userLang);
383
-				if (!empty($localizedSkeletonTemplatePath) && file_exists($localizedSkeletonTemplatePath)) {
384
-					\OC_Util::copyr($localizedSkeletonTemplatePath, $folder);
385
-					$userFolder->getStorage()->getScanner()->scan($folder->getInternalPath(), Scanner::SCAN_RECURSIVE);
386
-					$this->setTemplatePath($userTemplatePath);
387
-					return $userTemplatePath;
388
-				}
389
-			}
390
-
391
-			if ($path !== null && $isDefaultSkeleton && $isDefaultTemplates && $folderIsEmpty) {
392
-				$localizedSkeletonPath = $this->getLocalizedTemplatePath($skeletonPath . '/Templates', $userLang);
393
-				if (!empty($localizedSkeletonPath) && file_exists($localizedSkeletonPath)) {
394
-					\OC_Util::copyr($localizedSkeletonPath, $folder);
395
-					$userFolder->getStorage()->getScanner()->scan($folder->getInternalPath(), Scanner::SCAN_RECURSIVE);
396
-					$this->setTemplatePath($userTemplatePath);
397
-					return $userTemplatePath;
398
-				}
399
-			}
400
-
401
-			$this->setTemplatePath($path ?? '');
402
-			return $this->getTemplatePath();
403
-		} catch (\Throwable $e) {
404
-			$this->logger->error('Failed to initialize templates directory to user language ' . $userLang . ' for ' . $userId, ['app' => 'files_templates', 'exception' => $e]);
405
-		}
406
-		$this->setTemplatePath('');
407
-		return $this->getTemplatePath();
408
-	}
409
-
410
-	private function getLocalizedTemplatePath(string $skeletonTemplatePath, string $userLang) {
411
-		$localizedSkeletonTemplatePath = str_replace('{lang}', $userLang, $skeletonTemplatePath);
412
-
413
-		if (!file_exists($localizedSkeletonTemplatePath)) {
414
-			$dialectStart = strpos($userLang, '_');
415
-			if ($dialectStart !== false) {
416
-				$localizedSkeletonTemplatePath = str_replace('{lang}', substr($userLang, 0, $dialectStart), $skeletonTemplatePath);
417
-			}
418
-			if ($dialectStart === false || !file_exists($localizedSkeletonTemplatePath)) {
419
-				$localizedSkeletonTemplatePath = str_replace('{lang}', 'default', $skeletonTemplatePath);
420
-			}
421
-		}
422
-
423
-		return $localizedSkeletonTemplatePath;
424
-	}
264
+    private function getTemplateFields(TemplateFileCreator $type, int $fileId): array {
265
+        $providerTemplates = $this->getProviderTemplates($type);
266
+        $userTemplates = $this->getUserTemplates($type);
267
+
268
+        $matchedTemplates = array_filter(
269
+            array_merge($providerTemplates, $userTemplates),
270
+            function (Template $template) use ($fileId) {
271
+                return $template->jsonSerialize()['fileid'] === $fileId;
272
+            });
273
+
274
+        if (empty($matchedTemplates)) {
275
+            return [];
276
+        }
277
+
278
+        $this->eventDispatcher->dispatchTyped(new BeforeGetTemplatesEvent($matchedTemplates, true));
279
+
280
+        return array_values(array_map(function (Template $template) {
281
+            return $template->jsonSerialize()['fields'] ?? [];
282
+        }, $matchedTemplates));
283
+    }
284
+
285
+    /**
286
+     * @param Node|File $file
287
+     * @return array
288
+     * @throws NotFoundException
289
+     * @throws \OCP\Files\InvalidPathException
290
+     */
291
+    private function formatFile(Node $file): array {
292
+        return [
293
+            'basename' => $file->getName(),
294
+            'etag' => $file->getEtag(),
295
+            'fileid' => $file->getId(),
296
+            'filename' => $this->rootFolder->getUserFolder($this->userId)->getRelativePath($file->getPath()),
297
+            'lastmod' => $file->getMTime(),
298
+            'mime' => $file->getMimetype(),
299
+            'size' => $file->getSize(),
300
+            'type' => $file->getType(),
301
+            'hasPreview' => $this->previewManager->isAvailable($file),
302
+            'permissions' => $file->getPermissions(),
303
+        ];
304
+    }
305
+
306
+    public function hasTemplateDirectory(): bool {
307
+        try {
308
+            $this->getTemplateFolder();
309
+            return true;
310
+        } catch (\Exception $e) {
311
+        }
312
+        return false;
313
+    }
314
+
315
+    public function setTemplatePath(string $path): void {
316
+        $this->config->setUserValue($this->userId, 'core', 'templateDirectory', $path);
317
+    }
318
+
319
+    public function getTemplatePath(): string {
320
+        return $this->config->getUserValue($this->userId, 'core', 'templateDirectory', '');
321
+    }
322
+
323
+    public function initializeTemplateDirectory(?string $path = null, ?string $userId = null, $copyTemplates = true): string {
324
+        if ($userId !== null) {
325
+            $this->userId = $userId;
326
+        }
327
+
328
+        $defaultSkeletonDirectory = \OC::$SERVERROOT . '/core/skeleton';
329
+        $defaultTemplateDirectory = \OC::$SERVERROOT . '/core/skeleton/Templates';
330
+        $skeletonPath = $this->config->getSystemValueString('skeletondirectory', $defaultSkeletonDirectory);
331
+        $skeletonTemplatePath = $this->config->getSystemValueString('templatedirectory', $defaultTemplateDirectory);
332
+        $isDefaultSkeleton = $skeletonPath === $defaultSkeletonDirectory;
333
+        $isDefaultTemplates = $skeletonTemplatePath === $defaultTemplateDirectory;
334
+        $userLang = $this->l10nFactory->getUserLanguage($this->userManager->get($this->userId));
335
+
336
+        if ($skeletonTemplatePath === '') {
337
+            $this->setTemplatePath('');
338
+            return '';
339
+        }
340
+
341
+        try {
342
+            $l10n = $this->l10nFactory->get('lib', $userLang);
343
+            $userFolder = $this->rootFolder->getUserFolder($this->userId);
344
+            $userTemplatePath = $path ?? $this->config->getAppValue('core', 'defaultTemplateDirectory', $l10n->t('Templates')) . '/';
345
+
346
+            // Initial user setup without a provided path
347
+            if ($path === null) {
348
+                // All locations are default so we just need to rename the directory to the users language
349
+                if ($isDefaultSkeleton && $isDefaultTemplates) {
350
+                    if (!$userFolder->nodeExists('Templates')) {
351
+                        return '';
352
+                    }
353
+                    $newPath = Filesystem::normalizePath($userFolder->getPath() . '/' . $userTemplatePath);
354
+                    if ($newPath !== $userFolder->get('Templates')->getPath()) {
355
+                        $userFolder->get('Templates')->move($newPath);
356
+                    }
357
+                    $this->setTemplatePath($userTemplatePath);
358
+                    return $userTemplatePath;
359
+                }
360
+
361
+                if ($isDefaultSkeleton && !empty($skeletonTemplatePath) && !$isDefaultTemplates && $userFolder->nodeExists('Templates')) {
362
+                    $shippedSkeletonTemplates = $userFolder->get('Templates');
363
+                    $shippedSkeletonTemplates->delete();
364
+                }
365
+            }
366
+
367
+            try {
368
+                $folder = $userFolder->get($userTemplatePath);
369
+            } catch (NotFoundException $e) {
370
+                $folder = $userFolder->get(dirname($userTemplatePath));
371
+                $folder = $folder->newFolder(basename($userTemplatePath));
372
+            }
373
+
374
+            $folderIsEmpty = count($folder->getDirectoryListing()) === 0;
375
+
376
+            if (!$copyTemplates) {
377
+                $this->setTemplatePath($userTemplatePath);
378
+                return $userTemplatePath;
379
+            }
380
+
381
+            if (!$isDefaultTemplates && $folderIsEmpty) {
382
+                $localizedSkeletonTemplatePath = $this->getLocalizedTemplatePath($skeletonTemplatePath, $userLang);
383
+                if (!empty($localizedSkeletonTemplatePath) && file_exists($localizedSkeletonTemplatePath)) {
384
+                    \OC_Util::copyr($localizedSkeletonTemplatePath, $folder);
385
+                    $userFolder->getStorage()->getScanner()->scan($folder->getInternalPath(), Scanner::SCAN_RECURSIVE);
386
+                    $this->setTemplatePath($userTemplatePath);
387
+                    return $userTemplatePath;
388
+                }
389
+            }
390
+
391
+            if ($path !== null && $isDefaultSkeleton && $isDefaultTemplates && $folderIsEmpty) {
392
+                $localizedSkeletonPath = $this->getLocalizedTemplatePath($skeletonPath . '/Templates', $userLang);
393
+                if (!empty($localizedSkeletonPath) && file_exists($localizedSkeletonPath)) {
394
+                    \OC_Util::copyr($localizedSkeletonPath, $folder);
395
+                    $userFolder->getStorage()->getScanner()->scan($folder->getInternalPath(), Scanner::SCAN_RECURSIVE);
396
+                    $this->setTemplatePath($userTemplatePath);
397
+                    return $userTemplatePath;
398
+                }
399
+            }
400
+
401
+            $this->setTemplatePath($path ?? '');
402
+            return $this->getTemplatePath();
403
+        } catch (\Throwable $e) {
404
+            $this->logger->error('Failed to initialize templates directory to user language ' . $userLang . ' for ' . $userId, ['app' => 'files_templates', 'exception' => $e]);
405
+        }
406
+        $this->setTemplatePath('');
407
+        return $this->getTemplatePath();
408
+    }
409
+
410
+    private function getLocalizedTemplatePath(string $skeletonTemplatePath, string $userLang) {
411
+        $localizedSkeletonTemplatePath = str_replace('{lang}', $userLang, $skeletonTemplatePath);
412
+
413
+        if (!file_exists($localizedSkeletonTemplatePath)) {
414
+            $dialectStart = strpos($userLang, '_');
415
+            if ($dialectStart !== false) {
416
+                $localizedSkeletonTemplatePath = str_replace('{lang}', substr($userLang, 0, $dialectStart), $skeletonTemplatePath);
417
+            }
418
+            if ($dialectStart === false || !file_exists($localizedSkeletonTemplatePath)) {
419
+                $localizedSkeletonTemplatePath = str_replace('{lang}', 'default', $skeletonTemplatePath);
420
+            }
421
+        }
422
+
423
+        return $localizedSkeletonTemplatePath;
424
+    }
425 425
 }
Please login to merge, or discard this patch.