This repository has been archived by the owner on Jan 21, 2020. It is now read-only.
/
File.php
428 lines (385 loc) · 12.9 KB
/
File.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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
<?php
class CM_File extends CM_Class_Abstract implements CM_Comparable {
/** @var string */
private $_path;
/** @var CM_File_Filesystem */
protected $_filesystem;
/**
* @param string|CM_File $path Path to file
* @param CM_File_Filesystem|null $filesystem
* @throws CM_Exception_Invalid
*/
public function __construct($path, CM_File_Filesystem $filesystem = null) {
if ($path instanceof CM_File) {
/** @var CM_File $path */
$filesystem = $path->_filesystem;
$path = $path->getPath();
}
if (null === $filesystem) {
$filesystem = self::getFilesystemDefault();
}
$this->_filesystem = $filesystem;
$this->_path = CM_File_Filesystem::normalizePath($path);
}
/**
* @return string File path
*/
public function getPath() {
return $this->_path;
}
/**
* @return string File name
*/
public function getFileName() {
return pathinfo($this->getPath(), PATHINFO_BASENAME);
}
/**
* @return string
*/
public function getFileNameWithoutExtension() {
return pathinfo($this->getPath(), PATHINFO_FILENAME);
}
/**
* @return int
*/
public function getSize() {
return $this->_filesystem->getSize($this->getPath());
}
/**
* @return string File mime type
* @throws CM_Exception
*/
public function getMimeType() {
if ($mimeType = self::findMimeTypeByExtension($this->getExtension())) {
return $mimeType;
}
try {
return self::getMimeTypeByContent($this->read());
} catch (CM_Exception $ex) {
throw new CM_Exception('Cannot detect FILEINFO_MIME of file', null, ['path' => $this->getPath()]);
}
}
/**
* @return string|null
*/
public function getExtension() {
$fileName = $this->getFileName();
if (false === strpos($fileName, '.')) {
return null;
}
return strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
}
/**
* @return int
*/
public function getModified() {
return $this->_filesystem->getModified($this->getPath());
}
/**
* @return string MD5-hash of file contents
*/
public function getHash() {
return $this->_filesystem->getChecksum($this->getPath());
}
/**
* @return bool
*/
public function exists() {
return $this->_filesystem->exists($this->getPath());
}
/**
* @return bool
*/
public function isDirectory() {
return $this->_filesystem->isDirectory($this->getPath());
}
/**
* @param boolean|null $noRecursion
* @return CM_File[]
*/
public function listFiles($noRecursion = null) {
$result = $this->_filesystem->listByPrefix($this->getPath(), $noRecursion);
return \Functional\map(array_merge($result['dirs'], $result['files']), function ($path) {
return new CM_File($path, $this->_filesystem);
});
}
/**
* @return string
*/
public function read() {
$cache = CM_Cache_Storage_Runtime::getInstance();
if (false === ($content = $cache->get($this->_getCacheKeyContent()))) {
$content = $this->_filesystem->read($this->getPath());
$cache->set($this->_getCacheKeyContent(), $content, 1);
}
return $content;
}
/**
* @return string
*/
public function readFirstLine() {
$content = $this->read();
if (false !== ($firstLineEnd = strpos($content, "\n"))) {
$content = substr($content, 0, $firstLineEnd + 1);
}
return $content;
}
/**
* @param string $content
*/
public function write($content) {
$this->_filesystem->write($this->getPath(), $content);
$cache = CM_Cache_Storage_Runtime::getInstance();
$cache->set($this->_getCacheKeyContent(), $content, 1);
}
/**
* @param string $content
*/
public function append($content) {
$this->_filesystem->append($this->getPath(), $content);
$cache = CM_Cache_Storage_Runtime::getInstance();
$cache->delete($this->_getCacheKeyContent());
}
/**
* @param string|null $content
*/
public function appendLine($content = null) {
$this->append($content . PHP_EOL);
}
public function truncate() {
$this->write('');
}
/**
* @param string $path
*/
public function copy($path) {
$this->_filesystem->copy($this->getPath(), $path);
}
/**
* @param CM_File $file
*/
public function copyToFile(CM_File $file) {
$filesystemSource = $this->_filesystem;
$filesystemDestination = $file->_filesystem;
$adapterSource = $filesystemSource->getAdapter();
$adapterDestination = $filesystemDestination->getAdapter();
if ($filesystemSource->equals($filesystemDestination)) {
$this->copy($file->getPath());
} elseif ($adapterSource instanceof CM_File_Filesystem_Adapter_StreamInterface &&
$adapterDestination instanceof CM_File_Filesystem_Adapter_StreamInterface
) {
$this->_copyToFileStreaming($file, $adapterSource, $adapterDestination);
} else {
$file->write($this->read());
}
}
/**
* @param string $path
*/
public function rename($path) {
$path = (string) $path;
$this->_filesystem->rename($this->getPath(), $path);
$this->_path = $path;
}
/**
* @param bool|null $recursive
*/
public function delete($recursive = null) {
if ($recursive) {
$this->_filesystem->deleteByPrefix($this->getPath());
}
$this->_filesystem->delete($this->getPath());
$cache = CM_Cache_Storage_Runtime::getInstance();
$cache->delete($this->_getCacheKeyContent());
}
/**
* @return CM_File
*/
public function getParentDirectory() {
return new CM_File(dirname($this->getPath()), $this->_filesystem);
}
public function ensureParentDirectory() {
$parentDirectory = $this->getParentDirectory();
$this->_filesystem->ensureDirectory($parentDirectory->getPath());
}
/**
* @param string $path
* @return static
*/
public function joinPath($path) {
$path = implode('/', func_get_args());
$pathNew = CM_File_Filesystem::normalizePath($this->getPath() . '/' . $path);
return new static($pathNew, $this->_filesystem);
}
/**
* @return string
* @throws CM_Exception_Invalid
*/
public function getPathOnLocalFilesystem() {
$filesystemAdapter = $this->_filesystem->getAdapter();
if (!$filesystemAdapter instanceof CM_File_Filesystem_Adapter_Local) {
throw new CM_Exception_Invalid('Unexpected filesystem with adapter.', null, ['adapter' => get_class($filesystemAdapter)]);
}
return $filesystemAdapter->getPathPrefix() . $this->getPath();
}
/**
* @return string
*/
private function _getCacheKeyContent() {
return __CLASS__ . '_content_filesystem:' . get_class($this->_filesystem->getAdapter()) . '_path:' . $this->getPath();
}
/**
* @param string $path
* @param string|null $content
* @param CM_File_Filesystem|null $filesystem
* @return static
*/
public static function create($path, $content = null, CM_File_Filesystem $filesystem = null) {
$content = (string) $content;
if (null === $filesystem) {
$filesystem = self::getFilesystemDefault();
}
$filesystem->write($path, $content);
return new static($path, $filesystem);
}
/**
* @param string|null $content
* @param string|null $extension
* @return static
*/
public static function createTmp($extension = null, $content = null) {
if (null !== $extension) {
$extension = '.' . $extension;
}
$extension = (string) $extension;
$filesystem = CM_Service_Manager::getInstance()->getFilesystems()->getTmp();
return static::create(uniqid() . $extension, $content, $filesystem);
}
/**
* @return CM_File
*/
public static function createTmpDir() {
$filesystem = CM_Service_Manager::getInstance()->getFilesystems()->getTmp();
$dir = new CM_File(uniqid(), $filesystem);
$filesystem->ensureDirectory($dir->getPath());
return $dir;
}
/**
* taken from http://stackoverflow.com/a/2668953
*
* @param string $filename
* @return string
* @throws CM_Exception_Invalid
*/
public static function sanitizeFilename($filename) {
$filename = (string) $filename;
$strip = array("~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "=", "+", "[", "{", "]", "}", "\\", "|", ";", ":", "\"", "'",
"‘", "’", "“", "”", "–", "—", "—", "–", ",", "<", ">", "/", "?", "\0");
$clean = trim(str_replace($strip, '', $filename));
$clean = preg_replace('/\s+/', "-", $clean);
if (empty($clean)) {
throw new CM_Exception_Invalid('Invalid filename.');
}
return $clean;
}
/**
* @param string $content
* @return string
* @throws CM_Exception
*/
public static function getMimeTypeByContent($content) {
$info = new finfo(FILEINFO_MIME);
$infoFile = $info->buffer($content);
if (false === $infoFile) {
throw new CM_Exception('Cannot detect FILEINFO_MIME');
}
$mime = explode(';', $infoFile);
return $mime[0];
}
/**
* @param string $extension
* @return string|null
*/
public static function findMimeTypeByExtension($extension) {
$extension = strtolower($extension);
$mimeType = null;
$extensionToMimeType = [
'js' => 'text/javascript',
];
if (array_key_exists($extension, $extensionToMimeType)) {
$mimeType = $extensionToMimeType[$extension];
}
return $mimeType;
}
/**
* @param string $path
* @return CM_File
*/
public static function factory($path) {
$extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
switch ($extension) {
case 'php':
return new CM_File_Php($path);
case 'js':
return new CM_File_Javascript($path);
case 'csv':
return new CM_File_Csv($path);
default:
return new CM_File($path);
}
}
/**
* @return CM_File_Filesystem
*/
public static function getFilesystemDefault() {
static $filesystem;
if (null === $filesystem) {
$adapter = new CM_File_Filesystem_Adapter_Local();
$filesystem = new CM_File_Filesystem($adapter);
}
return $filesystem;
}
/**
* @param CM_Comparable $other
* @return boolean
*/
public function equals(CM_Comparable $other = null) {
if (empty($other)) {
return false;
}
/** @var CM_File $other */
$samePath = $this->getPath() === $other->getPath();
$sameFilesystemAdapter = $this->_filesystem->equals($other->_filesystem);
return ($samePath && $sameFilesystemAdapter);
}
/**
* @param CM_File $file
* @param CM_File_Filesystem_Adapter $adapterSource
* @param CM_File_Filesystem_Adapter $adapterDestination
* @throws CM_Exception
*/
protected function _copyToFileStreaming(CM_File $file, CM_File_Filesystem_Adapter $adapterSource, CM_File_Filesystem_Adapter $adapterDestination) {
/** @var CM_File_Filesystem_Adapter_StreamInterface $adapterSource */
/** @var CM_File_Filesystem_Adapter_StreamInterface $adapterDestination */
$streamSource = $adapterSource->getStreamRead($this->getPath());
$adapterDestination->writeStream($file->getPath(), $streamSource);
$sizeDestination = $file->getSize();
$sizeSource = $this->getSize();
if ($sizeSource !== $sizeDestination) {
throw new CM_Exception('Copy failed', null, [
'Source' => $this->getPath(),
'Destination' => $file->getPath(),
'Original size' => $sizeSource,
'Bytes copied' => $sizeDestination,
'Source adapter' => get_class($adapterSource),
'Destination adapter' => get_class($adapterDestination),
]);
}
if (is_resource($streamSource) && !@fclose($streamSource)) {
throw new CM_Exception('Could not close stream for path', null, [
'path' => $this->getPath(),
'Source adapter' => get_class($adapterSource),
]);
}
}
}