1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10:
11:
12: namespace Symfony\Component\HttpFoundation\File;
13:
14: use Symfony\Component\HttpFoundation\File\Exception\FileException;
15: use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException;
16: use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesser;
17: use Symfony\Component\HttpFoundation\File\MimeType\ExtensionGuesser;
18:
19: 20: 21: 22: 23: 24: 25:
26: class File extends \SplFileInfo
27: {
28: 29: 30: 31: 32: 33: 34: 35: 36: 37:
38: public function __construct($path, $checkPath = true)
39: {
40: if ($checkPath && !is_file($path)) {
41: throw new FileNotFoundException($path);
42: }
43:
44: parent::__construct($path);
45: }
46:
47: 48: 49: 50: 51: 52: 53: 54: 55:
56: public function guessExtension()
57: {
58: $type = $this->getMimeType();
59: $guesser = ExtensionGuesser::getInstance();
60:
61: return $guesser->guess($type);
62: }
63:
64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74:
75: public function getMimeType()
76: {
77: $guesser = MimeTypeGuesser::getInstance();
78:
79: return $guesser->guess($this->getPathname());
80: }
81:
82: 83: 84: 85: 86: 87: 88: 89: 90:
91: public function getExtension()
92: {
93: return pathinfo($this->getBasename(), PATHINFO_EXTENSION);
94: }
95:
96: 97: 98: 99: 100: 101: 102: 103: 104: 105: 106: 107:
108: public function move($directory, $name = null)
109: {
110: $target = $this->getTargetFile($directory, $name);
111:
112: if (!@rename($this->getPathname(), $target)) {
113: $error = error_get_last();
114: throw new FileException(sprintf('Could not move the file "%s" to "%s" (%s)', $this->getPathname(), $target, strip_tags($error['message'])));
115: }
116:
117: @chmod($target, 0666 & ~umask());
118:
119: return $target;
120: }
121:
122: protected function getTargetFile($directory, $name = null)
123: {
124: if (!is_dir($directory)) {
125: if (false === @mkdir($directory, 0777, true)) {
126: throw new FileException(sprintf('Unable to create the "%s" directory', $directory));
127: }
128: } elseif (!is_writable($directory)) {
129: throw new FileException(sprintf('Unable to write in the "%s" directory', $directory));
130: }
131:
132: $target = $directory.DIRECTORY_SEPARATOR.(null === $name ? $this->getBasename() : $this->getName($name));
133:
134: return new File($target, false);
135: }
136:
137: 138: 139: 140: 141: 142: 143:
144: protected function getName($name)
145: {
146: $originalName = str_replace('\\', '/', $name);
147: $pos = strrpos($originalName, '/');
148: $originalName = false === $pos ? $originalName : substr($originalName, $pos + 1);
149:
150: return $originalName;
151: }
152: }
153: