Elgg  Version 6.0
MimeTypeService.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Elgg\Filesystem;
4 
7 
14 
20  public function __construct(protected EventsService $events) {
21  }
22 
32  public function getMimeType(string $filename, string $default = MimeTypeDetector::DEFAULT_TYPE): string {
33  if (!is_file($filename) || !is_readable($filename)) {
34  throw new InvalidArgumentException("The file '{$filename}' is not a valid file or is not readable");
35  }
36 
37  $detector = new MimeTypeDetector();
38 
39  $mime = $detector->getType($filename, $default);
40 
41  $params = [
42  'filename' => $filename,
43  'original_filename' => basename($filename),
44  'default' => $default,
45  ];
46 
47  return $this->events->triggerResults('mime_type', 'file', $params, $mime);
48  }
49 
58  public function getSimpleType(string $mimetype, string $default = 'general'): string {
59  $result = $default;
60 
61  switch ($mimetype) {
62  case 'application/msword':
63  case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
64  case 'application/pdf':
65  $result = 'document';
66  break;
67  case 'application/ogg':
68  $result = 'audio';
69  break;
70  }
71 
72  $matches = [];
73  if (preg_match('~^(audio|image|video)/~', $mimetype, $matches)) {
74  $result = $matches[1];
75  }
76 
77  if (str_starts_with($mimetype, 'text/') || str_contains($mimetype, 'opendocument')) {
78  $result = 'document';
79  }
80 
81  $params = [
82  'mime_type' => $mimetype,
83  ];
84  return $this->events->triggerResults('simple_type', 'file', $params, $result);
85  }
86 
95  public function getSimpleTypeFromFile(string $filename, string $default = 'general'): string {
96  $mimetype = $this->getMimeType($filename);
97 
98  return $this->getSimpleType($mimetype, $default);
99  }
100 }
$default
Definition: checkbox.php:30
Exception thrown if an argument is not of the expected type.
$params
Saves global plugin settings.
Definition: save.php:13
Events service.
getSimpleType(string $mimetype, string $default= 'general')
Returns the category of a file from its MIME type.
getMimeType(string $filename, string $default=MimeTypeDetector::DEFAULT_TYPE)
Get the mimetype for a given filename.
__construct(protected EventsService $events)
Constructor.
Detect the MIME type of a file.
Public service related to MIME type detection.
getSimpleTypeFromFile(string $filename, string $default= 'general')
Returns the category of a file from a filename.