-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
FileTrait.php
322 lines (272 loc) · 8.53 KB
/
FileTrait.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
<?php
declare(strict_types=1);
namespace DrevOps\BehatSteps;
use Behat\Behat\Hook\Scope\AfterScenarioScope;
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
use Behat\Gherkin\Node\TableNode;
use Drupal\Core\File\FileExists;
use Drupal\Core\File\FileSystemInterface;
use Drupal\file\FileInterface;
use Symfony\Component\Filesystem\Filesystem;
/**
* Trait FileTrait.
*
* File-related steps.
*
* @package DrevOps\BehatSteps
*/
trait FileTrait {
/**
* Files entities.
*
* @var array<int,FileInterface>
*/
protected $fileEntities = [];
/**
* Unmanaged file URIs.
*
* @var array<int,string>
*/
protected $filesUnmanagedUris = [];
/**
* Ensures private and temp directories exist.
*
* @BeforeScenario
*/
public function fileBeforeScenarioInit(BeforeScenarioScope $scope): void {
// Allow to skip this by adding a tag.
if ($scope->getScenario()->hasTag('behat-steps-skip:' . __FUNCTION__)) {
return;
}
$fs = new Filesystem();
$dir = \Drupal::service('file_system')->realpath('private://');
if ($dir && !$fs->exists($dir)) {
$fs->mkdir($dir);
}
$dir = \Drupal::service('file_system')->realpath('temporary://');
if ($dir && !$fs->exists($dir)) {
$fs->mkdir($dir);
}
}
/**
* Create managed file with properties provided in the table.
*
* @Given managed file:
*/
public function fileCreateManaged(TableNode $nodesTable): void {
foreach ($nodesTable->getHash() as $nodeHash) {
$node = (object) $nodeHash;
$this->fileCreateManagedSingle($node);
}
}
/**
* Create a single managed file.
*/
protected function fileCreateManagedSingle(\StdClass $stub): FileInterface {
$this->parseEntityFields('file', $stub);
$saved = $this->fileCreateEntity($stub);
$this->fileEntities[] = $saved;
return $saved;
}
/**
* Create file entity.
*
* @param \StdClass $stub
* Stub object.
*
* @return \Drupal\file\FileInterface
* Created file entity.
*
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
protected function fileCreateEntity(\StdClass $stub): FileInterface {
if (empty($stub->path)) {
throw new \RuntimeException('"path" property is required');
}
$path = ltrim($stub->path, '/');
// Get fixture file path.
if (!empty($this->getMinkParameter('files_path'))) {
$full_path = rtrim((string) realpath($this->getMinkParameter('files_path')), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $path;
if (is_file($full_path)) {
$path = $full_path;
}
}
if (!is_readable($path)) {
throw new \RuntimeException('Unable to find file ' . $path);
}
$destination = 'public://' . basename($path);
if (!empty($stub->uri)) {
$destination = $stub->uri;
$directory = dirname($destination);
$dir = \Drupal::service('file_system')->prepareDirectory($directory, FileSystemInterface::CREATE_DIRECTORY + FileSystemInterface::MODIFY_PERMISSIONS);
if (!$dir) {
throw new \RuntimeException('Unable to prepare directory ' . $directory);
}
}
$content = file_get_contents($path);
if ($content === FALSE) {
throw new \RuntimeException('Unable to read file ' . $path);
}
$entity = \Drupal::service('file.repository')->writeData($content, $destination, FileExists::Replace);
$fields = get_object_vars($stub);
foreach ($fields as $property => $value) {
// If path or URI has been specified then the value has already been
// handled.
if (in_array($property, ['path', 'uri'])) {
continue;
}
$entity->set($property, $value);
}
$entity->save();
return $entity;
}
/**
* Clean all created managed files after scenario run.
*
* @AfterScenario
*/
public function fileCleanAll(AfterScenarioScope $scope): void {
// Allow to skip this by adding a tag.
if ($scope->getScenario()->hasTag('behat-steps-skip:' . __FUNCTION__)) {
return;
}
foreach ($this->fileEntities as $file) {
$file->delete();
}
foreach ($this->filesUnmanagedUris as $uri) {
@unlink($uri);
}
$this->fileEntities = [];
}
/**
* Delete managed files defined by provided properties/fields.
*
* Example: filename, uri, status, uid and more.
*
* @see Drupal\file\Entity\File
*
* @code
* Given no managed files:
* | filename |
* | myfile.jpg |
* | otherfile.jpg |
* @endcode
*
* @code
* Given no managed files:
* | uri |
* | public://myfile.jpg |
* | public://otherfile.jpg |
* @endcode
*
* @Given no managed files:
*/
public function fileDeleteManagedFiles(TableNode $nodesTable): void {
$storage = \Drupal::entityTypeManager()->getStorage('file');
$field_values = $nodesTable->getColumn(0);
// Get field name of the column header.
$field_name = array_shift($field_values);
if (is_numeric($field_name)) {
throw new \RuntimeException('The first column should be the field name');
}
$field_name = (string) $field_name;
foreach ($field_values as $field_value) {
$ids = $this->fileLoadMultiple([$field_name => (string) $field_value]);
$entities = $storage->loadMultiple($ids);
$storage->delete($entities);
}
}
/**
* Load multiple files with specified conditions.
*
* @param array<string, string> $conditions
* Conditions keyed by field names.
*
* @return array<int, string>
* Array of file ids.
*/
protected function fileLoadMultiple(array $conditions = []): array {
$query = \Drupal::entityQuery('file')->accessCheck(FALSE);
foreach ($conditions as $k => $v) {
$and = $query->andConditionGroup();
$and->condition($k, $v);
$query->condition($and);
}
return $query->execute();
}
/**
* Create an unmanaged file with specified content.
*
* @Given unmanaged file :uri created
*/
public function fileCreateUnmanaged(string $uri, string $content = 'test'): void {
$directory = \Drupal::service('file_system')->dirname($uri);
if (!file_exists($directory)) {
$dir = \Drupal::service('file_system')->prepareDirectory($directory, FileSystemInterface::CREATE_DIRECTORY + FileSystemInterface::MODIFY_PERMISSIONS);
if (!$dir) {
throw new \RuntimeException('Unable to prepare directory ' . $directory);
}
}
file_put_contents($uri, $content);
$this->filesUnmanagedUris[] = $uri;
}
/**
* Create an unmanaged file with specified content.
*
* @Given unmanaged file :uri created with content :content
*/
public function fileCreateUnmanagedWithContent(string $uri, string $content): void {
$this->fileCreateUnmanaged($uri, $content);
}
/**
* Assert that an unmanaged file with specified URI exists.
*
* @Then unmanaged file :uri exists
*/
public function fileAssertUnmanagedExists(string $uri): void {
if (!@file_exists($uri)) {
throw new \Exception(sprintf('The file %s does not exist.', $uri));
}
}
/**
* Assert that an unmanaged file with specified URI does not exist.
*
* @Then unmanaged file :uri does not exist
*/
public function fileAssertUnmanagedNotExists(string $uri): void {
if (@file_exists($uri)) {
throw new \Exception(sprintf('The file %s exists but it should not.', $uri));
}
}
/**
* Assert that an unmanaged file exists and has specified content.
*
* @Then unmanaged file :uri has content :content
*/
public function fileAssertUnmanagedHasContent(string $uri, string $content): void {
$this->fileAssertUnmanagedExists($uri);
$file_content = @file_get_contents($uri);
if ($file_content === FALSE) {
throw new \Exception(sprintf('Unable to read file %s.', $uri));
}
if (!str_contains($file_content, $content)) {
throw new \Exception(sprintf('File contents "%s" does not contain "%s".', $file_content, $content));
}
}
/**
* Assert that an unmanaged file exists and does not have specified content.
*
* @Then unmanaged file :uri does not have content :content
*/
public function fileAssertUnmanagedHasNoContent(string $uri, string $content): void {
$this->fileAssertUnmanagedExists($uri);
$file_content = @file_get_contents($uri);
if ($file_content === FALSE) {
throw new \Exception(sprintf('Unable to read file %s.', $uri));
}
if (str_contains($file_content, $content)) {
throw new \Exception(sprintf('File contents "%s" contains "%s", but should not.', $file_content, $content));
}
}
}