Elgg  Version 5.1
MimeTypeService.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Elgg\Filesystem;
4 
7 
14 
15  protected $events;
16 
22  public function __construct(EventsService $events) {
23  $this->events = $events;
24  }
25 
35  public function getMimeType(string $filename, string $default = MimeTypeDetector::DEFAULT_TYPE): string {
36  if (!is_file($filename) || !is_readable($filename)) {
37  throw new InvalidArgumentException("The file '{$filename}' is not a valid file or is not readable");
38  }
39 
40  $detector = new MimeTypeDetector();
41 
42  $mime = $detector->getType($filename, $default);
43 
44  $params = [
45  'filename' => $filename,
46  'original_filename' => basename($filename),
47  'default' => $default,
48  ];
49 
50  return $this->events->triggerResults('mime_type', 'file', $params, $mime);
51  }
52 
61  public function getSimpleType(string $mimetype, string $default = 'general'): string {
62  $result = $default;
63 
64  switch ($mimetype) {
65  case 'application/msword':
66  case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
67  case 'application/pdf':
68  $result = 'document';
69  break;
70  case 'application/ogg':
71  $result = 'audio';
72  break;
73  }
74 
75  $matches = [];
76  if (preg_match('~^(audio|image|video)/~', $mimetype, $matches)) {
77  $result = $matches[1];
78  }
79 
80  if (str_starts_with($mimetype, 'text/') || str_contains($mimetype, 'opendocument')) {
81  $result = 'document';
82  }
83 
84  $params = [
85  'mime_type' => $mimetype,
86  ];
87  return $this->events->triggerResults('simple_type', 'file', $params, $result);
88  }
89 
98  public function getSimpleTypeFromFile(string $filename, string $default = 'general'): string {
99  $mimetype = $this->getMimeType($filename);
100 
101  return $this->getSimpleType($mimetype, $default);
102  }
103 }
$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
__construct(EventsService $events)
Constructor.
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.
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.