1: <?php
2:
3: /*
4: * This file is part of the Symfony package.
5: *
6: * (c) Fabien Potencier <fabien@symfony.com>
7: *
8: * For the full copyright and license information, please view the LICENSE
9: * file that was distributed with this source code.
10: */
11:
12: namespace Symfony\Component\HttpFoundation\File\MimeType;
13:
14: /**
15: * A singleton mime type to file extension guesser.
16: *
17: * A default guesser is provided.
18: * You can register custom guessers by calling the register()
19: * method on the singleton instance.
20: *
21: * <code>
22: * $guesser = ExtensionGuesser::getInstance();
23: * $guesser->register(new MyCustomExtensionGuesser());
24: * </code>
25: *
26: * The last registered guesser is preferred over previously registered ones.
27: *
28: */
29: class ExtensionGuesser implements ExtensionGuesserInterface
30: {
31: /**
32: * The singleton instance
33: *
34: * @var ExtensionGuesser
35: */
36: private static $instance = null;
37:
38: /**
39: * All registered ExtensionGuesserInterface instances
40: *
41: * @var array
42: */
43: protected $guessers = array();
44:
45: /**
46: * Returns the singleton instance
47: *
48: * @return ExtensionGuesser
49: */
50: public static function getInstance()
51: {
52: if (null === self::$instance) {
53: self::$instance = new self();
54: }
55:
56: return self::$instance;
57: }
58:
59: /**
60: * Registers all natively provided extension guessers
61: */
62: private function __construct()
63: {
64: $this->register(new MimeTypeExtensionGuesser());
65: }
66:
67: /**
68: * Registers a new extension guesser
69: *
70: * When guessing, this guesser is preferred over previously registered ones.
71: *
72: * @param ExtensionGuesserInterface $guesser
73: */
74: public function register(ExtensionGuesserInterface $guesser)
75: {
76: array_unshift($this->guessers, $guesser);
77: }
78:
79: /**
80: * Tries to guess the extension
81: *
82: * The mime type is passed to each registered mime type guesser in reverse order
83: * of their registration (last registered is queried first). Once a guesser
84: * returns a value that is not NULL, this method terminates and returns the
85: * value.
86: *
87: * @param string $mimeType The mime type
88: * @return string The guessed extension or NULL, if none could be guessed
89: */
90: public function guess($mimeType)
91: {
92: foreach ($this->guessers as $guesser) {
93: $extension = $guesser->guess($mimeType);
94:
95: if (null !== $extension) {
96: break;
97: }
98: }
99:
100: return $extension;
101: }
102: }
103: