Elgg  Version 4.3
MimeTypeService.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Elgg\Filesystem;
4 
7 
14 
15  protected $hooks;
16 
23  $this->hooks = $hooks;
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->hooks->trigger('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 (0 === strpos($mimetype, 'text/') || false !== strpos($mimetype, 'opendocument')) {
81  $result = 'document';
82  }
83 
84  $params = [
85  'mime_type' => $mimetype,
86  ];
87  return $this->hooks->trigger('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:31
Exception thrown if an argument is not of the expected type.
$params
Saves global plugin settings.
Definition: save.php:13
getSimpleType(string $mimetype, string $default= 'general')
Returns the category of a file from its MIME type.
__construct(PluginHooksService $hooks)
Constructor.
getMimeType(string $filename, string $default=MimeTypeDetector::DEFAULT_TYPE)
Get the mimetype for a given filename.
Detect the MIME type of a file.
$filename
Public service related to MIME type detection.
getSimpleTypeFromFile(string $filename, string $default= 'general')
Returns the category of a file from a filename.